WeChat Pay Mini Program Payment Integration
About 1365 wordsAbout 5 min
2025-08-28
Use the unified order API to implement WeChat Mini Program payment integration. Merchants obtain user openid within the mini program, call the API through the backend to get prepay_id, then invoke WeChat payment in the mini program to complete the transaction.
🚀 Quick Start
Core Features:
- ✅ No redirection, payment completed within mini program
- 🛡️ Based on WeChat Mini Program security mechanism
- 🔌 Standardized API call process
- ⚡ Smooth and fast payment experience
WeChat Mini Program Payment Interaction Flow
Integration Navigation
Tip
- WeChat Mini Program payment is only available within WeChat Mini Program environment, requires obtaining user openid.
- You need to complete basic configuration and payment permission application for WeChat Mini Program in advance.
- It's recommended to thoroughly test in sandbox environment before going live in production.
Prerequisites
🔧 WeChat Mini Program Configuration
Requirements:
- ✅ WeChat Mini Program already activated and verified
- ✅ WeChat Pay merchant number already obtained
- ✅ JSAPI payment permission already enabled in WeChat Pay merchant platform
- ✅ Payment authorization directory already configured
Request Order and Payment
Use Order and Payment interface to create WeChat Mini Program payment order.
In the API Order and Payment response:
- When status is
SUCCESS, order has been paid successfully - When status is
PROCESSING, order has been created, returnsextraParam.wxPrepayIdfor mini program to call - When status is
FAILED, order creation failed
Key Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
paymentMethod.wxOpenId | String | Yes | Unique identifier of user in mini program, obtained via wx.login() |
paymentMethod.wxAppId | String | Yes | WeChat Mini Program AppID, obtained from mini program backend |
device.orderTerminal | String | Yes | Fixed value 06 (WeChat Mini Program identifier) |
paymentMethod.type | String | Yes | Fixed value WeChat Pay |
Parameter Example:
Mini Program Frontend Calls WeChat Payment
After obtaining extraParam.wxPrepayId from API response, call wx.requestPayment() in mini program to complete payment.
Get User Openid
Use
wx.login()to get code, backend exchanges for openidwx.login({ success: (res) => { // Send code to backend to exchange for openid this.getOpenIdFromBackend(res.code); } });Initiate Payment Request
Pass openid and other parameters to merchant server, merchant server calls Unified Order API
wx.request({ url: 'https://yourapi.com/payment/create', method: 'POST', data: { openid: this.data.openid, amount: this.data.amount, // Other order information } });Invoke WeChat Payment
Use returned prepayId to call
wx.requestPayment()wx.requestPayment({ timeStamp: paymentData.timeStamp, nonceStr: paymentData.nonceStr, package: `prepay_id=${prepayId}`, signType: 'RSA', paySign: paymentData.paySign, success: (res) => { // Payment successful, query payment status this.queryPaymentResult(); }, fail: (err) => { // Payment failure handling console.log('Payment failed', err); } });Handle Payment Result
Listen for payment callback, query payment status
onPaymentSuccess() { // Query final payment result from backend wx.request({ url: 'https://yourapi.com/payment/query', success: (res) => { if (res.data.status === 'SUCCESS') { wx.redirectTo({ url: '/pages/success/success' }); } } }); }
Complete Code Example
📱 Mini Program Frontend Implementation
// pages/payment/payment.js
Page({
data: {
orderInfo: {},
loading: false
},
onLoad(options) {
this.setData({
orderInfo: {
amount: options.amount || '100',
productName: options.productName || 'Test Product'
}
});
},
// Get user openid
async getOpenId() {
return new Promise((resolve, reject) => {
wx.login({
success: (res) => {
wx.request({
url: 'https://yourapi.com/wechat/auth',
method: 'POST',
data: { code: res.code },
success: (result) => resolve(result.data.openid),
fail: reject
});
}
});
});
},
// Initiate payment
async requestPayment() {
try {
this.setData({ loading: true });
wx.showLoading({ title: 'Paying...' });
const openid = await this.getOpenId();
const paymentRes = await this.createPaymentOrder(openid);
if (paymentRes.code === '000000') {
const paymentData = JSON.parse(paymentRes.bizContent);
const prepayId = paymentData.extraParam.wxPrepayId;
// Get payment signature and invoke payment
const signData = await this.getPaymentSign(prepayId);
this.callWechatPay(signData, prepayId);
}
} catch (error) {
console.error('Payment request exception', error);
wx.showToast({ title: 'Payment request failed', icon: 'error' });
} finally {
this.setData({ loading: false });
wx.hideLoading();
}
},
// Invoke WeChat payment
callWechatPay(signData, prepayId) {
wx.requestPayment({
timeStamp: signData.timeStamp,
nonceStr: signData.nonceStr,
package: `prepay_id=${prepayId}`,
signType: 'RSA',
paySign: signData.paySign,
success: () => this.onPaymentSuccess(),
fail: (err) => this.onPaymentFail(err)
});
},
// Payment success handling
onPaymentSuccess() {
wx.showToast({ title: 'Payment Successful', icon: 'success' });
setTimeout(() => {
wx.navigateBack();
}, 1500);
},
// Payment failure handling
onPaymentFail(error) {
if (error.errMsg.includes('cancel')) {
wx.showToast({ title: 'Payment Canceled', icon: 'none' });
} else {
wx.showToast({ title: 'Payment Failed', icon: 'error' });
}
}
});Common Issues and Solutions
⚠️ Openid Acquisition Failure
Common Causes:
- 🔥 Incorrect mini program login process
- ⏰ Code used beyond validity period (5 minutes)
- 🔑 Incorrect mini program AppID and AppSecret configuration
Solutions:
// ✅ Correct openid acquisition process
wx.login({
success: (res) => {
if (res.code) {
// 🔥 Send to backend immediately, no delay
this.getOpenIdFromServer(res.code);
} else {
console.log('Login failed!' + res.errMsg);
}
}
});Important Reminder
Code validity is only 5 minutes, should be used immediately after acquisition, avoid caching or delayed processing.
⏱️ PrepayId Invalid or Expired
Root Cause Analysis:
- 🔗 API call did not return successfully
- ⏰ PrepayId validity is 2 hours, has expired
- 🌐 Network delay affects usage timing
Best Practice
After obtaining prepayId, invoke payment immediately to avoid expiration due to delays. It's recommended to set reasonable timeout reminders in frontend.
🔐 Payment Permission Issues
Mini program payment permission not enabled:
- ✅ Confirm JSAPI payment permission already enabled
- 🔗 Check binding relationship between mini program and merchant number
Incorrect payment directory configuration:
- ⚙️ Configure payment authorization directory in WeChat Pay merchant platform
- 🌐 Ensure payment page domain is within authorized directory range
Technical Support
📚 Reference Documents
- WeChat Official Documentation: Mini Program Payment Integration Guide
- WeChat Mini Program API: wx.login() Login Interface
- WeChat Pay API: wx.requestPayment() Payment Interface
🛠️ Recommended Tools
- WeChat Developer Tool: Official tool for mini program development and debugging
Pre-launch Checklist
Before going live in production environment, please ensure completion of following checks:
- Verify handling logic for all error scenarios
- Confirm correctness and idempotency of asynchronous notification processing
- Check accuracy of payment amount and order information
- Configure production environment HTTPS certificate and domain
- Set up appropriate log recording and monitoring alerts
