Flutter Connect

The PortOne Flutter SDK offers merchants a seamless way to integrate the PortOne Payment Gateway into their Flutter applications, enabling them to accept payments securely and efficiently. This SDK serves as a bridge between a merchant's app and the PortOne Payment Gateway, providing a comprehensive set of tools and features tailored specifically for handling payment transactions.

The PortOne Flutter SDK empowers merchants to unlock the full potential of their Flutter applications by seamlessly integrating a reliable and secure payment gateway, enhancing user experience, and driving business growth through efficient payment processing capabilities


Video Tutorial


Sample App

Check the sample app to integrate on GitHub


Prerequisites

  • Create an account on PortOne:
    Before proceeding with the integration, ensure you have created an account on PortOne to access their services and functionalities.
  • Enable Payment Channels and Methods:
    Customize and enable the specific payment channels and methods that align with your business requirements and preferences.
  • Access API Keys
    Login to the portone portal where you can access the API Keys (client key and secret key) for integrations under Settings -> API tab.
  • Flutter application for the integration:
    You will need an Flutter application in which you intend to integrate the PortOne Flutter SDK for payment processing capabilities.

Integration

Steps to integrate your Android application with PortOne Flutter SDK.

  1. Configure the Flutter SDK with the Flutter App
  2. Initialise the PortOne Instance
  3. Set the Intent Filters in the manifests
  4. Add a listener to listen the payment status
  5. Setup to Obtain JWT Token from the Server:
  6. Generate a Signature Hash for Payload

1. Configure the Flutter SDK with the Flutter App

  1. Retrieve the Flutter package distributed by the PortOne team and ensure it is placed at the same directory level as your Flutter application within the folder structure.

  2. To integrate the necessary dependencies in your Flutter project, you can update the pubspec.yaml file with the following configuration:

    dependencies:
      flutter:
        sdk: flutter
      portone_flutter_package:
        path: /Users/flutter_app_sdk/flutter_sdk
      app_links: ^6.1.1
    
    ParametersDescription
    portone_flutter_packageThis is the package where the portone flutter sdk lies and it also has one param name path which requires the path of the sdk.
    In above code the given path is dummy please put the path where your portone sdk lies.
    app_links: ^6.1.1The app_links package plays a crucial role in your application by enabling the reception of intents from deep links or other applications. Its functionality is essential for capturing payment status updates seamlessly within your Flutter app.

2. Initialise the PortOne Instance

  • To facilitate checkout processing within your widget, initialize the PortOneImpl() instance. This instance grants access to the checkout methods necessary for transaction processing.
  • Additionally, ensure to provide the environment parameter (SANDBOX or LIVE) for seamless integration and transaction testing.
String environment = "sandbox";            // For Sandbox
String environment = "live";               // For Live

late PortOneImpl portone;
portone = PortOneImpl(context, environment);


3. Enable deep links

  1. For Android:

    1. Change the project structure to Android from Project or open the android module as project in IDE

    2. To add an Intent Filter to the activity in your AndroidManifest.xml file so that users are navigated to a specific activity (default being Checkout Activity) after payment completion

      <activity android:name=".CheckoutActivity">
          <intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <category android:name="android.intent.category.BROWSABLE" />
              <data
                  android:scheme="portone"
                  android:host="checkout" />
          </intent-filter>
      </activity>
      
      

      In this setup:

      • The <intent-filter> block defines the conditions under which the activity should be launched.
      • The <data> tag specifies the scheme and host required in the incoming Intent for it to be directed to this activity after payment completion.
      • The <activity> tag specifies the activity to which the Intent Filter applies.

    Update the activity name (e.g., .CheckoutActivity) as per your actual activity name and place this Intent Filter configuration within the corresponding <activity> tag in the AndroidManifest.xml file to handle post-payment navigation effectively.

    By configuring the scheme as "portone" and host as "checkout" within the <data> tag of the Intent Filter, your Android application will be able to intercept the redirection URL with the format "portone://checkout" and navigate the user to the specified activity (e.g., CheckoutActivity) after payment completion. Adjust the activity name in the configuration according to your actual activity name for proper redirection handling.

  2. For iOS:

    1. To open your application, add the url schemes to the app, Go to ProjectSettings -> info

    2. Add url schemes and identifier inside the URL types.

      You can see the scheme and identifier details in info.plist as below:

      <key>CFBundleURLTypes</key>
      <array>
      		<dict>
      			<key>CFBundleTypeRole</key>
      			<string>Editor</string>
      			<key>CFBundleURLName</key>
      			<string>checkout</string>
      			<key>CFBundleURLSchemes</key>
      			<array>
      				<string>portone</string>
      			</array>
      		</dict>
      	</array>
      
      
    3. To open the other applications, should include the url schemes in info.plist

      <key>LSApplicationQueriesSchemes</key>
      	<array>
      		<string>itms-appss</string>
      		<string>zalopay</string>
      		<string>line</string>
      		<string>ascendmoney</string>
      	</array>
      
      

      LSApplicationQueriesSchemes - Specifies the URL schemes you want the app to be able to use with the canOpenURL: method of the UIApplication class.


