This topic describes how to use EMAS Serverless to develop a mini program that supports Huabei Pay.
Preparations
Before you begin, make sure you have completed the following preparations:
Register an Alipay enterprise developer account.
If you do not have an Alipay mini program account, use your Alipay account to log on to the Ant Financial Open Platform and register as an enterprise developer. For more information, see Developer Registration Guide.
Download and install Alipay Mini Program Studio.
For more information, see Download Instructions.
The Node.js development environment has been installed.
Step 1: Activate the EMAS service
Log on to the Alibaba Cloud Management Console.
Hover over the
icon in the upper-left corner and choose Products & Services.In the product list, choose Enterprise Services & Cloud Communication > Multiexperience Development Platform.
On the product page, click Activate Now.
Step 2: Create a project and an application
Cloud resources created during mini program development are associated with a service space. Each service space has a globally unique space ID that is used to link all cloud resources. Follow these steps to create a service space and set database permissions:
Create a service space
Cloud resources created during mini program development are associated with a service space. Each service space has a globally unique space ID that is used to link all cloud resources. Follow these steps to create a service space.
Log on to the EMAS console. Choose Serverless and click Enter.
Click Create Service Space.
On the Create Service Space page, enter the following information.
Parameter name
Description
Service Space Name
Enter a custom name for the service space. The name must meet the following rules:
Contain only letters and digits.
Not start with a digit.
Be 3 to 15 characters in length.
Description
Enter a brief description of the service space's purpose.
Payment Method
Includes Subscription and Pay-as-you-go.
NoteWhen you select the subscription method, you can set Auto-renewal on Expiration. If you purchase the Developer Edition package, do not enable auto-renewal. The Developer Edition only supports manual renewal. Auto-renewal will fail.
Click Create and Pay.
After the service space is created, you can view the following information on the details page:
The Basic Information tab displays information such as Space Name, Space Status, and Billing Mode.
The Access Information tab displays information such as SpaceID, Secret, API Endpoint, and File Upload Endpoint.
Set database permissions
On the EMAS Serverless console page, choose . In the upper-right corner of the page, select the service space that you created.
On the ApsaraDB page, click Add Now.
In the New Data Table dialog box, enter a name for the data table and click OK.
Select your data table, and then choose Permissions > Edit Permissions.
NoteTo ensure data security, database access is restricted by default. You must set database permissions as needed. For more information, see Manage data permissions.
On the permission management page, click Custom Security Rules and change the write permission to true.
Step 3: Enable extended capabilities
Log on to the EMAS console, select Serverless, and click Enter.
In the navigation pane on the left, choose Extended Capabilities.
On the Extended Capabilities page, click Activate Now.
In the dialog box that appears, click Go to RAM for Authorization, and then click Agree to Authorize to grant the mini program access to the Function Compute service.
Return to the Extended Capabilities page to view the activation status.
Step 4: Create an Alipay mini program application
Follow these steps to create an Alipay mini program on the Ant Financial Open Platform:
Use your Alipay account to log on to the Ant Financial Open Platform and click Console.
Select Mini Program Application, click Create Application, and follow the instructions to create a mini program application.
In the navigation pane on the left, click Settings.
Click Development Settings. In the Development Information section, find the Interface Signature Method section and configure the Alipay public key.
You can use an RSA key generation tool to generate a mini program key. Two interface signature methods are available: public key and public key certificate. These methods are used for signing and validation. The developer is responsible for storing the private key, which is used for signing. The public key is used for signature validation. You must save your private key and use the public key provided by Alipay for communication. This process ensures data integrity during transmission and verifies the sender's identity. For more information, see Generate an Alipay RSA key.
ImportantEnterprise developers must use the public key certificate mode to access interfaces for fund-related transactions.
In the Function List on the development management page of the mini program, click the Add Function button in the upper-right corner to add Mini Program Pay.
The Mini Program Pay feature requires a signed contract to be activated. After the mini program is published, click Sign Contract on the right side of the function list. The approval process takes about one business day after you sign the contract. You will be notified of the approval result by text message and email. After the feature is approved, its status changes to Effective.
Step 5: Add the Alipay mini program
Before you start development, you must add the Alipay mini program information to the Alibaba Cloud EMAS Serverless console.
To add the Alipay mini program information, perform the following steps:
Log on to the EMAS console, select Serverless, and click Enter.
In the navigation pane on the left, choose Settings.
Click the Alipay tab, and then click Add Key.
Enter your private key. This is the mini program RSA private key generated in Step 4.
Enter the Alipay public key. To retrieve this key, log on to the Ant Financial Open Platform and navigate to Development Center > Settings > Development Settings. The key is displayed in the Interface Signature Method section.
Step 6: Get the template code
You can open the miniapp developer tool and select Mini Program Development.
Select Alipay Mini Program. Then, from the Open Capabilities category of mini program templates, select the Huabei Pay template.
Click Next, specify a project name and path, and then complete the project creation process.
Step 7: Quick start
In Alipay Mini Program Studio, log on with your Alipay developer account and associate it with your mini program.
In client/pages/app.js, update the configuration items with your parameters.
appId: '2021*********', // Mini program application ID spaceId: 'ca8eb10f-26c1-4bee-**********', // Service space ID clientSecret: 'Xckz2************', // Service space secret key endpoint: 'https://api.************' // Service space endpoint. Obtain it from the EMAS Serverless console.The appId is the AppId that you set in EMAS Serverless. You can find the spaceId, clientSecret, and endpoint parameters on the service space details page, as described in Step 2.
After you save the file, open the real-device debugger in the IDE. You can then use the Alipay app on your mobile phone to test the Huabei payment feature in your mini program. You have now successfully built a simple mini program that supports Huabei Pay and developed its core features using EMAS Serverless.
EMAS Serverless code details
Initialize the Serverless SDK
Before you use the EMAS Serverless service, you must install and initialize the EMAS Serverless client SDK in your mini program. For more information about the EMAS Serverless client SDK, see Install Client SDK V2.2.
// client/app.js import MPServerless from '@alicloud/mpserverless-sdk'; const mpserverless = new MPServerless({ uploadFile: my.uploadFile, request: my.request, getAuthCode: my.getAuthCode, }, { appId: ' ', // Mini program application ID spaceId: ' ', // Service space ID clientSecret: ' ', // Service space secret key endpoint: ' ' // Service space endpoint. Obtain it from the EMAS Serverless console. });Initialize the cloud call SDK and authorize log on
To use the extended capabilities provided by EMAS Serverless, you must first enable the cloud call feature in the console. Then, install and initialize the cloud call SDK in the mini program.
Before you call the EMAS Serverless service, you must call the authorize interface to request authorization. The authProvider request parameter for Alipay mini programs must be set to alipay_openapi. For more information, see authorize.
// client/app.js import cloud from 'alipay-serverless-sdk'; cloud.init(my.serverless); App({ async onLaunch(options) { var res = await my.serverless.user.authorize({ authProvider: 'alipay_openapi', }); }, });Create a transaction
The following code calls the payment.common.create and cloud.payment.huabei.create interfaces to create direct payment orders and Huabei installment payment transactions. For more information about the direct payment and Huabei installment interfaces, see payment.common.create and payment.huabei.create.
async tradeCreate() { let createRes if (this.data.checked === '1') { // Direct payment createRes = await cloud.payment.common.create('EMAS Serverless payment test', "demo" + new Date().getTime(), '0.03', this.data.userId); } else { // Huabei installment var huabeiConfig = new Object({ hbFqNum: "3", hbFqSellerPercent: "100" }); createRes = await cloud.payment.huabei.create('EMAS Serverless payment test', "demo" + new Date().getTime(), '0.03', this.data.userId, huabeiConfig); } this.setData({ tradeNO: createRes.tradeNo, outTradeNo: createRes.outTradeNo }) return createRes.tradeNo },Payment
The following code calls the my.tradePay Alipay open API to open the Alipay cashier for payment. For more information about mini program payments, see Mini Program Pay.
async onRepeatPayHandler(data) { my.tradePay({ tradeNO: this.data.tradeNO, success: async (res) => { if (res.resultCode === "9000") { my.alert({ title: 'Payment successful', content: res.resultCode, }); const value = data.currentTarget.dataset.item const { key } = value const { paymentHistory } = this.data paymentHistory.map(v => { if (v.key === key) { v.tradeStatus = 'TRADE_SUCCESS' } }) my.serverless.db.collection('payment').updateOne({ key }, { $set: { tradeStatus: 'TRADE_SUCCESS' } }) this.setData({ paymentHistory }) } }, }); },Refund
The following code calls the payment.common.refund cloud call interface to process a refund. For more information, see payment.common.refund.
async onRefundPayHandler(data) { const value = data.currentTarget.dataset.item const { outTradeNo, totalAmount, key } = value const rs = await cloud.payment.common.refund(outTradeNo, String(totalAmount)) if (rs.code === "10000") { my.showToast({ content: 'Refund successful', }); const { paymentHistory } = this.data paymentHistory.map(v => { if (v.key === key) { v.tradeStatus = 'TRADE_CLOSED' } }) this.setData({ paymentHistory }) my.serverless.db.collection('payment').updateOne({ key }, { $set: { tradeStatus: 'TRADE_CLOSED' } }) } else { my.showToast({ content: 'Refund failed', }); } console.log(rs) },