Alipay, China's leading third-party online payment solutionAlipay, China's leading third-party online payment solution

Auto Debit (App)

This article introduces the integration solution to support automatic deduction from app. After integration, you can access various payment methods like digital wallets, bank cards, and bank transfers.

User experience

Log-in-to-authorize WAP page user experience

The buyer is redirected from a merchant app to a WAP wallet page where an account and password are required to complete the authorization.

登录授权APP1.webp

Notes:

  • If the buyer has the wallet app installed, the wallet app is opened in one of the following ways:
    • Via a universal link or an app link
      • Universal Link: Allow buyers to intelligently follow links to content in your app or to your website in the iOS system. For more information, see iOS Universal Links.
      • App Link: A deep link that when tapped, takes the buyer directly to a page within a specific app. For more information, see Android App Links.
    • Via an intermediate page
    • Via a dynamic link (Only for GCash)
  • Which type of wallet terminal the buyer is redirected to is determined by the target wallet's capability and the merchant's integration method. There are three types of URLs returned by the value of authUrl in the consult response. Each type of URL leads to a different wallet redirection experience:
    • If the authUrl value is an ordinary WAP address, the buyer is redirected to a log-in-to-authorize WAP page.
    • If the authUrl value is a URL scheme (WAP-scheme), the buyer is redirected to open the browser first and then open the wallet app.
    • If the authUrl value is a universal link or app link, the buyer is redirected to open the wallet app directly.

The following table shows which kind of experiences are provided by each wallet when the merchant terminal type is APP:

Payment method

Log-in-to-authorize WAP page

Wallet app

Installed

Not installed

Open intermediate page first and then open wallet

Open wallet via a universal link or app link

Open WAP page

GCash

✔️

✔️ Log-in-to-authorize WAP page

DANA

✔️

AlipayHK

✔️

✔️ Log-in-to-authorize WAP page

Kakao Pay

✔️

✔️ Wallet app download WAP page

Touch'n Go eWallet

✔️

✔️ Log-in-to-authorize WAP page

TrueMoney

✔️

✔️ Wallet app download WAP page

Alipay

✔️

✔️ Wallet app download WAP page

NAVER Pay

✔️

Boost

✔️✔️

✔️ Log-in-to-authorize WAP page

LINE Pay

✔️

✔️ Wallet app download WAP page

Maya

✔️

Payment flow

After obtaining the buyer's authorization, you can directly initiate the Auto Debit service without the need to go through the authorization process again for each payment.

Before conducting an automatic deduction, you need to obtain the buyer's authorization first. After the authorization is successfully obtained, obtain a payment token using an authorization code. The payment token is used to perform subsequent Auto Debit.

image.png

Integration steps

You need to obtain the buyer's authorization before conducting an Auto Debit. Upon successful authorization, obtain an authorization code to request a payment token for subsequent Auto Debit. You can obtain the buyer's authorization and conduct an Auto Debit by completing the following integration steps:

  1. Get and redirect to the authorization URL
  2. Obtain the authorization result
  3. Apply for a payment token
  4. Initiate an Auto Debit
  5. Obtain the payment results

Step 1: Get and redirect to the authorization URL Server side

You need to get the authorization URL first and redirect buyers to the authorization URL to complete authorizations.

Get the authorization URL

Antom provides server-side API libraries for multiple languages. The following codes use Java as an example. You need to install Java 6 or higher.

Install an API library

You can find the latest version on GitHub.

copy
<dependency>
    <groupId>com.alipay.global.sdk</groupId>
    <artifactId>global-open-sdk-java</artifactId>
    <version>2.0.44</version>
</dependency>

Initialize the request instance

copy
import com.alipay.global.api.AlipayClient;
import com.alipay.global.api.DefaultAlipayClient;
import com.alipay.global.api.model.constants.EndPointConstants;

public class Sample {
    public static final String        CLIENT_ID            = "";
    public static final String        ANTOM_PUBLIC_KEY     = "";
    public static final String        MERCHANT_PRIVATE_KEY = "";

    private final static AlipayClient CLIENT               = new DefaultAlipayClient(
            EndPointConstants.SG, MERCHANT_PRIVATE_KEY, ANTOM_PUBLIC_KEY, CLIENT_ID);

}

Call the consult API

The following parameters are included in the consult request.

Parameter name

Is required?

Description

authRedirectUrl

Yes

The URL used to redirect buyers to the merchant page after the authorization is completed.

authState

Yes

A string specified by you to identify an authorization request.

customerBelongsTo

Yes

Specify the target payment method for which you are requesting authorization.

scopes

Yes

In this scenario, the field is fixed to AGREEMENT_PAY.

terminalType

Yes

Indicates the terminal type where the merchant terminal is located.

The following sample code is used for calling the consult API to get the authorization URL:

copy
public static void authorizationConsult() {
    AlipayAuthConsultRequest alipayAuthConsultRequest = new AlipayAuthConsultRequest();

    // replace with your authState
    String authState = UUID.randomUUID().toString();
    alipayAuthConsultRequest.setAuthState(authState);

    // set the target payment method for which you are requesting authorization
    alipayAuthConsultRequest.setCustomerBelongsTo(CustomerBelongsTo.GCASH);

    // set the authorization scope
    alipayAuthConsultRequest.setScopes(new ScopeType[]{ScopeType.AGREEMENT_PAY});

    // set terminalType
    alipayAuthConsultRequest.setTerminalType(TerminalType.APP);
    alipayAuthConsultRequest.setOsType(OsType.ANDROID);

    // replace with your authRedirectUrl
    alipayAuthConsultRequest.setAuthRedirectUrl("http://www.yourRedirectUrl.com");

    // do authorization consult
    AlipayAuthConsultResponse alipayAuthConsultResponse;
    try {
        alipayAuthConsultResponse = CLIENT.execute(alipayAuthConsultRequest);
    } catch (AlipayApiException e) {
        String errorMsg = e.getMessage();
        // handle error condition
    }
}

The following code shows a sample of the request message:

copy
{
    "authRedirectUrl": "http://www.yourRedirectUrl.com",
    "authState": "21d6d7f5-5f04-4dbc-8741-3e8a02290d73",
    "customerBelongsTo": "GCASH",
    "osType": "ANDROID",
    "scopes": [
        "AGREEMENT_PAY"
    ],
    "terminalType": "APP"
}

Receive a consult response

The returned parameters are as follows:

  • normalUrl
  • schemeUrl
  • applinkUrl
  • appIdentifier

The following example is the sample response.

copy
{
    "appIdentifier": "com.iap.linker_portal",
    "applinkUrl": "https://g.alipayplus.com/page/aplus-linker/acwallet/authorization.html?acqSiteId=1022188***",
    "normalUrl": "https://g.alipayplus.com/page/aplus-linker/acwallet/authorization.html?acqSiteId=1022***",
    "result": {
        "resultCode": "SUCCESS",
        "resultMessage": "success.",
        "resultStatus": "S"
    },
    "schemeUrl": "alipayconnect://platformapi/signcontract/?source=AlipayConnect&needCallback=false***"
}

Common questions

Q: How to set terminalType?

A: The valid values of terminalType are:

  • If the buyer initiates a transaction from PC, the terminalType needs to be specified as WEB.
  • If the buyer initiates a transaction from the mobile browser, the terminalType needs to be specified as WAP. Add the osType parameter and fill in the corresponding system parameters ANDROID or IOS according to the buyer's mobile phone.
  • If the buyer initiates a transaction from app, the terminalType needs to be specified as APP.

Q: Can I use Chinese characters in the value of the request parameters?

A: To avoid incompatibility of a certain payment method, do not use Chinese characters for fields in the request.

Q: How to set the URL to receive the payment notification?

A: Antom sends you the payment result via notifyPayment. You can provide the address to receive the notification in Antom Dashboard.

Redirect to the authorization URL

After your server gets normalUrl, pass the URL to your client side. Your front-end page performs the action of redirecting the buyer to the address specified by normalUrl. The authorization process can lead to success or failure, with different redirections in each case:

  • Authorization success: Redirect your buyer back to the merchant page. The page address is a reconstructed URL composed of authRedirectUrlauthCode, and authState values.
  • Authorization failure:
    • If the buyer exits the authorization page, some payment methods allow buyers to be redirected to the merchant page. The address of the merchant page is specified by the value of authRedirectUrl.
    • If the buyer fails to be redirected to the merchant page from the payment method application due to authorization timeout or failure, we recommend that you guide the buyer to reinitiate the authorization process. Usually, if the buyer fails to be redirected to the merchant page from the payment method application after 15 minutes, the authorization fails.

Since the authorization URL can only be used once, if the user authorization fails, you need to call the consult API with a new authState value.

Step 2: Obtain the authorization result Server side

After the buyer completes the authorization, you can obtain the authorization code (authCode) in one of the following ways:

  • Obtain the authorization code from the reconstructed URL returned by the payment method.
  • Obtain the authorization code from the asynchronous authorization notification sent by Antom.

Obtain authCode from reconstructed URL

After the buyer's authorization process is completed, the buyer is to be redirected to the reconstructed URL returned by the payment method. This URL consists of three parts:

  • The value of the authRedirectUrl parameter that you specified in the consult API.
  • The authCode returned by the payment method.
  • The value of the authState parameter that you specified in the consult API.

The following sample shows a reconstructed URL:

copy
https://www.alipay.com/?authCode=d2f60253-ecdc-e9bc-27d1-566970191040&authState=663A8FA9-D836-48EE-8AA1-1FF682989DC7

You can obtain the authCode value from the reconstructed URL. However, before using the authCode value, it is necessary to check whether the value of authState in the reconstructed URL is consistent with the value of the authState parameter you specified in the consult API. If they are inconsistent, authCode in the reconstructed URL cannot be used because the reconstructed URL is not reliable due to possible malicious events such as attacks during the redirection process.

Obtain authCode from authorization notification

Due to network issues or other reasons, you might not be able to obtain the reconstructed URL. Instead, you can obtain the authorization code (authCode) from the authorization notification sent by Antom in the following steps:.

  1. Configure the address for receiving the asynchronous authorization notifications. For more details, see Notifications.
  2. After the buyer agrees to authorize, you will receive an authorization success notification sent by Antom.
  3. After receiving the asynchronous notification, you need to send a response to Antom with a format presented in the Requirements topic. Otherwise, Antom will resend the asynchronous notification.

