Best practice
Create optimal payment experiences for your customers by following these best practices for integrations. The best practice needs to be implemented not only between the server side and Alipay, but also to the terminals.
Prepare your device
A device that can scan QR code and can conduct external communication needs to be prepared for the payment service.
Properly use Alipay interfaces
It is suggested to integrate at least the payment, query, refund, cancel, and payment notification interfaces. You need to use Alipay interfaces properly for your business.
- Payment interface:
The payment notification URL needs to be specified in the payment request. After calling a payment interface (alipay.acquire.overseas.spot.pay), the payment result is to be returned by Alipay. If no result is returned, take the following actions:
- If no asynchronous notification and payment result are returned from Alipay within 5 seconds after the payment request is sent, the merchant needs to use the query interface to inquire the payment result. The query request can be sent 10 to 20 times, with an interval of 3 seconds.
- When calling the query interfaces, if no payment result can be obtained after the query requests being sent more than the maximum number of times, the merchant needs to call the cancel interface to cancel the transaction. If being out of the cancellable period, the merchant cannot use the cancel interface to cancel the transaction. The merchant can call the refund interface to make a refund instead. (Note: The cancel request can only be used within the same business day in the Beijing time zone. If the cancellation cannot succeed within the same business day, you can call the refund request to initiate a refund process.)
- Query interface:
After calling a query interface (alipay.acquire.overseas.query), the query result might be returned from Alipay. If no result is returned, take the following actions:
- If no result is returned from Alipay for 3 seconds due to network issues, the merchant needs to retry the query interface. The query interface can be called 10 to 20 times, with an interval of 3 seconds.
- When calling the query interfaces, if no payment result can be obtained after the query requests being sent more than the maximum number of times, the merchant needs to call the cancel interface to cancel the transaction.
About the query response:
- is_success: indicates whether the request is accepted by the Alipay gateway.
- result_code: indicates whether the query request is successfully called.
- alipay_trans_status: indicates the transaction status. You can decides your further actions according to the alipay_trans_status and error fields.
- error: displays the error code when the transaction was failed. When the value of this field is SYSTEM_ERROR, it means the query request is recognized as failed and you need to retry the query process.
- Cancel interface:
After calling a cancel interface (alipay.acquire.cancel), the cancel result might be returned from Alipay. If no result is returned, take the following actions:
- If no result is returned from Alipay for 3 seconds due to network issues, the merchant needs to use the same parameters to retry the cancel request. The cancellation process needs to be retried for at least 60 seconds, with an interval of 5 to 10 seconds. If you have retried the cancellation request for 60 seconds and still get no response, you are suggested to record failed cancels and retry in batches in the later stage. It is recommended to implement the store-and-forward queue to control the cancel retry mechanism.
- If no result is obtained after trying several times of cancellation, the merchant needs to contact Alipay technical support team.
Note:
- The cancel request can only be used within the same business day in the Beijing time zone. If the cancellation cannot succeed within the same business day, you can call the refund request to initiate a refund process.
The following graphic gives you a clear structure about the above-mentioned relationships between the payment, query, and cancel interfaces.
Figure 1. Calling the payment, payment query, and cancellation interfaces.
- Refund interface:
After calling a refund interface, the refund result might be returned from Alipay. If no result is returned, take the following actions:
- If no result is returned from Alipay for 3 seconds due to network issues, the merchant needs to use the same parameters to retry the refund request. The refund process can be retried for 60 seconds, with an interval of 5 to 10 seconds.
- If no result is obtained after trying several times of refund, the merchant needs to contact Alipay technical support team.
Note:
You can use the alipay.acquire.refund.query interface to check the refund status if the refund process is interrupted or when the back office needs to get the refund status immediately.
- Payment notification:
By specifying the notify_url field in the payment interface,you can receive the payment notification sent by Alipay. Follow these suggestions to handle the notification:
- If a notification is received when the order status reaches the final state, the merchant can ignore the notification.
- If a notification is received after the merchant initiated a cancellation request, the merchant can ignore the notification and determine the payment status according to the result of the cancellation request.
Create partner trans ID/out trade number properly
When the same business order needs to be paid multiple times, for a reason that the previous payments failed or revoked, it is necessary to ensure that the value of partner trans ID/out trade number for each payment interface is not repeated. Therefore, the business order number cannot be used as the partner trans ID or out trade number directly. Instead, an independent ID/number should be generated for each payment request. Besides, the relationship between the business order number and partner trans ID/out trade number should be created at the merchant server.
The partner trans ID/out trade number must be unique, and cannot be reset. You are suggested to create the partner trans ID/out trade number in the following way:
time stamp (accurate to seconds) + terminal number + terminal transaction serial number.
Follow the customer barcode/QR code standard
You need to be able to support payment codes that have 17 to 32 digits and start with 25, 26, 27, 28, 29, or 30. Besides, stay open to the possibility of code length expansion.
Print receipt
The receipt to print must contain the following information:
- The partner trans ID/out trade number or the Alipay transaction ID (alipay_trans_id). It is suggested to use also a barcode display.
- Alipay payment indication, to indicate the payment is processed by Alipay.
- Transaction date and time in the local time (accurate to seconds).
Besides, it is not suggested to show the following information on the printed receipt:
- The actual funding channels used by Alipay.
- The payment amount. (Note: the payment amount will be displayed on the customer's mobile phone.)
Confirm the payment result
You must confirm the payment result in a correct way. Pay attention to the following items:
- You must verify the signature of the payment asynchronous notification and check whether the returned payment amount and its monetary unit are consistent with those of the payment request. Ensure that the received notification was not tampered with.
- After receiving the asynchronous notification or payment result, first confirm whether the notification has been processed. Only for the original transaction that has not been processed and cancelled, you can continue to complete the payment. If you receive the cancel request from the terminal, complete the cancel process.
- Use data lock for concurrency control to avoid getting the payment result from the query request and the asynchronous notification at the same time, which might cause data confusion if the same transaction information is repeatedly recorded in the database.
Solution for cancellation retries
To avoid duplicated charges, the delivery of cancellation message needs to be guaranteed. Although retrying the cancel interface is able to achieve a very high successful rate, it is still recommended to use message queueing when possible. The following graphic shows the three steps of using message queuing:
- If calling the query interface fails to get the result, the cancel process is initiated. If the cancel request cannot be sent out, you need to save the cancel request to a local queue for retries at regular intervals or when network recovery.
- After receiving the cancel request, the receiving queue acknowledges the cancel request and initiates the cancel request after the original transaction arrives.
- If a network exception or system error occurs when the cancel request is sent to Alipay, save the cancel request to sending queue and try again.
Figure 2. Three steps of using message queuing
Keep transactions in final status
For each In-store Payment transaction, an intermediate status WAIT_BUYER_PAY
and three final statuses TRADE_SUCCESS
, TRADE_FINISHED
, and TRADE_CLOSED
exist. Merchants must ensure that each transaction is in the final status. In addition, the transaction status must be consistent at merchant system, cashier side, and Alipay side.
By default, an In-store Payment transaction is automatically closed in 3 minutes if the payment is not completed. However, in real life, the cashier might not wait for 3 minutes. Merchants can set different time limit according to specific business requirements.
You can take the following actions to ensure that the transactions reach the final status:
- If the transaction result is not returned in a certain period, for example, 5 seconds after the transaction is created, use QUERY interface to poll the result once every 3-5 seconds.
- Set a timeout period, for example, 60 seconds, and keep polling the result before the timeout period expires.
- If
TRADE_SUCCESS
orTRADE_CLOSED
is received during the query, the cashier will then be notified of the result. - If only
WAIT_BUYER_PAY
is returned during the query, the CANCEL interface must be called to force the transaction to close. For more information about the cancel retry logic, see Handling errors.
Note
The following rule applies to all products.
Sometimes, the cashier might be unable to initiate the automatic correction. In this case, a background job must be configured in partner's system to perform the auto-correction for transactions in status WAIT_BUYER_PAY
, and the timeout period can be slightly longer than the one set at the cashier side.
For more information about the transaction status, see Trade status.
Idempotence
Idempotence is the property of Alipay sending back only one unique result for the same requests that were sent multiple times. Alipay checks the idempotence to keep an accurate transaction or refund result for each request. To help Alipay checks the idempotence, you need to take the following actions:
- For the same payment requests that were sent multiple times, provide the same out_trade_no for the same payment requests. Requests with the same out_trade_no are considered as the same transaction.
- For the same refund requests that were sent multiple times, provide the same out_trade_no or partner_transaction_id for refund requests that were sent multiple times. Requests with the same out_trade_no or partner_transaction_id are considered as the same transaction.
Alipay checks the idempotence for payment and refund requests in the following ways:
- For the payment requests with a same PID:
After receiving a payment request, Alipay checks the idempotence of out_trade_no (partner_transaction_id). Transactions with a same out_trade_no are considered as same transactions. Alipay then checks other information such as the buyer information and the transaction amount. If the information does not match with that in the Alipay system, errors will be returned. Otherwise, Alipay returns the real status of the transaction.
- For the refund request with a same PID:
After receiving a refund request, Alipay checks the idempotence of out_trade_no (partner_transaction_id) and partner_refund_id. Refunds with a same out_trade_no or partner_transaction_id are considered as same refund. Alipay then checks information such as the amount of the refund. If this information does not match with that in the Alipay system, errors will be returned. Otherwise, Alipay returns the real status of the refund.
For more details about idempotency, see API idempotency.
For integrations between acquirers and merchants
Alipay transactions are settled in real time, which imposes challenges of maintaining consistent transaction states among customers, merchants, acquirers and Alipay. Since customers are able to view transactions on their mobile on the spot, any discrepancies can lead to on-site complaints. To maintain the consistency of transaction states, acquirers need to follow not only the best practice for integration between acquirers and Alipay but also that for integration between acquirers and merchants. This document illustrates the principles for ensuring a high-quality integration between acquirers and merchants. The principles apply for merchants and acquirers that adopt the consumer-presented mode payment, order code payment, and entry code payment products.
Principles
Due to the diversity of integration methods between merchants and acquirers, Alipay recommends that the integration between merchants and acquirers follow these principles to ensure the integration quality:
- Keep the transaction status consistent for all parties.
- In case of any uncertain state, initiate a cancellation process if you can.
- If the cancellation is not executed because of packet loss or other abnormal conditions, you need to retry the cancellation process by yourself or through the retry queue.
Apply principles for various integration models:
Several integration models and the corresponding integration principles are discussed in the following sections to illustrate various integrations between merchants and acquirers. Contact Alipay technical support for help if your integration model is not in any of the following situations.
Forwarding gateway
This is an integration model where the acquirer gateway simply forwards messages from downstream (merchants) to Alipay. The forwarded messages include the payment, query, cancel and refund request.
All requests are initiated downstream and forwarded by the gateway and protocol translation might be involved. Although protocol details or data fields used between merchants and acquirers might be different from that are used between acquirers and Alipay, the processing logic and transaction flows are similar. Therefore, the integration between merchants and acquirers also needs to follow the best practices issued by Alipay.
Take a typical Alipay barcode transaction as an example. The following graphic shows the process of initiating requests and forwarding requests.
Figure 3. The process of initiating requests and forwarding requests
In case of any uncertain state, it is recommended to initiate a cancellation process actively or by using the store-and-forward queue.
Active cancellation
In the integration model where the acquirer gateway simply forwards messages from downstream (merchants) to Alipay, connection issues between merchants and the gateway occur frequently. When connection issues occur, it is suggested that the forwarding gateway send a cancellation request to Alipay to avoid transaction status inconsistency.
For example, the connection between downstream and the gateway is disconnected in the middle of a query process before the user authorizing the transaction. However, the authorization process is completed normally between the user and Alipay. Therefore, the merchant treats the timeout as a declined transaction while Alipay debits the user’s fund. As a result, transaction status inconsistency occurs, which needs to be avoided.
To avoid transaction status inconsistency, it is suggested that the forwarding gateway initiate an active cancellation to Alipay on behalf of downstream when the following conditions are satisfied:
- An agreed transaction timeout is reached, that is, the transaction cannot be processed further.
- No response with an approval for the authorization is returned from Alipay for previous inquiries to the gateway.
- No cancellation request from downstream is received by the gateway after the timeout being reached.
The following graphic shows the process of initiating an active cancellation from the forwarding gateway to Alipay:
Figure 4. The process of initiating an active cancellation
Note:
The timeout setting of the gateway must be greater than timeout settings of the merchants, otherwise transactions can be reversed prematurely, which affects success rate.
Store-and-forward queue
About the retransmission of cancellation, implementing the store-and-forward queue for cancellation can reduce the possibility of getting undelivered cancellations.
Implementing the store-and-forward queue can help the cashier to send cancellations in the back office until success. Therefore, it is recommended to implement the store-and-forward queue at both the merchant side and the gateway side. Besides, if you don't want to implement the store-and-forward queue for both sides, you need to implement at the merchant side at least.
RESTful API gateway
This is an integration model where existing payment infrastructures of acquirers are used. For example, connect acquirers' RESTful APIs with merchants for Alipay integration. Although this kind of integration model increases the complexity of the integration at the server side, the integration at the merchant side becomes much easier because most of the query and cancellation logic can be implemented at the server side.
For this kind of integration, the principle of keeping transaction status consistent among all parties needs to be carefully considered.
Take a typical Alipay barcode transaction as an example. After the merchant initializing the transactions, the gateway starts the Alipay transaction by following our integration best practices including those for queries and retries. The merchant uses the acquirer's API to check results of the transactions asynchronously. The merchant and acquirer maintain their own timeout value independently. The following graphic shows the process of using the acquirer's API to check transaction results.
Figure 5. The process of using the acquirer's API to check transaction results
In case of any uncertain state, it is recommended to complete the following actions to ensure transaction status consistent among all parties:
- The gateway takes responsibility of determining the closing time of the transaction and making the final cancellation request to Alipay to close the transaction with Alipay.
- The gateway needs to be able to provide the merchant with the final transaction status by setting a shorter timeout value than that of the merchant side.
- The merchant initiates a cancellation request to the gateway to help reduce the possibilities of inconsistent transaction status.
To close transactions between the acquirer and Alipay, the gateway needs to actively send the cancellation request when one of the following conditions is satisfied:
- After the gateway timeout is reached, no response with an approval for the authorization is returned from Alipay.
- When an authorization approval is returned by Alipay, but the gateway is not able to deliver the approval to downstream, a cancellation request needs to be initiated to reverse the transaction after timeout.
The following graphic shows the process to initiate a cancellation request to Alipay.
Figure 6. The process of initiating a cancellation request to Alipay
Although the gateway needs to be able to deliver the final transaction status to the merchant, it is possible that the merchant doesn't receive the message for some reason. In this case, merchants need to notify the gateway somehow and the gateway needs to be able to interpret it as a cancellation request to Alipay. Besides, it is suggested that the merchant initiate a cancellation process as a safe net to reduce the possibilities of inconsistent transaction states.
Request and response switch
This is an integration model where the acquirer uses an existing payment switch.
In this case, downstream is responsible for initiating cancellations after timeout. The switch saves reversal advices in the store-and-forward queue and translates the advices to cancellation requests to Alipay. The switch needs to guarantee the successful delivery of cancellation requests to Alipay by using store-and-forward queue.
The following graphic shows the process of initiating reversal advices by merchants. The merchant initiates a reversal advice to the switch. The switch returns a response to the merchant immediately and takes the responsibility of sending a cancellation request to Alipay successfully.
Figure 7. The process of of initiating a reversal advice to Alipay