4. Add a listener to listen the payment status by the callback to initState()

  1. Receiving Payment Status:

    a. Set up app-to-app communication to receive a deep link via intent post-checkout.

    b. In the root stateful widget, implement initState() and dispose() methods.

    c. Declare variables:

    late AppLinks _appLinks;
    StreamSubscription<Uri>? _linkSubscription;
    
    
  2. Initialization in initState():

    a. Initialize initState() method to handle payment status reception:

    @override
      void initState() {
        super.initState();
        initDeepLinks();
      }
      
      Future<void> initDeepLinks() async {
        _appLinks = AppLinks();
        _linkSubscription = _appLinks.uriLinkStream.listen((uri) {
          print('onAppLink: $uri');
        });
      }
    
  3. Dispose Method Handling:

    a. To cancel the subscription and avoid memory leaks, implement dispose():

      @override
      void dispose() {
         _linkSubscription?.cancel();
        super.dispose();
      }
    
  4. Adding Payment Status Listener:

    a. Implement the following method in the checkout activity to capture checkout status post-completion:

    portone.setPaymentStatusListener(
            callback: (Map<String, dynamic> paymentStatus) {
          print('PortOne_PaymentStatus-> $paymentStatus');
        });
    
    
  5. Listening to Payment Status on Checkout Activity:

    Implement the following method in the checkout activity to receive and handle the checkout status post-completion:

    portone.setPaymentStatusListener(
        callback: (Map<String, dynamic> paymentStatus) {
            print('PortOne_PaymentStatus-> $paymentStatus');
        });
    
    

    By integrating this method, you can effectively capture and process the payment status updates within the checkout activity using the PortOne SDK in your Flutter application.


5. Have a setup to get JWT token from the server

To set up the process of obtaining a JWT token from the server, you need to construct a JWT token that accepts the portoneKey as input. Here's an outline of the steps involved in setting up this process:

  1. JWT Token Construction:

    Implement the server-side logic to generate a JWT token using the portoneKey as a key component of the token payload.

  2. Token Retrieval in Android App:

    • Implement logic in your Android application to make a server request to retrieve the JWT token using the portoneKey.
    • Receive and store the returned token securely within the app for subsequent API authentication.

Authentication | PortOne


6. Generate Signature Hash

To generate a signature hash on the server side using a secret key that will be included in the payload.

Payment Request | PortOne


Flutter Connect

Flutter SDK Flutter Connect empowers merchants with advanced business logic functionalities, focusing solely on core processing capabilities without the inclusion of pre-built user interface components. This design choice offers flexibility to merchants, allowing them the freedom to craft and customize their own unique checkout interface tailored to their brand aesthetics and user experience preferences.

The Flutter SDK V2 provides a detailed breakdown of key functionalities essential for merchants to enhance their payment processing capabilities efficiently. Each point represents a specific feature or action that can be easily referenced for seamless integration and utilization within merchant applications.