Note: You can get authCode from either the reconstructed URL or the authorization notification. In case you have received multiple authCodes, utilize the first one that arrives and refrain from reusing the same authCode value when applying for payment tokens.

The following is an notification request sample:

copy
{
    "authorizationNotifyType": "AUTHCODE_CREATED",
    "authState": "556c1e32-3723-4b02-88ed-8c46087540ca",
    "authCode": "28100113_1631148338197000019ba74",
    "result": {
        "resultCode": "SUCCESS",
        "resultMessage": "success",
        "resultStatus": "S"
    }
}

Common questions

Q: When will the notification be sent?

A: After the buyer's authorization is completed, Antom sends an asynchronous notification to you.

Q: Will the asynchronous notification be re-sent?

A: Yes, the asynchronous notification will be re-sent automatically within 24 hours for the following cases:

  • If you didn't receive the asynchronous notification due to network reasons.
  • If you receive an asynchronous notification from Antom, but you didn't make a response to the notification in the Sample code format.

The notification can be resent up to 8 times or until a correct response is received to terminate delivery. The sending intervals are as follows: 0 minutes, 2 minutes, 10 minutes, 10 minutes, 1 hour, 2 hours, 6 hours, and 15 hours.

Q: When responding to asynchronous notification, do I need to add a digital signature?

A: If you receive an asynchronous notification from Antom, you are required to return the response in the Sample code format, but you do not need to countersign the response.

Q: What are the key parameters in the notification that I need to use?

A: Pay attention to the following key parameters:

  • authorizationNotifyType: Indicates the notification type. In this case, the value is AUTHCODE_CREATED.
  • authState: The request ID you provided when calling the consult API.
  • authCode: The authorization code generated after the user completes authorization. Use this authorization code to request for a payment token.

Step 3: Apply for a payment token Server side

After obtaining the authorization code (authCode), call the applyToken API to obtain a payment token (accessToken).

Call the applyToken API within one minute after obtaining the authorization code (authCode) to apply for the payment token (accessToken), otherwise the authorization code (authCode) will expire and become invalid. Only with the payment token (accessToken) can an automatic deduction from the buyer's account be implemented.

When calling the applyToken API, specify the following parameters correctly in the request:

Parameter name

Is required?

Description

grantType

Yes

Pass in the fixed value AUTHORIZATION_CODE.

customerBelongsTo

Yes

Specify the target payment method for which you are requesting authorization.

authCode

Yes

Pass in the value od authcode that you obtained.

The following code is a sample of applying for the payment token:

copy
public static void applyToken() {
    String authCode = "yourAuthCode";
    AlipayAuthApplyTokenRequest alipayPayRequest = new AlipayAuthApplyTokenRequest();

    // set grant type
    alipayPayRequest.setGrantType(GrantType.AUTHORIZATION_CODE);
    // set the target payment method for which you are requesting authorization
    alipayPayRequest.setCustomerBelongsTo(CustomerBelongsTo.GCASH);
    // set auth code
    alipayPayRequest.setAuthCode(authCode);

    // do apply token
    AlipayAuthApplyTokenResponse authApplyTokenResponse;
    try {
        authApplyTokenResponse = CLIENT.execute(alipayPayRequest);
    } catch (AlipayApiException e) {
        String errorMsg = e.getMessage();
        // handle error condition
    }
}

The following sample is a request message for applying for the payment token:

copy
{
  "authCode": "663A8FA9D83648EE8AA11FF68298XXXX",
  "customerBelongsTo": "GCASH",
  "grantType": "AUTHORIZATION_CODE"
}

In the response, you will receive the following key parameter:

  • accessToken: the payment token.

Notes:

  • Due to historical reasons, the key parameter above is applicable to new merchants in Antom. Refer to the table below for more information on token expiration time. If you have previously utilized the accessTokenExpiryTime, refreshToken, and refreshTokenExpiryTime fields, you may continue using your original logic.
  • If no response is received after calling the API, it is recommended that you use the same parameters and parameter values to initiate the request again.
  • If you can receive a response after calling the API, but the payment token (accessToken) is not returned in the response, the recommended handling method is as follows:
    • If result.resultStatus value is U, use the same parameters and parameter values to initiate the request again.
    • If the value of result.resultStatus is Faddress the associated issues based on the prompts provided by result.resultCode. If you need to call the applyToken API again to obtain a payment token, since the authCode can only be used once, you need to start over again from Step 1 to get the authorization URL, redirect to the authorization URL, get a new authCode, and then call the applyToken API again.
  • If you need to display the authorized account to the buyer, use the value of userLoginId returned in the applyToken API. The returned value of this field has been desensitized and can be displayed directly.

Regarding the payment methods supported by Auto Debit, the validity period of the payment token is shown in the following table:

Payment method

Validity period of token

Alipay

92 years

AlipayHK

100 years

Kakao Pay

100 years

GCash

100 years

DANA

100 years

Touch'n Go eWallet

100 years

TrueMoney

100 years

PayPay

100 years

NAVER Pay

2 years

Boost

100 years

KrungThai Bank

