Integrating WeChat Pay into Mini Programs
The payment architecture relies on a secure interaction between the client-side mini program, the merchant backend, and the WeChat Pay server.
Transaction Workflow
- The user triggers a checkout action within the mini program.
- The client sends a payment initiation request to the merchant server.
- The backend communicates with the WeChat Pay unified order API.
- WeChat Pay returns a prepayment ID (
prepay_id) to the back end. - The server signs the necessary parameters and sends them back to the client.
- The mini program invokes the payment interface using the signed parameters.
Implementation Details
User Identification
Before processing transactions, the system must identify the user via their OpenID. This is achieved through the login credential exchange mechanism.
// Helper function to retrieve user OpenID
async function fetchUserIdentifier() {
try {
const loginResult = await wx.login();
if (loginResult.code) {
const response = await wx.request({
url: 'https://api.example.com/auth/exchange',
method: 'POST',
data: { credential: loginResult.code }
});
return response.data.userOpenId;
}
throw new Error('Login credential missing');
} catch (error) {
console.error('Authentication failed:', error);
return null;
}
}
Initiating the Transaction
Too invoke the native payment UI, specific signed parameters are required. These must be generated by the backend to ensure security. The client should not attempt to sign payloads locally.
Required fields for the payment invocation include:
timeStamp: Current Unix timestamp.nonceStr: Random string to prevent replay attacks.package: The prepayment ID string (format:prepay_id=...).signType: Encryption method (e.g., HMAC-SHA256 or MD5).paySign: The signature generated by the server.
// Function to execute payment request
async function executePayment(paymentParams) {
return new Promise((resolve, reject) => {
wx.requestPayment({
timeStamp: paymentParams.timestamp,
nonceStr: paymentParams.randomString,
package: paymentParams.prepayPackage,
signType: paymentParams.algorithm,
paySign: paymentParams.signature,
success: (result) => {
resolve({ status: 'success', details: result });
},
fail: (error) => {
reject({ status: 'failed', error: error });
}
});
});
}
Verifying Transaction Status
While the client receives immediate feedback, the definitive transaction status is communicated via server-to-server notifications. The client should query the backend to confirm the final state.
// Verify order status with backend
async function confirmOrderStatus(orderId) {
const verification = await wx.request({
url: 'https://api.example.com/orders/verify',
data: { transactionId: orderId }
});
if (verification.data.isValid) {
// Update UI for successful purchase
handleSuccessfulCheckout();
} else {
// Handle verification failure
handleCheckoutError();
}
}
Configuration Requirements
Successful integration requires proper setup on the WeChat Merchant Platform.
- Merchant Account: Complete registration and bussiness verification.
- API Credentials: Configure API keys and set up secure callback URLs for notifications.
- Mini Program Settings: Bind the Mini Program AppID to the merchant account in the developer console.
- Security: Ensure all communication uses HTTPS and signatures adhere to the latest security standards.
Complete Integration Example
The following snippet demonstrates chaining authentication and payment logic.
async function completeCheckoutFlow(amount) {
const userOpenId = await fetchUserIdentifier();
if (!userOpenId) {
console.warn('User identification failed');
return;
}
const orderData = await wx.request({
url: 'https://api.example.com/payments/create',
method: 'POST',
data: { uid: userOpenId, amount: amount }
});
try {
await executePayment(orderData.data);
await confirmOrderStatus(orderData.data.orderId);
} catch (err) {
console.error('Payment process interrupted', err);
}
}