Overview:

  1. Fetch Enabled Payment Methods and Channels
  2. Checkout Using a New Credit/Debit Card
  3. Checkout Using Saved Credit/Debit Cards
    1. Retrieve Saved Cards Using Phone Number
      1. Fetch OTP for Authentication
      2. Fetch Saved Cards Using Phone Number and OTP
    2. Retrieve Saved Cards Using Auth Token
  4. Checkout Using Non-Tokenized Methods
    1. Instalments
    2. Direct Bank Transfer
  5. Merchant Centric Card Vault
    1. Create a Customer
    2. Save a Card for Customer
    3. Fetch a List of Cards for a Customer
    4. Delete Card for a Customer
  6. PreAuth and Capture
  7. Failover Routing

The subsequent methods are elaborated upon extensively, including their practical applications:

  1. This method is utilized to retrieve the available payment channels and methods that can be used for the checkout process.

    ParametersData Type
    portoneKeyStringmandatory
    currencyStringmandatory
     portone.getPaymentMethods(
                          portoneKey, currency);
    

    For receiving the response, the following listener needs to be added.

     portone.setPaymentMethodsListener(
            callback: (PaymentMethodResponse response) {
          final json = jsonEncode(response);
          print('Response-> $response--> $json');
        });
    
  2. This method is employed to initiate the checkout process with a new card, allowing for payment from a card that has not been saved previously.

    portone.checkoutUsingNewCard(
                          WithTokenizationRequest(),
                          ChanexTokenRequest(),
                          jwtToken);
    

    jwtToken

    The jwtToken serves as the authentication mechanism in the API, generated following the guidelines outlined in the integration documentation.

    ChanexTokenRequest()

    ParametersData Type
    cardNumberStringmandatory
    cardTypeStringmandatory
    cardholderNameStringmandatory
    serviceCodeStringmandatory
    expiryYearStringmandatory
    expiryMonthStringmandatory
    environmentStringmandatory
    portoneKeyStringmandatory

    WithTokenizationRequest

    ParametersData Type
    portoneKeyStringmandatory
    paymentChannelStringmandatory
    paymentMethodStringmandatory
    merchantOrderIdStringmandatory
    amountDoublemandatory
    currencyStringmandatory
    billingDetailsCheckoutPaymentDto.BillingDetailsOptional
    shippingDetailsCheckoutPaymentDto.ShippingDetailsOptional
    orderDetailsList<CheckoutPaymentDto.OrderDetail>Optional
    successUrlStringmandatory
    failureUrlStringmandatory
    environmentStringmandatory
    signatureHashStringmandatory
    redirectUrlStringmandatory
    descriptionStringOptional
    sourceStringmandatory
    transactionTypeStringmandatory

    For receiving the response, the following listener needs to be added.

     portone.setCheckoutWithTokenizationListener(
            callback: (WithTokenizationResponse response) {
          final json = jsonEncode(response);
          print('Response-> $response--> $json');
        });
    
  3. To make a payment using saved cards for the first time, the following method facilitates fetching the cards linked to the phone number. However, to access the cards, OTP authentication is necessary, requiring a two-step process.

    1. Retrieving the saved cards for the initial occurrence.

      1. This method is employed to send an OTP to the registered phone number.

        ParametersData Type
        phoneNoStringmandatory
        portone.getOTP(phoneNo);
        
      2. Upon completing the previous step, an OTP will be sent to the phone number, serving as the input for subsequent authentication.

        ParametersData Type
        tokenStringOptional
        portoneKeyStringmandatory
        phoneNoStringmandatory
        otpStringmandatory
        portone.getSavedCards(null, portoneKey, phoneNo, otp);
        

        For receiving the response, the following listener needs to be added.

         portone.setSavedCardsListener(
                callback: (CreditCardDetailsResponse response) {
              final json = jsonEncode(response);
              print('Response-> $response--> $json');
            });
        
    2. Retrieving the saved cards repeatedly.
      Following the initial retrieval of saved cards, a token is obtained in the response, offering an alternative method for authentication. This token can be utilised in place of the OTP, providing convenience for subsequent card retrievals.

      ParametersData Type
      tokenStringmandatory
      portoneKeyStringmandatory
      phoneNoStringmandatory
      otpStringOptiona

      portone.getSavedCards(token, portoneKey, phoneNo, null);
      

      For receiving the response, the following listener needs to be added.

       portone.setSavedCardsListener(
              callback: (CreditCardDetailsResponse response) {
            final json = jsonEncode(response);
            print('Response-> $response--> $json');
          });
      
  4. The following method is utilized for processing non-tokenized payment methods, where tokenization is not required for transaction completion. This method facilitates streamlined checkout experiences for payment methods that do not necessitate the tokenization process.

    portone.checkoutWithoutTokenization(
                          WithoutTokenizationRequest());
    

    For the non-tokenized flow, it is necessary to pass an object containing the checkout request details to facilitate the payment process without requiring tokenization.

    WithoutTokenizationRequest()

    ParametersData Type
    portoneKeyStringmandatory
    paymentChannelStringmandatory
    paymentMethodStringmandatory
    merchantOrderIdStringmandatory
    amountDoublemandatory
    currencyStringmandatory
    billingDetailsCheckoutPaymentDto.BillingDetailsOptional
    shippingDetailsCheckoutPaymentDto.ShippingDetailsOptional
    orderDetailsList<CheckoutPaymentDto.OrderDetail>Optional
    successUrlStringmandatory
    failureUrlStringmandatory
    environmentStringmandatory
    signatureHashStringmandatory
    redirectUrlStringmandatory
    descriptionStringOptional
    sourceStringmandatory
    transactionTypeStringmandatory

    The parameters mentioned above are standard for non-tokenized checkout methods. However, additional parameters and steps are required for specific methods such as Direct Bank Transfer and Instalments.


    These methods also fall under the non-tokenized flow but necessitate extra parameters and steps in the request process.

    1. Direct Bank Transfer
    2. Instalments

    These methods, while classified under non-tokenized flows, entail supplementary parameters and steps in the request, as outlined in detail below.

    Direct Bank Transfer

    To process a Direct Bank Transfer checkout, the following steps should be followed:

    1. Fetch Direct Bank Transfer Details:
      Utilise the following method that only requires the portoneKey as input to retrieve the details pertaining to Direct Bank Transfer.

      portOne.getDBTDetails(portoneKey)
      

      For receiving the response, the following listener needs to be added.

       portone.setDBTDetailsListener(callback: (DBTDetailsResponse response) {
            final json = jsonEncode(response);
            print('DBTDetails-> $json');
          });
      
    2. Process Checkout with Bank Details:
      Once the bank details are obtained, incorporate them into the payload for checkout processing.

       portone.checkoutUsingDirectBankTransfer(
                            CheckoutWithDirectBankTransferRequest());
      

      The upcoming request mirrors the structure of the checkout request object without tokenization, with the exception of the final additional object appended to the request.

      PaymentDto.CheckoutWithDirectBankTransferRequest()

      ParametersData Type
      portoneKeyStringmandatory
      paymentChannelStringmandatory
      paymentMethodStringmandatory
      merchantOrderIdStringmandatory
      amountDoublemandatory
      currencyStringmandatory
      billingDetailsCheckoutPaymentDto.BillingDetailsOptional
      shippingDetailsCheckoutPaymentDto.ShippingDetailsOptional
      orderDetailsList<CheckoutPaymentDto.OrderDetail>Optional
      successUrlStringmandatory
      failureUrlStringmandatory
      environmentStringmandatory
      signatureHashStringmandatory
      redirectUrlStringmandatory
      descriptionStringOptional
      sourceStringmandatory
      transactionTypeStringmandatory
      DBTDetailsPaymentDto.DBTDetailsmandatory

      PaymentDto.DBTDetails

      ParametersData Type
      customerNameStringmandatory
      transactionTimeStringmandatory
      amountPaidDoublemandatory

    Instalments

    To initiate an Instalments checkout, the following steps need to be taken:

    1. Retrieve Bank List for Instalments:
      Initially, fetching the bank list that offers instalment options is necessary to process instalment payments.

      portone.getBankList(paymentChannel, BankListRequest());
      

      BankListRequest()

      ParametersData Type
      amountDoublemandatory
      environmentStringmandatory
      portoneKeyStringmandatory
      isMerchantSponsoredBooleanmandatory
      paymentMethodStringmandatory
      overrideDefaultBooleanmandatory
      currencyStringmandatory

      The response will include a list of banks and associated terms which must be included in the request body for further processing.

    2. Request Parameters for Instalments:

      The subsequent request parameters are consistent with the generic checkout request object without tokenization, apart from the addition of a supplementary object for Instalments.

      portone.checkoutUsingInstallation(
                            CheckoutWithInstallationRequest());
      

      PaymentDto.CheckoutWithInstallationRequest()

      ParametersData Type
      portoneKeyStringmandatory
      paymentChannelStringmandatory
      paymentMethodStringmandatory
      merchantOrderIdStringmandatory
      amountDoublemandatory
      currencyStringmandatory
      billingDetailsCheckoutPaymentDto.BillingDetailsOptional
      shippingDetailsCheckoutPaymentDto.ShippingDetailsOptional
      orderDetailsList<CheckoutPaymentDto.OrderDetail>Optional
      successUrlStringmandatory
      failureUrlStringmandatory
      environmentStringmandatory
      signatureHashStringmandatory
      redirectUrlStringmandatory
      descriptionStringOptional
      sourceStringmandatory
      transactionTypeStringmandatory
      bankDetailsPaymentDto.BankDetailsmandatory

      BankDetails

      ParametersData Type
      bankCodeStringmandatory
      bankNameStringmandatory
      isMerchantSponsoredBooleanmandatory
      overrideDefaultBooleanmandatory
      installmentPeriodPaymentDto.TermObjectmandatory

      PaymentDto.TermObject

      ParametersData Type
      monthIntmandatory

