AlipayHK - Membership Points Auto-Earn Solution
Introduction
In today's rapidly changing business landscape, digital transformation has become a necessity for companies to remain competitive and relevant. This is particularly true for retail and catering industry, which face growing pressure to adapt to the evolving needs of consumers and the increasing demands of a digital economy.
Membership Points Auto-Earn Solution is a comprehensive digital transformation solution designed to help commercial areas address these challenges and optimize their operations. Through advanced technologies and innovative strategies, the solution enables businesses to streamline their processes, enhance customer experiences, and unlock new revenue streams.
This document provides an overview of Membership Points Auto-Earn Solution , including its key features, user flows, and integration guideline. It is intended for merchants or ISVs who are looking for ways to drive digital transformation and stay ahead in today's competitive market.
As part of the broader initiative to digitize the retail ecosystem, our current focus is on the implementation of a membership program. By digitizing the membership experience, we aim to improve customer engagement, loyalty, and satisfaction, while also enabling loyalty program operators to collect and analyze valuable data to optimize their operations. Through the use of advanced technologies such as mobile apps and AlipayHK payment solutions , we will ensure that the membership program is convenient, secure, and user-friendly.
User Experience
We anticipate that AlipayHK users will automatically receive merchant's membership points upon successful payment at designated merchants without the need for additional actions such as uploading receipts, scan membership QR Code, etc. To enable this feature for users, the following requirements must be met:
- Payment must be made using the AlipayHK APP
- User must have authorized AlipayHK to share transaction information with the designated shopping malls or merchants
- The designated merchants must have an AlipayHK mini-app or Brand Channel
AlipayHK provides two approach for implementing this solution
2.1 via Brand Channel
Step 1: User login to to the Merchant's Brand Channel Page
Step 2: Confirm the authorization
Step 3: Payment with AlipayHK
Step 4: The Merchant's points updated automatically and user get the push notification
2.2 via Mini-APP
2.2.1 Auto Upload
User needs to login to Merchant’s or Shopping Mall‘s mini-app to authorize first.
Step 1: User login to Merchant's mini-app to authorize
Step 2: Payment with AlipayHK
Step 3: The Merchant's points updated automatically and user get the push notification
2.2.2 Manual Upload
User needs to login to Merchant’s or Shopping Mall‘s mini-app and then select the transactions to submit manually.
Step 1: User login to Merchant's mini-app to authorize
Step 2: Payment with AlipayHK
Step 3: User login to Merchant's mini-app
Step 4: Select the transactions and submit for membership points calculation
System Flow
3.1 via Brand Channel
If you want to adopt this feature via brand channel, you could refer the general system flow below. You may need to design the flow based on your own system requirement
3.2 via Mini-APP
3.2.1 Auto Upload
If you want to adopt this feature via mini-app, you could refer the general system flow below. You may need to design the flow based on your own system requirement.
3.2.2 Manual Upload
If you want to adopt this feature via mini-app, you could refer the general system flow below. You may need to design the flow based on your own system requirement.
Quick Integration
4.1 Preparation
HK Site Merchant ID and End Point
Merchant needs to complete the on-boarding progress to get a Merchant ID from AlipayHK side.
The merchant id should start with 2160. Please contact your BD/SA for initial information setup. Please include below information
- Endpoint for different environment ( Production and non-Production)
- Public key for different environment ( Production and non-Production)
After configuration complete, AlipayHK will reply with the clientID and AlipayHK public id.
The clientID will be used for API calling
PMS Information
PMS information is a must for Implementing this solution
If merchant can't provide the PMS, we provide approach for collecting the PMS ID.
a. Collect them via an identifier code.
please contact your BD/SA to get a PMS identifier code.
b. Collect them via API
please check the API imformation in below sessions
Membership Card Template
Membership card template needs to be provided if you wants your membership card display in AlipayHK APP
Please fill in the template information and send to your BD for template creation📎{Merchant_Name}Membership_Template.xlsx
If more user information is needed during account creation, please also provide below information
📎MembershipCardCreation_Supplementary_v1.0.xlsx
4.2 API fundamentals
This section presents general information (such as message structure, message fields, and message transmission) of online messages between your system and Alipay. A message refers to the request message or the response message.
Request message structure
The following figures illustrate the request message structure:
Request URL
The request URL is: https://{host}/openapi/v{majorVersion}/{restfulPath}
where,
host is the standard domain name assigned by Alipay.
restfulPath is the path to the interface.
An interface can be uniquely identified by restfulPath and majorVersion.
Request method
POST method is used to make an HTTP request.
Request header
The request header mainly contains fields such as Client-Id, Signature, Encrypt, Content-Type, Request-Time, and Agent-Token.
Client-Id
Client-Id is used to identify a client, and is associated with the keys that are used for signature and encryption. It is assigned by AlipayHK.
Signature
Signature contains key-value pairs that are separated by comma (,). Each key-value pair is an equation, which is a key joined with its value with an equal sign (=).
The following keys can be configured:
- algorithm: Specifies the digital signature algorithm that is used to generate the signature. The value is not case-sensitive. RSA256 and ECC224 are supported, and RSA256 by default.
- keyVersion: Specifies the key version that is used to generate or validate the signature. By default, the value is the latest version of the key associated with Client-Id.
- signature: Contains the signature value of the request.
For example:
signature: algorithm=RSA256, keyVersion=1,
signature=KEhXthj4bJ801Hqw8kaLvEKc0Rii8KsNUazw7kZgjxyGSPuOZ48058UVJUkkR21iD9JkHBGR
rWiHPae8ZRPuBagh2H3qu7fxY5GxVDWayJUhUYkr9m%2FOW4UQVmXaQ9yn%2Fw2dCtzwAW0htPHYrKMyrT
pMk%2BfDDmRflA%2FAMJhQ71yeyhufIA2PCJV8%2FCMOa46303A0WHhH0YPJ9%2FI0UeLVMWlJ1XcBo3Jr
bRFvcowQwt0lP1XkoPmSLGpBevDE8%2FQ9WnxjPNDfrHnKgV2fp0hpMKVXNM%2BrLHNyMv3MkHg9iTMOD%
2FFYDAwSd%2B6%2FEOFo9UbdlKcmodJwjKlQoxZZIzmF8w%3D%3D
Encrypt
This field is required when a message need to be encrypted. Encrypt contains key-value pairs that are separated by comma (,). Each key-value pair is an equation, which is a key joined with its value with an equal sign (=).
The following keys can be configured:
• algorithm: Specifies the symmetric key algorithm that is used to encrypt message. The value is not case-sensitive, and currently only RSA_AES is supported.
• keyVersion: Specifies the symmetric key version that is used to encrypt message. By default, the value is the latest version of the key associated with clientId.
• symmetricKey: Contains the encrypted symmetric key.
For example:
Encrypt: algorithm=RSA, keyVersion=1,
symmetricKey=bqS8HSmdaRrpKSuPy7CqUlyd8lJurG93
Content-Type
Optional. Content-Type indicates the media type of the body of the request, as defined by RFC2616. In which, charset is used for generating/validating the signature and encrypting/decrypting content.
For example:
Content-Type: application/json; charset=UTF-8
Request-Time
Specifies the time when the request is sent, as defined by RFC3339. Note: This field must be accurate to milliseconds.
Request-Time: 2019-04-04T12:08:56.253+05:30
Agent-Token
An agent can obtain the token from Alipay, and then use this client authorized token to interact with Alipay.
Request body
The request body contains the detailed request information in a JSON format. Fields enclosed in the request body section vary depending on services. For more information, see instructions of the specific message interface.
Response message structure
The following figures illustrate the response structure:
Figure 2. Response structure
Response header
Response header carries additional information about the response, such as the signature and the encryption. Most fields in the response header are the same as that of the request header, except:
Response-Time
Specifies the time when the response is sent, as defined by RFC3339.
Response body
Response body contains the information responding to the client. Fields in this section vary depending on services. However, the result parameter, which indicates the result of an interface call, is always contained.
Message fields
Read the following chapter for general information of message fields, such as data type, common data structure, and processing rules of special characters.
Data type
This following table describes the data types supported by Alipay.
Data type | Description |
String | A sequence of bytes. |
Email format | |
URL | URL format |
Datetime | Date time as defined by RFC3339. For example, 2020-01-01T23:59:59+08:00 |
Date | A three-part value (yyyyMMdd) designating a time point in time. |
Boolean | The boolean value can be either true or false. |
Integer | A numeric value without a decimal. |
Decimal | A numeric value with a decimal. |
Array | A homogeneous data structure (elements have same data type) that stores a sequence of consecutively numbered objects--allocated in contiguous memory. |
Processing rules of special characters
The following rules are about how to process special characters enclosed in the message.
base64
For byte data, such as the signature and the encrypted content, encode the data with the base64 algorithm before transmitting.
urlencode
For URL data, perform URL encoding first before transmitting. For example:
Original URL: https://www.merchant.com/authorizationResult
Converted URL: https%3A%2F%2Fwww.merchant.com%2FauthorizationResult
4.3 Digital signature
To guarantee that data have not been altered in transmission, digital signature and encryption mechanism can be adopted. For all messages, the digital signature is mandatory. In addition, data encryption is required if sensitive information is enclosed in the message. For more details about encryption, see Encryption.
The signature algorithm used for data transmission is RSA 256. You can use RSA256 for creating or validating signatures. When creating a signature, calculate a sha256 digest first, and then encrypt the digest by using RSA algorithm. The recommended RSA key size is 2048 bits.
Generating an RSA key pair
RSA key pair
An RSA key pair contains the private key and the public key. The private key is required for generating the signature, while the public key is used for verifying the signature.
Generating an RSA key pair
Many tools can be used to generate the RSA key pair. The following steps assume that you use OpenSSL to generate the RSA key pair.
1.Install OpenSSL.
For linux system, use the following command:
sudo apt-get install openssl
For windows system, download and then install OpenSSL from the official site
2.Generate RSA2 key pair.
For linux system, use the following command:
$ openssl
OpenSSL> genrsa -out rsa_private_key.pem 2048 ##generate private key
OpenSSL> pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM - nocrypt ##transform private key into PKCS8 format
OpenSSL> rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
##Generate public key
OpenSSL> exit
Uploading RSA public key
After the RSA2 key pair is generated, you must exchange the public key with the AlipayHK server for signature verification by completing the following steps:
- Upload your public key to AlipayHK
- Obatin AlipayHK public key
Creating a signature
See the following figure for an overview of the signature creation process:
Complete the following steps to create a signature:
1. Obtain the private key.
2. Create the string to sign. The string to be signed is:
<HTTP Method> <HTTP-URI-with-query-string>
<Client-Id>.<Request-Time|Response-Time>.<HTTP body>
3. Generate the signature. Use the algorithm and private key obtained in step1 to generate the signature. The following example assumes that RSA256 algorithm is used to generate the signature:
signature=base64UrlEncode(sha256withrsa(string-to-sign))
Demo code:
/**
*
* @param requestURI // domain part excluded, sample: /ams/api/v1/payments/pay
* @param clientId
* @param requestTime
* @param privateKey
* @param requestBody
* @return
*/
public static String sign(String requestURI, String clientId, String requestTime,
String privateKey, String requestBody) {
String content = String.format("POST %s\n%s.%s.%s", requestURI, clientId, requestTime,
requestBody);
try {
java.security.Signature signature = java.security.Signature
.getInstance("SHA256withRSA");
PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(
new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey.getBytes("UTF-8"))));
signature.initSign(priKey);
signature.update(content.getBytes("UTF-8"));
byte[] signed = signature.sign();
return URLEncoder.encode(new String(Base64.encodeBase64(signed), "UTF-8"), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
- Add the signature to header. Assemble the signature algorithm, the key version used for the signature, and the signature into Signature header. The following example shows a finished Signature header:
key: Signature ;
value:algorithm=<algorithm>,keyVersion=<key-version>,signature=<signature>
Validating a signature
See the following figure for an overview of the signature validation process:
The signature verification process consists of the following steps:
1. Obtain the public key, obtain Client-Id and algorithm from header.
2. Create the string to sign. The string to be signed is:
<HTTP Method> <HTTP-URI-with-query-string>
<Client-Id>.<Request-Time|Response-Time>.<HTTP body>
- Use the algorithm obtained in step 1 to calculate a digest of the string you created in step 2. Then, decrypt the signature by using the public key to get a digest. Compare two digests, if the digests match the signature is verified. For example, assume RSA256 algorithm is used, base64url decode the signature content to obtain the original signature, and then validate the signature by using the sender’s public key and sha256withrsa algorithm.
sha256withrsa_verify(base64UrlDecode(<signature>), <content_to_be_verified>, <serverPublicKey>)
Demo code:
/**
*
* @param requestURI // domain part excluded, sample: /ams/api/v1/payments/pay
* @param clientId
* @param reponseTime
* @param alipayPublicKey
* @param responseBody
* @param signatureToBeVerified
* @return
*/
public static boolean verify(String requestURI, String clientId, String reponseTime,
String alipayPublicKey, String responseBody,
String signatureToBeVerified) {
//signatureToBeVerified would not be present in the response when AMS returns a SIGNATURE_INVALID
if (StringUtil.isBlank(signatureToBeVerified)) {
return false;
}
String content = String.format("POST %s\n%s.%s.%s", requestURI, clientId, reponseTime,
responseBody);
try {
java.security.Signature signature = java.security.Signature
.getInstance("SHA256withRSA");
PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(
new X509EncodedKeySpec(Base64.decodeBase64(alipayPublicKey.getBytes("UTF-8"))));
signature.initVerify(pubKey);
signature.update(content.getBytes("UTF-8"));
return signature.verify(Base64.decodeBase64(URLDecoder.decode(signatureToBeVerified,
"UTF-8").getBytes("UTF-8")));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
4.4 SDK Download
To make the integration process easier, we recommend you to use our SDK.
You can get the SDK from below Git repository
JAVA:https://github.com/alipay/global-open-sdk-java
4.5 Implementing error handling
4.5.1 Idempotence
Idempotence means that in response to the same requests sent multiple times, AlipayHK will send back only one unique result.
To create a membership card: AlipayHK checks the idempotence by using merchantId, templateCode and bizSerialId. If existing record is found, errors will be returned.
To update a membership card: AlipayHK checks the idempotence by using merchantId, templateCode and passId. If existing record is found, errors will be returned.
4.5.2 Timeout or system error
Because HTTPS requests depend on network stabilities, timeout might occur on interface requests. At the same time, AlipayHK might return SYSTEM_ERROR for internal system problems. In both cases, partners can retry to get aligned with the final pass status.
Returned Result | Description |
PARAM_ILLEGAL | Illegal parameters |
USER_NOT_EXSITS | User does not exist |
PASS_HAS_EXIT | Pass is existed |
PASS_TEMPLATE_HAS_NOT_EXIT | Pass template does not exist |
PASS_TYPE_NOT_MATCH | Pass type does not match to template |
PASS_PRODUCT_TYPE_NOT_MATCH | Pass product type does not match to template |
PASS_IS_NULL | Pass is null |
PASS_HAS_NOT_EXIST | Pass does not exist |
PASS_USED_OCCUPIED | Pass has been redeemed |
PASS_UPDATE_FAIL | Fail to update pass status (Only pass with 'active' status can be updated. |
Best Practice
- Prevent calculating points duplicately
Besides of AlipayHK, we believe merchant will calculate membership points via other channels such as merchant's own APP, onsite customer service center, etc. To avoid calculating duplicately, we suggest Ordering system or CRM to verify the transactions before adding the points based on transaction no.
AlipayHK suggested de-duplicated logic
- Make the points updated timely
To bring the best customer experience, we will suggest merchant update the Points once received the transaction record from AlipayHK side. Technically, the /updatePass API should be called after received the API /notify call from AlipayHK side. Understand that some CRM/OMS system may update the point by batch, we strongly recommend CRM/OMS could implement realtime points update. Alternatively, could split into two sperate logic, one for real-time and one for batch update
- Make the user login smoothly (for mini-app solution)
To bring the best customer experience, we will suggest merhcant adopting our SSO solution. Hence user doesn't need to login again when re-enter the mini-app
For more details about the SSO, please check the details here
- Adopt proper retry mechanism
As the system can't be 100% stable and response to the API call timely everytime, merchant could consider to adopt proper retry mechanism to increate the robust of the overal system design. Merchant could use below interval and frequency.
1st time: 01:00:00 - initial request
2nd time: 01:00:02 - after ard 2s
3rd time: 01:00:04 - after ard 2s
4th time: 01:00:06 - after ard 2s
5th time: 01:10:06 - after ard 10mins
6th time: 01:40:06 - after ard 30mins
- Response to AlipayHK's API timely
To bring the best user experience, our front-end has 3s timeout rules, which means if our system doesn't receive response within 3s, the APP will then display error message to user. Hence we will suggest Merchant‘s system should response to AlipayHK's API call within 3s, better 2s.
API List
Below are the overview of all the APIs might be used. You can choose the APIs depends on your own requirement. There are also some APIs need to be developed by merchant side.
6.1 via Brand Channel
API Type | Index | API | Description | Direction | Developed by |
| 1.1 | NA | No API Integration needed | NA | NA |
| 2.1 | /{Merchant’s tag}/points/membercard/create | Uses for AlipayHK to create a membership card in Merchant side | AlipayHK --> Merchant |
|
2.2 | Uses for Merchant to create a membership card in AlipayHK app | Merchant --> AlipayHK |
| ||
2.3 | Uses for Merchant to update membership card information n AlipayHK app | Merchant --> AlipayHK |
| ||
| 3.1 | /{Merchant’s tag}/points/bill/notify | Uses for AlipayHK to send transaction information for authorized user | AlipayHK --> Merchant |
|
| 4.1 | NA | PMS colletcion and Maintenance will be conducted offline | NA | NA |
6.2 via Mini-App
6.2.1 Auto Upload
API Type | Index | API | Description | Call Direction | Developed by |
| 1.1 | JSAPI: my.getAuthCode
| Uses for Merchant to get user authorization | Merchant --> AlipayHK |
|
| 2.1 | Uses for Merchant to create a membership card in AlipayHK app | Merchant --> AlipayHK |
| |
2.2 | Uses for Merchant to update membership card information n AlipayHK app | Merchant --> AlipayHK |
| ||
| 3.1 | /{Merchant’s tag}/points/bill/notify | Uses for AlipayHK to send transaction information for authorized user | AlipayHK --> Merchant |
|
| 4.1 | NA | Uses for Shopping Malls to collect PMS information | Merchant --> AlipayHK | NA |
6.2.1 Manual Upload
API Type | Index | API | Description | Call Direction | Developed by |
| 1.1 | JSAPI: my.getAuthCode
| Uses for Merchant to get user authorization | Merchant --> AlipayHK |
|
| 2.1 | Uses for Merchant to create a membership card in AlipayHK app | Merchant --> AlipayHK |
| |
2.2 | Uses for Merchant to update membership card information n AlipayHK app | Merchant --> AlipayHK |
| ||
| 3.1 | /api/open/alipayhk/businessdistrict/bill/query | Uses for Shopping Malls to query authorized user's transaction information | Merchant --> AlipayHK |
|
3.2 | JSAPI: my.navigateToMiniProgram | Uses for Shopping Malls mini-app to re-direct to the page for user transaction information submission *needs to contact SA team for enabling this API for your mini-app | Merchant --> AlipayHK |
| |
3.3 | Mini-APP funciton : onShow(options) * please contact SA team for details of this function | Uses for Shopping Malls to switch between to the user transaction information page and Mall's mini-app | Merchant --> AlipayHK |
| |
| 4.1 | /api/open/alipayhk/businessdistrict/circleStore/save | Uses for Shopping Malls to collect PMS information | Merchant --> AlipayHK |
|
4.2 | /api/open/alipayhk/businessdistrict/circleStore/queryPage | Uses for Shopping Malls to check PMS information collection result | Merchant --> AlipayHK |
|
API Details
Create Merchant’s Membership Card
Send User Transaction Record
Create AlipayHK Membership Card
Could refer to general createPass API
https://docs.alipay.hk/alipayhkdocs/hk/gcmc/create_giftmem
Or below specs specifically for auto-earn points scenario
Update AlipayHK Membership Card
Could refer to general createPass API
https://docs.alipay.hk/alipayhkdocs/hk/gcmc/update_giftmember
Or below specs specifically for auto-earn points scenario
Query User Transaction Record
Collect PMS Information
Query PMS Collection Result
Testing Environment
Items | Value | Description |
Merchant's IPs | Please contact our SA team for setting this up | To access AlipayHK’s DEV environment,we need to whitelist your outbound IPs. |
AlipayHK's endppoint | business.dl.alipaydev.com | Please use this endpoint for API testing |
ClientId | Please contact our SA team for retrieving this data | Please use this client-id for API testing |
MID | Please contact our SA team for retrieving this data | Please use this MID for API testing |
TemplateCode | 22023041200135606000000000297866 | Please use this MID for API testing - Memership card creation |
userid | Please contact our SA team for retrieving this data | Please use this userId for API testing - Memership card creation |
AlipayHK Public Key | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0eIBay2+dwlrlNzhM3cHmnkOXC3GfK3+Zxoy+Ffug6XYYwJJvi5ZjN0opOhjFehzVfB008/x11IwxM9eOZL4L05TSVV7T3+Xg2DjQ1FPW4tRba3NnfaUL5vaIfWZxIARow2YgqgtlpPk6ILplUPP59d0+BGDrvlritP76C82yCKVNrz7TIyU+lo1xqrYqu4Dr+VnaKgbEG2r2cJ7Ren2ko9C6UJacg6e7A9IRT0vHNqg0cAIIOcmLocd7Fya3C/DFoxYmEdahJtZDETC1xwwX3fX5Pb13bNlU3Yc/CtSa8Fs/L9ncrspMu8Qe9F/9xQu1dN9AEqVTzngCB2NVfkjdwIDAQAB | Please use this Public Key for APi message verification in DEV Environment |
Merchant Private Key | Please contact our SA team for retrieving this data | Please use this Private Key to sign your API request and response in DEV Environment |