76 years

Siam Commercial Bank

76 years

Grabpay SG

10 years

Grabpay MY/PH

10 years

K PLUS

100 years

Maya

100 years

LINE Pay

100 years

Toss Pay

14 years

ZaloPay

10 years

Step 4: Initiate an auto debit Server side

Once you have obtained the buyer's authorization, you can offer the Auto Debit service directly to buyers without requiring them to undergo the authorization process for each payment.

Specify the following parameters when initiating an Auto Debit:

Parameter name

Is required?

Description

productCode

Yes

In this scenario, this field is fixed to AGREEMENT_PAYMENT.

paymentRequestId

Yes

A unique ID generated by the merchant. For each payment is initiated, a new ID must be created.

paymentAmount

Yes

The payment amount needs to be set in the smallest unit of the single currency, such as CNY for cents and KRW for yuan.

paymentMethod

Yes

Payment method enumeration value

paymentMethod.paymentMethodId

Yes

The value of the payment token (accessToken) obtained by calling the the applyToken API

paymentRedirectUrl

Yes

The merchant-side payment result page needs to be displayed based on the server-side results, and is not fixed to the success page.

paymentNotifyUrl

No

The payment result notification address can be transmitted through the API, or a fixed value can be set in the portal.

settlementStrategy

No

The settlement currency of this payment. If the business has signed multiple settlement currencies, it needs to be specified in the API.

order

Yes

Order information, including merchant order amount, order id, order description and other information

env

Yes

The terminal type from where the buyer initiates the transaction. For example, the transaction is initiated from the merchant PC website, the value is env.terminalType = WEB

The parameters listed above are not comprehensive. See the pay API for a complete list of parameters and any additional requirements for specific payment methods.

The following sample code shows how to initiate an Auto Debit:

copy
public static void pay() {
    AlipayPayRequest alipayPayRequest = new AlipayPayRequest();
    alipayPayRequest.setProductCode(ProductCodeType.AGREEMENT_PAYMENT);

    // replace with your paymentRequestId
    String paymentRequestId = UUID.randomUUID().toString();
    alipayPayRequest.setPaymentRequestId(paymentRequestId);

    // set amount
    // you should convert amount unit(in practice, amount should be calculated on your serverside)
    Amount amount = Amount.builder().currency("SGD").value("550000").build();
    alipayPayRequest.setPaymentAmount(amount);

    // set paymentMethod
    PaymentMethod paymentMethod = PaymentMethod.builder().paymentMethodType("GCASH").
            paymentMethodId("2828XXX77801726307481000Iba1Pm20IU171000179").build();
    alipayPayRequest.setPaymentMethod(paymentMethod);

    // set buyer info
    Buyer buyer = Buyer.builder().referenceBuyerId("yourBuyerId").build();

    // replace with your orderId
    String orderId = UUID.randomUUID().toString();
    // set order Info
    Order order = Order.builder().referenceOrderId(orderId).
            orderDescription("antom api testing order").orderAmount(amount).buyer(buyer).build();
    alipayPayRequest.setOrder(order);

    // set env info
    Env env = Env.builder().terminalType(TerminalType.APP).osType(OsType.ANDROID).clientIp("114.121.121.01").build();
    alipayPayRequest.setEnv(env);

    // replace with your notify url
    alipayPayRequest.setPaymentNotifyUrl("http://www.yourNotifyUrl.com");

    AlipayPayResponse alipayPayResponse;
    try {
        alipayPayResponse = CLIENT.execute(alipayPayRequest);
    } catch (AlipayApiException e) {
        String errorMsg = e.getMessage();
        // handle error condition
    }
}

The following code shows a sample of the request message:

copy
{
    "env": {
        "clientIp": "114.121.121.01",
        "osType": "ANDROID",
        "terminalType": "APP"
    },
    "order": {
        "buyer": {
            "referenceBuyerId": "yourBuyerId"
        },
        "orderAmount": {
            "currency": "SGD",
            "value": "550000"
        },
        "orderDescription": "antom api testing order",
        "referenceOrderId": "334b8883-5a7f-4ee4-a624-5a8b8e01cc00"
    },
    "paymentAmount": {
        "currency": "SGD",
        "value": "550000"
    },
    "paymentMethod": {
        "paymentMethodId": "2828XXX77801726307481000Iba1Pm20IU171000179",
        "paymentMethodType": "GCASH"
    },
    "paymentNotifyUrl": "http://www.yourNotifyUrl.com",
    "paymentRequestId": "8573febe-f65a-4e82-95f3-261e5ebc20bd",
    "productCode": "AGREEMENT_PAYMENT"
}

Common questions

Q: How to set terminalType?

A: The valid values of terminalType are:

  • If the buyer initiates a transaction from PC, the terminalType needs to be specified as WEB.
  • If the buyer initiates a transaction from the mobile browser, the terminalType needs to be specified as WAP. Add the osType parameter and fill in the corresponding system parameters ANDROID or IOS according to the buyer's mobile phone.
  • If the buyer initiates a transaction from app, the terminalType needs to be specified as APP.

Q: Can I use Chinese characters in the value of the request parameters?

A: To avoid incompatibility of a certain payment method, do not use Chinese characters for fields in the request.