For non-tokenized methods such as Direct Bank Transfer and Installments, the method for receiving the response is already included during integration, which is the payment status listener.

Merchant Centric Card Vault

The Merchant Centric Card Vault operates by enrolling merchants initially, followed by adding customers specific to each merchant. Cards are then saved based on individual customers, ensuring a personalized and secure card storage system. Several methods are available to facilitate various operations within this card vault setup.

  1. The subsequent method is utilised for customer addition.

    portone.addCustomer(
                          token,
                          portoneKey,
                          AddCustomerRequest(
                              name,
                              customerRef,
                              email,
                              phoneNo));
    
    ParametersData Type
    tokenStringmandatory
    portoneKeyStringmandatory
    nameStringmandatory
    phoneNoStringmandatory
    emailStringmandatory
    customerRefStringmandatory

    For receiving the response, the following listener needs to be added.

    portone.setAddCustomerListener(callback: (AddCustomerResponse response) {
          final json = jsonEncode(response);
          print('AddCustomer-> $json');
        });
    
  2. The following method is used to save a particular card for a specific customer.

    portone.addCardForCustomer(
                          customerUUID,
                          token,
                          portoneKey,
                          ChanexTokenRequest());
    
    ParametersData Type
    customerUUIDStringmandatory
    tokenStringmandatory
    portoneKeyStringmandatory

    ChanexTokenRequest()

    ParametersData Type
    cardNumberStringmandatory
    cardTypeStringmandatory
    cardholderNameStringmandatory
    serviceCodeStringmandatory
    expiryYearStringmandatory
    expiryMonthStringmandatory
    environmentStringmandatory
    portoneKeyStringmandatory

    For receiving the response, the following listener needs to be added.

    
    portone.setAddCardForCustomerListener(
            callback: (AddCardForCustomerResponse response) {
          final json = jsonEncode(response);
          print('AddCard-> $json');
        });
    
  3. This method is utilized to retrieve the stored cards based on the customer.

      portone.listCardsForCustomer(customerUUID,
                          token, portoneKey);
    
    ParametersData Type
    customerUUIDStringmandatory
    tokenStringmandatory
    portoneKeyStringmandatory

    For receiving the response, the following listener needs to be added.

    portone.setListCardsForCustomerListener(
            callback: (ListCardsForCustomerResponse response) {
          final json = jsonEncode(response);
          print('ListCustomerCards-> $json');
        });
    
  4. This method is employed to remove a specific card for an individual customer.

     portone.deleteCardForCustomer(
                          customerUUID,
                          token,
                          portoneKey,
                          DeleteCardRequest(
                              token: cardToken));
    
    
    ParametersData Type
    customerUUIDStringmandatory
    tokenStringmandatory
    portoneKeyStringmandatory
    ParametersData TypeRemarks
    cardTokenStringmandatoryThe Card Token can be retrieved in the above fetching the list of cards method

    For receiving the response, the following listener needs to be added.

     portone.setDeleteCardForCustomerListener(
            callback: (GenericResponse response) {
          final json = jsonEncode(response);
          print('DeleteCard-> $json');
        });
    
    

