---
title: WeChat Pay Mini Program Payment Integration
permalink: /en/notes/paymentMethods/WeChatPay/miniProgram/
createTime: '2025/08/28 15:16:33'
description: >-
WeChat Mini Program payment integration is implemented through the unified order API, supporting payments within mini programs. Applicable to Mainland China, key features include no redirection, security mechanisms based on WeChat mini programs, standardized API call processes, and smooth and fast payment experience. Key parameters include user openid, mini program AppID, and order terminal identifier.
---
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
```mermaid
%%{init: {
'theme': 'base',
'themeVariables': {
'primaryColor': '#E3F2FD',
'primaryTextColor': '#0D47A1',
'primaryBorderColor': '#1976D2',
'lineColor': '#1565C0',
'secondaryColor': '#BBDEFB',
'tertiaryColor': '#90CAF9',
'background': '#F8FBFF',
'mainBkg': '#E3F2FD',
'secondBkg': '#BBDEFB',
'tertiaryBkg': '#90CAF9',
'actorBkg': '#2196F3',
'actorBorder': '#1976D2',
'actorTextColor': '#FFFFFF',
'actorLineColor': '#1565C0',
'signalColor': '#0D47A1',
'signalTextColor': '#0D47A1',
'c0': '#E8F4FD',
'c1': '#D1E7DD',
'c2': '#B3D9FF',
'c3': '#81C784',
'noteBkgColor': '#E1F5FE',
'noteTextColor': '#01579B',
'noteBorderColor': '#0288D1',
'loopTextColor': '#0D47A1',
'activationBkgColor': '#B3E5FC',
'activationBorderColor': '#0277BD'
}
}}%%
sequenceDiagram
participant User as π€ User
participant MiniApp as π± Mini Program Frontend
participant Merchant as πͺ Merchant Backend
participant PP as π PingPongCheckout Server
participant WeChat as π¬ WeChat Payment Platform
Note over User, WeChat: π WeChat Mini Program Payment Process
Note over User, MiniApp: π Preparation Phase: User initiates payment within mini program
User->>MiniApp: 1. User clicks payment button
MiniApp->>MiniApp: 2. Get user openid
Note right of MiniApp: Call wx.getUserProfile()
or use authorization login
MiniApp->>+Merchant: 3. Send payment request
Note right of Merchant: Include product information, amount
and user openid
Merchant->>Merchant: 4. Business verification
Note right of Merchant: Order verification, inventory check
risk control validation, etc.
Merchant->>+PP: 5. Call unified order API
Note right of PP: Include mini program specific parameters:
wxOpenId, wxAppId
device.orderTerminal=06
PP->>+WeChat: 6. Call WeChat unified order
Note right of WeChat: PSP calls WeChat
institution platform API
WeChat-->>-PP: 7. Return prepay_id and other parameters
PP-->>-Merchant: 8. Return payment parameters
Note right of PP: Include extraParam.wxPrepayId
and other necessary parameters
Merchant->>Merchant: 9. Construct mini program payment parameters
Note right of Merchant: Generate payment signature
prepare wx.requestPayment parameters
Merchant-->>-MiniApp: 10. π Return payment parameters to mini program
MiniApp->>MiniApp: 11. 1οΈβ£ Call wx.requestPayment()
Note right of MiniApp: Use returned parameters
to invoke WeChat payment
MiniApp->>+WeChat: 12. 2οΈβ£ Invoke WeChat payment interface
User->>WeChat: 13. 3οΈβ£ User completes payment authentication
WeChat-->>-MiniApp: 14. 4οΈβ£ Payment result callback
alt β
[Payment Success]
WeChat->>+PP: 15. 5οΈβ£ Asynchronous payment result notification
PP->>PP: 16. Process payment result
PP->>+Merchant: 17. 6οΈβ£ Asynchronous notification to merchant
Merchant-->>-PP: 18. Confirm notification received
PP-->>-WeChat: 19. Confirm processing completed
MiniApp->>+Merchant: 20. 7οΈβ£ Query payment result
Merchant-->>-MiniApp: 21. Return payment success status
MiniApp-->>User: 22. 8οΈβ£ Display payment success page
else β [Payment Failed/Canceled]
MiniApp-->>User: 23. Display payment failure information
Note right of MiniApp: User can retry payment
end
Note over User, PP: π― WeChat Mini Program Payment Process Completed
```
## Integration Navigation
::: note Tip
1. WeChat Mini Program payment is only available within WeChat Mini Program environment, requires obtaining user openid.
2. You need to complete basic configuration and payment permission application for WeChat Mini Program in advance.
3. 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, returns `extraParam.wxPrepayId` for 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()`](https://developers.weixin.qq.com/miniprogram/dev/api/payment/wx.requestPayment.html) in mini program to complete payment.
::: steps
1. **Get User Openid**
Use [`wx.login()`](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html) to get code, backend exchanges for openid
```javascript
wx.login({
success: (res) => {
// Send code to backend to exchange for openid
this.getOpenIdFromBackend(res.code);
}
});
```
2. **Initiate Payment Request**
Pass openid and other parameters to merchant server, merchant server calls Unified Order API
```javascript
wx.request({
url: 'https://yourapi.com/payment/create',
method: 'POST',
data: {
openid: this.data.openid,
amount: this.data.amount,
// Other order information
}
});
```
3. **Invoke WeChat Payment**
Use returned prepayId to call [`wx.requestPayment()`](https://developers.weixin.qq.com/miniprogram/dev/api/payment/wx.requestPayment.html)
```javascript
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);
}
});
```
4. **Handle Payment Result**
Listen for payment callback, query payment status
```javascript
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
```javascript
// 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**οΌ
```javascript
// β
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);
}
}
});
```
::: tip 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
::: tip 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](https://pay.weixin.qq.com/doc/v3/merchant/4012791911)
- **WeChat Mini Program API**: [wx.login() Login Interface](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html)
- **WeChat Pay API**: [wx.requestPayment() Payment Interface](https://developers.weixin.qq.com/miniprogram/dev/api/payment/wx.requestPayment.html)
### π οΈ Recommended Tools
- **WeChat Developer Tool**: Official tool for mini program development and debugging
---
::: important 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==
:::