Q: How to set the URL to receive the payment notification?

A: Specify paymentNotifyUrl in the createPaymentSession API to receive the asynchronous notification about the payment result (notifyPayment), or configure the receiving URL in Antom Dashboard. If the URL is specified in both the request and Antom Dashboard, the value specified in the request takes precedence.

Step 5: Obtain the payment results

When the buyer completes the payment or the payment times out, you can get the corresponding payment result from the Antom asynchronous notification or by inquiring the payment result actively.

Receive the asynchronous notification

When a payment is completed or fails, Antom sends an asynchronous notification (notifyPayment) to the address that you specified in the pay API via the paymentNotifyUrl parameter. If the address of each payment is the same, you can also configure the address in Antom Dashboard.

The following is the notification request sample code:

copy
{
    "actualPaymentAmount": {
        "currency": "SGD",
        "value": "550000"
    },
    "notifyType": "PAYMENT_RESULT",
    "paymentAmount": {
        "currency": "SGD",
        "value": "550000"
    },
    "paymentCreateTime": "2024-09-14T02:59:28-07:00",
    "paymentId": "202409141940108001001888H0209958443",
    "paymentRequestId": "214c60e7-672d-4ad8-9163-905ad4abe71f",
    "paymentResultInfo": {},
    "paymentTime": "2024-09-14T02:59:30-07:00",
    "pspCustomerInfo": {
        "pspCustomerId": "use***@alipay.com",
        "pspName": "GCASH"
    },
    "result": {
        "resultCode": "SUCCESS",
        "resultMessage": "success.",
        "resultStatus": "S"
    }
}

How to verify the signature of the notification and make a response to the notification, see Sign a request and verify the signature.

The following is the notification response sample code:

copy
{
  "result": {
    "resultCode": "SUCCESS",
    "resultStatus": "S",
    "resultMessage": "Success"
  }
}

Common questions

Q: When will the notification be sent?

A: It depends on whether the payment is completed:

  • If the payment is successfully completed, Antom will usually send you an asynchronous notification within 3 to 5 seconds. For some payment methods like OTC, the notification might take a bit longer.
  • If the payment is not completed, Antom needs to close the order first before sending an asynchronous notification. The time it takes for different payment methods to close the order varies, usually defaulting to 14 minutes.

Q: Will the asynchronous notification be re-sent?

A: Yes, the asynchronous notification will be re-sent automatically within 24 hours for the following cases:

  • If you didn't receive the asynchronous notification due to network reasons.
  • If you receive an asynchronous notification from Antom, but you didn't make a response to the notification in the Sample code format.

The notification can be resent up to 8 times or until a correct response is received to terminate delivery. The sending intervals are as follows: 0 minutes, 2 minutes, 10 minutes, 10 minutes, 1 hour, 2 hours, 6 hours, and 15 hours.

Q: When responding to asynchronous notification, do I need to add a digital signature?

A: If you receive an asynchronous notification from Antom, you are required to return the response in the Sample code format, but you do not need to countersign the response.

Q: What are the key parameters in the notification that I need to use?

A: Pay attention to the following key parameters:

  • result: indicates the payment result of the order.
  • paymentRequestId: indicates the payment request number you generated for consult, cancel, and reconciliation.
  • paymentId: indicates the payment order number generated by Antom, used for refund and reconciliation.
  • paymentAmount: indicates the payment amount.

Inquire about the payment result

Initiating a query request will involve the following parameters.

Parameter name

Is required?

Description

paymentRequestId

Yes

The payment request Id generated by the merchant.

The following is the sample code:

copy
public static void inquiryPayment() {
    AlipayPayQueryRequest alipayPayQueryRequest = new AlipayPayQueryRequest();

    // replace with your paymentRequestId
    alipayPayQueryRequest.setPaymentRequestId("yourPaymentRequestId");

    AlipayPayQueryResponse alipayPayQueryResponse = null;
    try {
        alipayPayQueryResponse = CLIENT.execute(alipayPayQueryRequest);
    } catch (AlipayApiException e) {
        String errorMsg = e.getMessage();
        // handle error condition
    }
}

The following is the response code:

copy
{
    "actualPaymentAmount": {
        "currency": "SGD",
        "value": "550000"
    },
    "paymentAmount": {
        "currency": "SGD",
        "value": "550000"
    },
    "paymentId": "202409141940108001001888H0209958443",
    "paymentRequestId": "214c60e7-672d-4ad8-9163-905ad4abe71f",
    "paymentResultCode": "SUCCESS",
    "paymentResultMessage": "success",
    "paymentStatus": "SUCCESS",
    "paymentTime": "2024-09-14T02:59:30-07:00",
    "pspCustomerInfo": {
        "pspName": "GCASH"
    },
    "result": {
        "resultCode": "SUCCESS",
        "resultMessage": "success.",
        "resultStatus": "S"
    }
}

Common questions

Q: How often should I call the inquiryPayment API?

A: Call the inquiryPayment API constantly with an interval of 2 seconds until the final payment result is obtained or an asynchronous payment result notification is received.

Q: What are the key parameters in the notification that I need to use?