Pre Auth and Capture Payment

During Pre-authorization, the transaction is initially approved, and at a later time or within specified days, the payment can be processed using the Capture API.

To designate a transaction for pre-authorization, a specific parameter must be configured in the payload:

transactionType = *PREAUTH*


    WithTokenizationRequest request =
      WithTokenizationRequest(transactionType: "PREAUTH");

📘

💡 Please note that Pre-authorization is applicable only for credit card payments with a smooth workflow.

Following the pre-authorization of a transaction, the subsequent method is utilized for capturing the transaction.

portone.captureTransaction(orderReference,
                      token, portoneKey);
ParametersData Type
orderReferenceStringmandatory
portoneKeyStringmandatory
tokenStringmandatory

For receiving the response, the following listener needs to be added.

portone.setCaptureTransactionListener(callback: (GenericResponse response) {
  final json = jsonEncode(response);
  print('CapturedTransaction-> $json');
});

Failover Routing

Failover routing is a feature developed for the seamless credit card payment methods. In this feature we set up primary and secondary payment channel from the admin portal so that while paying using one payment channel is not successful due to any reason, it will take user directly to the secondary payment channel.

Following method is used to fetch routes created in admin portal.

portOne.getRoutesList(
                token = token,
                portoneKey = portoneKey,
                object : ApiCallbackInterface<PaymentDto.RoutesListResponse> {
                    override fun onSucceed(response: PaymentDto.RoutesListResponse) {
                        val gson = Gson()
                        val json = gson.toJson(response)
                        LoggerUtil.info("Successful")
                    }

                    override fun onFailure(
                        errorCode: Int?,
                        status: String?,
                        errorMessage: String,
                        throwable: Throwable
                    ) {
                        LoggerUtil.info("Failed")
                    }

                })

