Flutter Paystack 모든 옵션 구현

내용의 테이블


  • 🕹 Introduction
  • 📡 Required Paystack Details and Endpoints
  • 🖲 Installing WebView Package
  • 🛢 Making API calls in Flutter
  • 📲 Displaying Paystack pop-up in webView
  • 💾 Listening For Navigation url

  • 🕹 소개

    As at the time of writing this article, paystack integration for android and mobile SDK, only supports card payments and bank (with just Zenith as the option).

    In this article, you will learn how to include other payment options in your flutter application.

    PS: I'm assuming you are familiar with flutter and 
    paystack with all the necessary keys and how to get them 
    from your paystack dashboard.
    
    Before we continue, please take a quick look at this article from Paystack 거기서 아이디어를 얻었어요 😋. 원하는 경우 해당 기사를 사용하거나 계속 읽을 수 있습니다.

    📡 필수 Paystack 세부 정보 및 끝점

    You will need your paystack secret_key (use the test key for testing and live key for prod) as your Bearer token in your Authorization header while making a POST request to the paystack initialize api .

    더 나은 이해를 위해 아래 이미지를 확인하십시오.

    secret_key로 인증 헤더 설정





    POST 본문 세부정보





    email: This is the payers email.
    
    amount: This is the amount to be paid, please multiply by 
            100, to remove the kobo value
    
    reference: This should be randomly generated as it should 
               be a unique value for each payment.
    
    callback_url: This is the most important part. If you 
                  already have a callback url, setup from your 
                  paystack dashboard, you don't need this 
                  parameter. If you still go ahead to include 
                  it, it'll override that of the dashboard. 
                  This callback_url is what we will be 
                  listening for from our webview.
    
    cancel_action: This will be used to listen for when the 
                   user wants to cancel payment, we then pop 
                   the webview screen.
    

    페이 스택 API의 응답





    authorization_url: This is the most important data we will 
                       be needing for our webview, so hold on 
                       to it 😎.
    

    🖲 WebView 패키지 설치

    To install this package, please visit this link 설정을 읽고 설치합니다.

    🛢 Flutter에서 API 호출하기

    This approach depends on which architecture you're using to build your application, at the end, it's all the same response you will receive. In this article, i'll be keeping it really simple 🥹.

    var headers = {
      'Authorization': 'Bearer sk_test_039***************',
      'Content-Type': 'application/json',
    };
    var request = http.Request('POST', Uri.parse('https://api.paystack.co/transaction/initialize'));
    request.body = json.encode({
      "email": "[email protected]",
      "amount": "10000",
      "reference": "randomDetails",
      "callback_url": "https://github.com/gikwegbu",
      "metadata": {"cancel_action": "https://www.google.com/"}
    });
    request.headers.addAll(headers);
    
    http.StreamedResponse response = await request.send();
    
    if (response.statusCode == 200) {
      print(await response.stream.bytesToString());
    }
    else {
      print(response.reasonPhrase);
    }
    
    

    PS: I personally love using the
    flutter dio package

    Retrieve the authorization_url from the response and store 
    it in a global variable.
    

    📲 webView에서 Paystack 팝업 표시하기

    Ok, let's be on the same page here 🙃. We are building an application that allows users make payment for an item via paystack.


    🏳️ 데이터 흐름:

    사용자가 PAY 버튼을 클릭하면 페이 스택이 팝업되고 사용자는 적합한 옵션을 선택하고 진행합니다. 결제가 완료되면 callback_url으로 리디렉션됩니다. 이 일이 발생하면 해당 callback_url을 수신해야 합니다. 이 URL을 감지하면 webview 위젯을 닫은 다음 계속해서 서버에 reference code을 전송하여 PAID 항목의 체크아웃을 완료할 수 있습니다.


    🏳️ 구현:

    프로세스를 원활하게 만들기 위해 팝업 대화 상자를 사용하고 전체 화면으로 설정하여 현재 페이지를 오버레이하고 webview 위젯을 추가합니다.

    다음은 더 많은 것을 이해하는 데 도움이 되는 코드 스니펫입니다.

    
    // This is called when the PAY button is clicked.
    _showPaystack() async {
        var _ref = 'ChargedFromMyApp_${DateTime.now().millisecondsSinceEpoch}';
        Map data = {
          // Removing the kobo by multiplying with 100
          "amount": double.parse('${_amount * 100}').toInt(),
          "email": _user.email,
          "reference": _ref,
          "callback_url": "https://github.com/gikwegbu",
          "metadata": {"cancel_action": "https://www.google.com/"}
        };
        // This awaits the [authorization_url](#authUrl). NB: I'm using the MVVM architecture in my live code, but it's still the same process of retrieving the authURL.
        var authUrl = await _profileCtrl.paystackWebViewChargeCard(data);
    
        // only pull-up the dialog box when we get the authURL
        if (authUrl != null) {
          return showGeneralDialog(
              context: context,
              barrierDismissible: true,
              barrierLabel:
                  MaterialLocalizations.of(context).modalBarrierDismissLabel,
              barrierColor: Colors.black45,
              transitionDuration: const Duration(milliseconds: 200),
              pageBuilder: (BuildContext buildContext, Animation animation,
                  Animation secondaryAnimation) {
                return Center(
                    child: Container(
                  width: MediaQuery.of(context).size.width - 10,
                  // height: MediaQuery.of(context).size.height - 80,
                  height: MediaQuery.of(context).size.height - 0,
                  padding: const EdgeInsets.only(top: 40),
                  color: Colors.white,
                  child: WebView(
                    initialUrl: authUrl.toString(),
                    javascriptMode: JavascriptMode.unrestricted,
                    userAgent: 'Flutter;Webview',
                    navigationDelegate: (navigation) {
                      //Listen for callback URL
                      if (navigation.url == "https://standard.paystack.co/close") {
                        Navigator.of(context).pop(); //close webview
    
                        // _txnRef is my glabally created variable to handle my reference
                        _txnRef = _ref;
                        _submit();
                      }
                      if (navigation.url ==
                          "github.com/gikwegbu?trxref=$_ref&reference=$_ref") {
                        Navigator.of(context).pop();
                        _txnRef = _ref;
                        _submit();
                      }
                      if (navigation.url == "https://www.google.com/") {
                        Navigator.of(context).pop();
                      }
                      return NavigationDecision.navigate;
                    },
                  ),
                ));
              });
        }
      }
    
    



    The _submit(), is a function that sends the reference to 
    my backend to complete the purchase transaction on the
    selected item.

    💾 내비게이션 URL 듣기

    From the above code snippet, you'd have noticed the navigationDelegate section, this is where you'll handle listening for the callback_url and also, in the case the user is making payments with a Card, and the 3Ds Authentication will have to redirect you to the ' https://standard.paystack.co/close '. 그 외에는 사용자 지정 callback_url을 수신한 다음 화면을 표시합니다.

    드디어



    우리는 다중 옵션이 있는 페이스택 결제 시스템을 Flutter 애플리케이션에 성공적으로 통합했습니다. 여러 옵션을 경험하려면 테스트 비밀 키에서 라이브 비밀 키로 변경해야 합니다.

    좋은 웹페이지 즐겨찾기