flutter

Stripe 결제 Flutter 와 연동하기

이나주니 2025. 1. 2. 10:38
반응형

먼저

https://dashboard.stripe.com/

 

Stripe Login | Sign in to the Stripe Dashboard

Incompatible browser You need a modern browser to use the Stripe Dashboard. Please switch to a compatible browser to continue.

dashboard.stripe.com

회원 가입후 API 키를 만들어준다

 

라이브 모드 API 키 설정

API 키에서 public 과 Secret 키를 복사해 둔다

 

flutter 초기화 및 설정

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Stripe.publishableKey =
  'pk_test_51QbwuF79..........';

}

 

테스트 이기 때문에 1 달러만 결제 하도록 만들어 본다

createPaymentIntent('1', 'USD');

 Future<void> makePayment(BuildContext context) async {

    try {
      paymentIntent = await createPaymentIntent('1', 'USD');
      await Stripe.instance.initPaymentSheet(
        paymentSheetParameters: SetupPaymentSheetParameters(
          paymentIntentClientSecret: paymentIntent!['client_secret'],
          googlePay: const PaymentSheetGooglePay(
              testEnv: false, // 테스트 모드
              currencyCode: "USD",
              merchantCountryCode: "US"),
          // Merchant Name
          merchantDisplayName: 'Flutterwings',
        ),
      );
      displayPaymentSheet(context);
    } catch (e) {
      print("exception $e");

      if (e is StripeConfigException) {
        print("Stripe exception ${e.message}");
      } else {
        print("exception $e");
      }
    }
  }

 

 

테스트 모드 관련 설정 제거

기존 코드:

googlePay: const PaymentSheetGooglePay(
  testEnv: true, // 테스트 모드
  currencyCode: "USD",
  merchantCountryCode: "US",
),

 

수정 코드:

googlePay: const PaymentSheetGooglePay(
  testEnv: false, // 테스트 모드 비활성화
  currencyCode: "USD",
  merchantCountryCode: "US",
),

 

 displayPaymentSheet(BuildContext context) async {
    try {
      await Stripe.instance.presentPaymentSheet();
      CommonDialog(text: "결제 성공");
      paymentIntent = null;
    } on StripeException catch (e) {
      print('Error: $e');

      CommonDialog(text: "결제 실패");
    } catch (e) {
      print('$e');
    }
  }

 

결제 요청 

secretKey 는 Stripe사이트에서 복사해둔 값을 넣자

결제 금액 처리

'amount': ((int.parse(amount)) * 100).toString(), // USD 기준으로 $1.00은 100 센트

 

 createPaymentIntent(String amount, String currency) async {
    try {
      Map<String, dynamic> body = {
        'amount': ((int.parse(amount)) * 100).toString(),
        'currency': currency,
        'payment_method_types[]': 'card',
      };
      var secretKey =
          "sk_test_...................";
      var response = await http.post(
        Uri.parse('https://api.stripe.com/v1/payment_intents'),
        headers: {
          'Authorization': 'Bearer $secretKey',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: body,
      );
      print('Payment Intent Body: ${response.body.toString()}');
      return jsonDecode(response.body.toString());
    } catch (err) {
      print('Error charging user: ${err.toString()}');
    }
  }

 

 

아래 사이트에서 테스트 관련 내용 확인가능

https://docs.stripe.com/testing

 

Test card numbers

Use test cards to validate your Stripe integration without moving real money. Test a variety of international scenarios, including successful and declined payments, card errors, disputes, and bank authentication. You can also test non-card payment methods

docs.stripe.com

 

테스트 모드 이기 떄문에 결제 정보는 어래 처럼 넣어준다

대화형으로 테스트할 때는 4242 4242 4242 4242 와 같은 카드 번호를 사용하세요 . 대시보드나 모든 결제 양식에 카드 번호를 입력하세요.

  • 12/34 와 같이 유효한 미래 날짜를 사용하세요 .
  • 3자리 CVC를 사용하세요(American Express 카드의 경우 4자리).
  • 다른 양식 필드에는 원하는 값을 사용하세요.

 

 

 

 

 

 

※ 여기서 알아야할점 사업자

한국에서는 stripe를 사용할수 없다는 점이다..

전혀 몰랐던 사실..

사업장이 허용되는 국가만 사용가능하기 때문에

사용하려면 미국에 법인이 있거나 미국 등 다른국가에 페이퍼 컴퍼니를 만드는 경우도 있다고 한다.

하지만 작성이는 그정도 까진 필요없어서 다른 방법을 찾아 보려고 한다!

아래 사진은 사업장등록할때 국가 설정 하는 페이지

참고로 한국은 없다!

반응형