This method provides the routeRef that should be included in the payload as outlined below:

  1. Enable routing by setting isRoutingEnabled to true.
  2. Specify the Routing Param type as failover.
  3. Include the Routing Ref, which is configured in the merchant portal.

    val paymentDetails = PaymentDto.CheckoutUsingTokenizationRequest()
    paymentDetails.isRoutingEnabled= true     // true || false
    paymentDetails.routingParams= PaymentDto.RoutingParams(type = "failover", routeRef)

Possible Error Scenarios:

INVALID_UNAUTHORIZED_JWT_TOKEN_ERROR

  1. Ensure that the PortOne Key and Secret Key belong to the same account.
  2. Confirm that the Secret Key has not been altered.
  3. Verify that the Bearer keyword precedes the generated token with a space. Example: Bearer $jwtToken.
  4. Check if the token expiration time is after the current time.

INVALID_UNAUTHORIZED_TRANSACTION_SIGNATURE_ERROR

  1. Validate if all parameters align with the payload/request.
  2. Ensure that the PortOne key matches with the payload and the account.

INVALID_UNAUTHORIZED_TRANSACTION_IAMPORTKEY_ERROR

  1. Confirm that the PortOne key matches with the payload and the account.

INVALID_PAYMENT_CHANNEL

  1. Validate that the payment channels and methods included in the payload are enabled in the PortOne portal.

INVALID_ENVIRONMENT

  1. Verify that an environment (sandbox or live) has been specified.

Summation of order value, tax, duties, shipping, and discount should equal the total amount

  1. If items are provided, ensure that the values match the total amount calculation formula: sum(items price * items quantity) + shipping charge - discount = amount.
  2. Mandatory parameters in the payload:
    • price
    • promo_discount (0 accepted)
    • shipping_charges (0 accepted)