Mini Program WeChat Pay Integration Process
Scenario Introduction
This document primarily introduces how to use the WeChat Pay template to integrate the payment process for Mini Program applications built on the cloud development platform.
Implementation Process
Installing the WeChat Pay template will automatically generate cloud functions, workflows, and WeChat Pay APIs. The order placement, payment, and callback processes are implemented as follows:
1 WeChat Pay Template Installation
Find the Mini Program WeChat Pay template in the template center of the CloudBase platform.
Install the template
Template Installation in Progress
Template Installation Completed
View Template Details
During template parameter configuration, you need to configure payment merchant information. Refer to the relevant parameter descriptions in Payment Merchant Configuration
2 Implement Order Placement and Payment Initiation in the Editor
Payment scenarios require previewing the actual effects in a real device environment or WeChat Developer Tools, as the payment function cannot be invoked in the editor.
Prerequisites
Before formally invoking the payment process, you need to understand:
In the editor, Basic Concepts of Events and How to Call JavaScript Event Methods
How to Call Cloud Functions in the Editor, using the javascript invocation method as a sample
WeChat Pay - Introduction to Mini Program JSAPI Order Placement Parameters
Invocation Process
2.1. In the editor, create a new js method to trigger the WeChat Pay order placement function in cloud functions and invoke payment
2.2. The js method code is as follows:
In the code, const orderInfo = event.detail
is the input parameter when calling the js method in the editor. Please pass it according to the actual business scenario and the Mini Program JSAPI Order Placement Parameters.
export default async function ({ event, data }) {
const orderInfo = event.detail;
const ordeResult = await $w.cloud.callFunction({
// Cloud function name
name: "wxpayFunctions",
data: {
// Invoke the order placement method of the cloud function
type: "wxpay_order",
// For the Mini Program Fully Managed Authorization mode, use the following method in the editor to pass the user's openid. Requires pre-enabling openid login or mobile number authorization login methods.
// openid:$w.auth.currentUser.openId,
// Other business parameters
...orderInfo,
},
});
const paymentData = ordeResult.result?.data;
// Invoke the WeChat Pay component to complete the payment
return new Promise((resolve, reject) => {
wx.requestPayment({
timeStamp: paymentData?.timeStamp, // "1414561699",
nonceStr: paymentData?.nonceStr, // "5K8264ILTKCH16CQ2502SI8ZNMTM67VS",
package: paymentData?.packageVal, //"prepay_id=wx201410272009395522657a690389285100"
signType: paymentData?.signType, //"RSA",
paySign: paymentData?.paySign, //"oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg==",
success: function (res) {
resolve(orderInfo._id);
},
fail: function (res) {
reject(orderInfo._id);
},
});
});
}
2.3. If the mini program and cloud development platform use fully managed authorization mode, the method for receiving openid in the cloud function needs to be modified as follows:
If the Mini Program and CloudBase platform use QR code authorization mode, this step can be skipped
In the cloud function, you need to use event.openid
to receive the user's openid passed from the frontend js method.
payer: {
// In QR code authorization mode, the cloud function on the server side directly obtains the current user's openId. In fully managed mode, you need to use event.openid to receive it.
openid: wxContext.OPENID? wxContext.OPENID:event.openid,
},
2.4. The event triggers the above-mentioned js method, using the click event as an example.
2.5. In the payment cloud function, variables passed from the frontend can be received through the event parameter and processed within the cloud function.
3 Payment Callback Handling
Using Cloud Functions to Receive WeChat Pay Notifications
WeChat Pay asynchronously sends payment notifications. Here, cloud functions are used to receive these notifications and determine payment success. Developers can update the order payment status based on the WeChat Pay notifications received by the cloud function.
Create a cloud function named
wxpayOrderCallback
as the callback function for receiving payment notifications, as shown in the sample code below"use strict";
exports.main = async (event, context) => {
// event contains all the json parameters listed above; use them as needed
// Here, event_type === "TRANSACTION.SUCCESS" is used to determine successful payment
const { event_type } = event;
if (event_type === "TRANSACTION.SUCCESS") {
// Process business logic related to successful payment, such as updating order status in the data model
}
return event;
};In the parameter settings, configure the "Cloud Function for Receiving Payment Notifications" field with the value: scf:wxpayOrderCallback
Parameters sent by WeChat Pay
NoteDifferent payment types return varying parameter structures; refer to the actual parameters received by the callback function.
{
"id": "EV-2018022511223320873", // Unique ID of the callback notification
"create_time": "2015-05-20T13:29:35+08:00", // Creation time of this callback notification
"resource_type": "encrypt-resource", // Resource data type for the notification, fixed to encrypt-resource
"event_type": "TRANSACTION.SUCCESS", // Type of WeChat Pay callback notification. The type for successful payment notification is TRANSACTION.SUCCESS.
"summary": "Payment successful", // Summary note for the callback content by WeChat Pay.
"resource": {
"amount": {
"currency": "CNY",
"payerCurrency": "CNY",
"payerTotal": 1,
"payer_currency": "CNY",
"payer_total": 1,
"total": 1
},
"appid": "wx480c*****aa44a43",
"attach": "",
"bankType": "BOC_DEBIT",
"bank_type": "BOC_DEBIT",
"mchid": "1613752320",
"outTradeNo": "8206022981401",
"out_trade_no": "8206022981401",
"payer": {
"openid": "ou*********************3zM"
},
"promotionDetail": null,
"promotion_detail": null,
"successTime": "2025-03-21T17:27:37+08:00",
"success_time": "2025-03-21T17:27:37+08:00",
"tradeState": "SUCCESS",
"tradeStateDesc": "Payment successful",
"tradeType": "JSAPI",
"trade_state": "SUCCESS",
"trade_state_desc": "Payment successful",
"trade_type": "JSAPI",
"transactionId": "4200002********8510115762",
"transaction_id": "42000026********8510115762"
}
}
Introduction to Core Modules of WeChat Pay Template
The Cloud Function
wxpayFunctions
includes the following methods:- wxpay_order: Mini Program order placement
- wxpay_query_order_by_transaction_id: Query order by WeChat Pay transaction ID
- wxpay_query_order_by_out_trade_no: Query order by merchant order number
- wxpay_refund: Apply for refund
- wxpay_refund_query: Query a single refund by merchant refund number
Workflow: Connects cloud functions and APIs methods to achieve seamless payment process integration.
APIs: Encapsulate WeChat Pay-related interfaces, where the JSAPI order placement method serves as a key prerequisite step for payment initiation.
Frequently Asked Questions FAQ
1 Why can't the payment be invoked in the editor?
The editor actually provides a web-based rendering effect and cannot simulate a real payment environment.
2 How to determine if a cloud function has been executed successfully?
You can view cloud function execution logs on the cloud development platform.
3 No response when clicking the pay button on a real device?
Check if the jsapi order placement parameters are correct by referring to the implementation steps described above.
To perform breakpoint debugging on cloud functions, add console log statements in the order placement method. During execution, view the logs via cloud function logs or the mini program's vconsole mode.