A: Pay attention to these key parameters:

  • result: represents the result of this inquiryPayment API call, the result of the order needs to be judged according to paymentStatus:
    • SUCCESS and FAIL represent the final result.
    • PROCESSING represents the processing.
  • paymentAmount: indicates the payment amount.

Best practice

Follow these best practices to improve integration efficiency.

Configure the authorization URL

In the app scenario, different payment methods in the response of the consult API may return some or all of the following three URLs:

  • normalUrl
  • applinkUrl
  • schemeUrl

Note: For payments on a mobile application, in addition to the URL parameters used for redirection mentioned above, the response of the consult API also contains the appIdentifier parameter. This parameter is the package name of the corresponding payment method app and is used to determine whether the payment method app is installed for app payment. It can also be used to avoid disambiguation dialogs on Android.

Choose a URL

If the consult API response only contains one of the three URLs, use the received URL directly as the redirection link. If you receive multiple URLs, we recommend that you choose the URL based on the following instructions:

  • For iOS system: Prioritize using applinkUrl,then schemeUrl, and finally normalUrl.
  • For Android system: Prioritize using schemeUrl, then applinkUrl, and finally normalUrl.

Open the URL

For Android and iOS, you can open the authorization URL using the following methods:

iOS

Android

  • Redirect outside of the application: Call the iOS method to open the authorization URL.
  • Redirect within the application:
    • Use WKWebView
    • Use WKWebView and JSBridge
    • Use SafariViewController
  • Depending on whether the payment method app is installed, open the authorization URL either outside of the application or within the application.
  • Redirect outside of the application: Call the Android method to open the authorization URL.
  • Redirect within the application:
    • Use WKWebView
    • Use WKWebView and JavascriptInterface
    • Use Custom Tabs plug-in
  • Depending on whether the payment method app is installed, open the authorization URL either outside of the application or within the application.

Pros and cons of each redirection method

Each redirection method has its pros and cons. We recommend that you choose the most suitable redirection method based on the operation system and integration scenario.

Redirection method

Description

Redirect outside of the application: Call the Android/iOS method to open the authorization URL.

Antom recommends this method.

  • Pros: Low integration costs. One-time integration suits all payment methods.
  • Cons: The payment process is not fully kept on your clients.

Redirect within the application

  • WKWebView
  • WebView

WKWebView/WebView is a built-in control that can embed a web browser in an application. You can use it to load website links.

  • Pros: You can customize a better payment experience for buyers. Furthermore, you can achieve a seamless payment experience by redirecting buyers within the application, which means buyers do not leave your application and complete the subsequent payment process within your application.
  • Cons: Requires more development and testing efforts.
  • WKWebView+JSBridge
  • WebView+JavascriptInterface

An upgrade solution based on WKWebView/WebView. After using JSBridge/JavascriptInterface, you can directly call Android/iOS methods to open the authorization URL in WebView.

  • Pros: Performance, scalability, and security is improved compared to WKWebView/WebView. Provides a customized payment experience for buyers.
  • Cons: Requires more development and testing efforts.
  • SafariViewController
  • Custom Tabs

Provided by iOS/Android to open the authorization URL within the application. Has more comprehensive capabilities compared to WebView.

  • Pros: Can be integrated with the system browser, and share capabilities such as cookies with the system browser. The integration is relatively simple.
  • Cons: Does not support customizing payment experience.

Depending on whether the payment method app is installed, open the authorization URL either outside of the application or within the application.

Depending on whether the payment method app is installed, provide different redirection methods.

  • Pros: Provides a buyer-friendly payment experience.
  • Cons: Requires more development and testing efforts.

Code sample (iOS)

Method 1: Call the iOS method to open the authorization URL

The following code sample shows how to redirect buyers from your application to a payment method application using an iOS method in the iOS system.

copy
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Url] options:@{} completionHandler:nil];
}else{ 
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Url]];
}
Method 2: Open the authorization URLwithin the application

To open the authorization URL in your application, use the following URL types:

  • normalUrl
  • applinkUrl

Note: Some payment methods do not support authorization on a mobile website. Opening normalUrl triggers invoking the corresponding payment method app via a redirection, while WKWebView intercepts the redirection. You need to use the decidePolicyForNavigationAction method of WKWebView and call the iOS method to open the authorization URL to achieve the redirection from your WKWebView to the payment method app.

Use WKWebView

The following code sample shows how to use WKWebView to load the payment method page within the iOS application:

copy
// Initialize webview configuration
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
// Initialize webView 
WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
webView.navigationDelegate = self;
//Load the payment method URL
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:Url]]];
[self.view addSubview:self.webView];

The following code sample shows how to use the decidePolicyForNavigationAction method of WKWebView to achieve the redirection from your WKWebView to a payment method app:

copy
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    // WKWebView intercepts the redirection by default. Enable the redirection in the following ways.
    // Operations such as opening Safari
    NSURL *url = navigationAction.request.URL;
    NSString *absoluteString = url.absoluteString;
    NSString *scheme = url.baseURL.scheme;

    DLog(@"navigationAction.request.URL.absoluteString=====> %@", absoluteString);
    if ([absoluteString isEqualToString:@"about:blank"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    if (!([absoluteString containsString:@"https://"] || [absoluteString containsString:@"http://"])) {
        if ([absoluteString containsString:@"://"]) {
            NSString *urlHeader =  [absoluteString componentsSeparatedByString:@"://"][0];
            [MBProgressHUD showAutoMessage:[NSString stringWithFormat:@"Scheme\n%@://",urlHeader] toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self openAppWithUrlStr:navigationAction.request.URL];
                decisionHandler(WKNavigationActionPolicyAllow);
            });
        }
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
Use WKWebView and JSBridge

Using WKWebView and JSBridge optimizes the buyer's payment experience, while requiring strong development capabilities. Combining the use of JSBridge with opening URLs through WKWebView is beneficial for the project's maintenance and scalability, as well as improving performance and security. Using JSBridge can facilitate interaction between web pages and native applications, allowing WAP pages to directly call native methods of the app. The following code example demonstrates how to use JSBridge in WKWebView.

copy
[self.wkWebView evaluateJavaScript:bridge completionHandler:nil];
Use SFSafariViewController

SFSafariViewController supports opening and rendering normalUrl, applinkUrl, and schemeUrl. Compared to WebView, it has more comprehensive capabilities and a simpler integration. For how to use SFSafariViewController to open the authorization URL, see the SFSafariViewController user guide. The following code sample demonstrates how to use SFSafariViewController.

copy
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:Url entersReaderIfAvailable:NO];
safariVC.delegate = self;
[self.navigationController presentViewController:safariVC animated:YES completion:nil];
Method 3: Handle the redirection according to whether the payment method app is installed

You must first determine whether the buyer has installed the payment method app, and then handle the opening method of the authorization URL accordingly. Perform the following steps:

  1. Add LSApplicationQueriesSchemes to the configuration in info.plist. Note that there is a limit on the number of schemes in info.plist.
  2. Use the canOpenURL method to determine whether the payment method app is installed. See the following code:
copy
NSString *walletSchemeUrl = @"gcash://";

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:walletSchemeUrl]]){
    // The payment method app is installed. Open the app directly.
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:Url] options:@{} completionHandler:nil];
    
    return YES;
} else {
    // The payment method app is not installed. We recommend that you load the mobile website in WebView.
    SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:Url entersReaderIfAvailable:NO];
    safariVC.delegate = self;
    [self.navigationController presentViewController:safariVC animated:YES completion:nil];
    
    return NO;
}

Code sample (Android)

Method 1: Call an Android method to open the authorization URL

The following code sample demonstrates how to open the authorization URL using an Android method to achieve the redirection from your application to a payment method application.

copy
try {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Url));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    // use the startActivity function to redirect to the wallet app 
    startActivity(intent);
} catch (Exception e) {
    e.printStackTrace();
}

Using this method may result in the appearance of a disambiguation dialog box.

What is a disambiguation dialog box

Android App Link requests authentication from Google servers when installing the app. If authentication fails, the Android App Link will become invalid, and a disambiguation dialog box will appear when the buyer tries to open the app through such a link. The buyer needs to manually select how to open the link.

This image shows an example of a disambiguation dialog box that appears when a buyer clicks on an Android App Link. The buyer needs to manually select how to open the link: using Google Maps or Google Browser.

image.png

Prevent the appearance of a disambiguation dialog box

When a disambiguation dialog box appears, the buyer needs to manually select the way to open the application, which affects the payment success rate. Therefore, you need to prevent the appearance of a disambiguation dialog box by taking the following action as needed:

  • If the buyer has installed the payment method app, specify the package name of the payment method and open the URL of the payment method.
  • If the buyer has not installed the payment method app, use the sample code below to open the URL.
copy
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(applinkUrl));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
//Specify the package name of the payment method
intent.setPackage(walletPackageName);
PackageManager packageManager = MainActivity.this.getPackageManager();
//Check whether there is an app that supports opening this link.
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
if (activities.size() <= 0) {
   //The payment method app is not installed. Initialize the Intent object. This link will be opened by the default Android method.
   intent = new Intent(Intent.ACTION_VIEW, Uri.parse(applinkUrl));
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(intent);
} else {
  //The payment method app is installed. Specify the package name of the payment method and open the payment method URL. The disambiguation dialog box will not appear.
     startActivity(intent);
}

Note: The packageName values of some payment methods are shown as follows:

  • AlipayHK: hk.alipay.wallet
  • GCash: com.globe.gcash.android
  • TrueMoney: th.co.truemoney.wallet
  • KakaoPay: com.kakao.talk
  • Touch 'n Go: my.com.tngdigital.ewallet
  • Dana: id.dana
Method 2: Open the authorization URLwithin the application

To open the authorization URL in your application, use WebView to load normalUrl or applinkUrl as a mobile website:

  • normalUrl
  • applinkUrl

Note: Some payment methods do not support authorization on a mobile website. Opening normalUrl triggers invoking the corresponding payment method app via a redirection, while WKWebView intercepts the redirection. You need to use the shouldOverrideUrlLoading method of WKWebView and call the Android method to open the authorization URL to achieve the redirection from your WKWebView to the payment method app.

Use WebView

The following code sample demonstrates how to load the payment method page in WebView.

copy
WebView webView = findViewById(R.id.webview);
//Set webview
webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        view.loadUrl(request.getUrl().toString());
        return super.shouldOverrideUrlLoading(view, request);
    }});

WebSettings webSettings = webView.getSettings();
//Enable javascript
webSettings.setJavaScriptEnabled(true);
//Enable scaling
webSettings.setSupportZoom(true);
//Enable scaling controls (buttons)
webSettings.setBuiltInZoomControls(true);
//Webview has two cache modes. Cache is not used here.
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//Allow JavaScript to open a new tab (false by default)
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//Allow JavaScript to load local storage
webSettings.setDomStorageEnabled(true);
//WAP cache size (settings are not needed)
//webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
//WAP cache path
String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
//WAP cache size
webSettings.setAppCachePath(absolutePath);
//Set whether to allow WebView to access files (true by default)
webSettings.setAllowFileAccess(true);
//Allow WAP cache to be saved
webSettings.setAppCacheEnabled(true);
//In preview mode, if the page width exceeds the WebView display, scale down the page to fit WebView (false by default)
webSettings.setLoadWithOverviewMode(true);
//Support the viewport HTML meta tag
webSettings.setUseWideViewPort(true);
//Load the payment method URL
webView.loadUrl(Url);

Set WebViewClient for WebView, use the WebViewClient.shouldOverrideUrlLoading method to intercept the URL, and call the corresponding Android method. See the following code sample:

copy
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    if (request.getUrl().toString().startsWith("http")) {
        view.loadUrl(request.getUrl().toString());
        return super.shouldOverrideUrlLoading(view, request);
    } else {
        view.onPause();
        view.stopLoading();
        try {
          Intent intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          view.getContext().startActivity(intent);
        } catch (URISyntaxException e) {
          //Alert that this scheme is not supported
        }
        return false;
    }
}

Note: If your application has an allowlist of applications that can be redirected to, configure the allowlist properly, consider compatibility issues with older versions, and reduce the number of application releases.

Use WebView and JavascriptInterface

Using this method will optimize the buyer's payment experience, while requiring strong development capabilities. We recommend that you use JavascriptInterface in WevView. Using JavascriptInterface can help facilitate bidirectional communication between the Android application and WebView, allowing a mobile webpage to directly call native methods of the app, making your application more flexible and powerful, and beneficial for the subsequent maintenance and improvement of the project. The following code sample demonstrates how to use JavascriptInterface in WebView.

  1. Declare JavascriptInterface in WebView
copy
@JavascriptInterface
    public void openActivity(String url) {
        //Add the code if needed
        try {
        Intent intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    } catch (Exception e) {
        Toast.makeText(context, "App not installed", Toast.LENGTH_SHORT).show();
    }
}
  1. Add JavascripInterface to WebView
copy
mWebView.addJavascriptInterface(this, "bridge");
  1. Open the authorization URL using the following code
copy
window.bridge.openActivity("Url");
Use Custom Tabs

Custom Tabs supports opening and rendering normalUrl, applinkUrl, and schemeUrl. Compared to WebView, it has more comprehensive capabilities and a simpler integration. The following code sample demonstrates how to use Custom Tabs.

  1. Add Custom Tabs in the build.gradle file.
copy
dependencies {
    ...
    implementation "androidx.browser:browser:1.4.0"
}
  1. Use Custom Tabs to open a Chrome tab in your application.
copy
// Use CustomTabsIntent.Builder to configure CustomTabsIntent.
// Use CustomTabsIntent.Builder.build() to create CustomTabsIntent
// Use CustomTabsIntent.launchUrl() to launch the URL

CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

For more information about how to use CustomTabs to open the URL, see the Custom Tabs user guide.

Method 3: Handle the redirection according to whether the payment method app is installed

You must first determine whether the buyer has installed the payment method app, and then handle the opening method of the authorization URL accordingly. Perform the following steps:

  1. To comply with Android system's privacy and security policies, the <queries> tag needs to be added in AndroidManifest.xml to ensure that the authorization URL can invoke the corresponding payment method app. The package name of the payment method app needs to be configured in the <queries> tag. You can obtain the corresponding value from the appIdentifier parameter in the pay response returned by Antom or by contacting Antom Technical Support.
copy
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.llw.scandemo">
  
  ...
  <queries>
    <package android:name="th.co.truemoney.wallet" />
    <package android:name="com.eg.android.AlipayGphone" />
    <package android:name="my.com.tngdigital.ewallet" />
    ...
  </queries>
  ...
  
</manifest>
  1. Determine whether the payment method app is installed and invoke the authorization page:
copy
String Url = "applinkUrl/schemeUrl";
try {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Url));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setPackage("my.com.tngdigital.ewallet");
    // Determine whether the payment method app is installed
    PackageManager packageManager = MainActivity.this.getPackageManager();
    List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
    
    if (activities.size() <= 0) {
        // The payment method app is not installed. We recommend that you open the mobile website URL in WebView.

        intent = new Intent(MainActivity.this, WebviewActivity.class);
        intent.setData(Uri.parse(Url));
        startActivity(intent);
    } else {
        
        // The payment method app is installed. Open the payment method app directly.
        startActivity(intent);
    }
} catch (Exception e) {
    // Handle exceptions
    e.printStackTrace();
}