Payment and Login (WeChat Pay, Alipay)
Payment and Login (WeChat Pay, Alipay)
uni-app, as a cross-platform development framework, supports the integration of WeChat Pay and Alipay. These two payment methods are highly frequent in mobile applications, and developers need to be familiar with their integration processes and common issue handling.
WeChat Pay Integration
The implementation of WeChat Pay in uni-app primarily relies on the uni.requestPayment
API. Before integration, ensure that the application has been registered and approved on the WeChat Open Platform.
// WeChat Pay example code
uni.requestPayment({
provider: 'wxpay',
orderInfo: {}, // Payment parameters returned by the server
success: function(res) {
console.log('Payment successful:' + JSON.stringify(res));
},
fail: function(err) {
console.log('Payment failed:' + JSON.stringify(err));
}
});
Key parameter explanations:
timeStamp
must be a string-type timestampnonceStr
a random string within 32 characterspackage
fixed format asprepay_id=xxx
signType
signature algorithm, usuallyMD5
orHMAC-SHA256
Common issue handling:
- Signature error: Verify the merchant key is correct and parameter order matches the documentation
- No callback after payment completion: Check if the app was killed by the system; consider adding a local storage flag
- Cross-platform compatibility issues: iOS and Android package names/bundle IDs must match those registered on the WeChat Open Platform
Alipay Implementation
Alipay integration is relatively simpler but requires attention to differences between sandbox and production environments. uni-app also provides a unified API:
// Alipay example
uni.requestPayment({
provider: 'alipay',
orderInfo: 'partner="2088xxxx"&seller_id="xxx@xxx.com"&...', // Complete order string
success: function(res) {
uni.showToast({ title: 'Payment successful' });
},
fail: function(err) {
console.error('Payment exception', err);
}
});
Special notes:
- The order string must include all required parameters
- Android platform requires application signature configuration
- Server-side must implement asynchronous notification verification
Payment Status Verification
Payment status verification after success should be completed on the server side, not relying on client-side returns. Recommended flow:
- Client receives payment success callback
- Query order status from the server
- Update UI based on server response
function verifyPayment(orderNo) {
uni.request({
url: '/api/payment/verify',
data: { orderNo },
success(res) {
if(res.data.paid) {
// Actual payment success handling
} else {
// Payment incomplete handling
}
}
});
}
Multi-Platform Compatibility Handling
Different platforms have varying payment implementations, requiring compatibility handling:
// Platform detection example
let provider;
// #ifdef MP-WEIXIN
provider = 'wxpay';
// #endif
// #ifdef APP-PLUS
provider = 'alipay'; // Default to Alipay
// #endif
uni.requestPayment({
provider,
// ...other parameters
});
Login Authorization Integration
Payments often need to integrate with login systems. WeChat login example:
uni.login({
provider: 'weixin',
success(res) {
const code = res.code; // Obtain temporary credential
uni.request({
url: '/api/wxlogin',
method: 'POST',
data: { code },
success(userInfo) {
// Login success handling
}
});
}
});
Alipay authorization login differs slightly:
uni.getUserInfo({
provider: 'alipay',
success(res) {
const authCode = res.code;
// Send authCode to server to exchange for user info
}
});
Security Considerations
- Payment keys must be stored on the server; never include them in client-side code
- Amount verification must be completed on the server
- Regularly check certificate and key validity
- Implement anti-replay attack mechanisms, such as order number uniqueness verification
- Key logs require desensitization
Performance Optimization Suggestions
For high-frequency payment scenarios:
- Pre-create orders: Create them before users enter the payment flow
- Cache payment results locally: Avoid duplicate queries
- Combine payment verification requests: Reduce network overhead
- Use WebSocket to receive payment result notifications
// WebSocket listening example
const socket = uni.connectSocket({
url: 'wss://yourdomain.com/ws'
});
socket.onMessage(res => {
const data = JSON.parse(res.data);
if(data.type === 'payment_success') {
// Update order status
}
});
Error Handling Mechanism
Comprehensive error handling should include:
- Network exception retry mechanism
- Automatic cancellation on payment timeout
- Guidance to alternative payment methods for insufficient balance
- Fallback solutions during system congestion
// Payment example with retry
function payWithRetry(orderInfo, retryCount = 3) {
uni.requestPayment({
provider: 'wxpay',
orderInfo,
success() { /*...*/ },
fail(err) {
if(retryCount > 0) {
setTimeout(() => payWithRetry(orderInfo, retryCount - 1), 1000);
} else {
uni.showModal({
content: 'Payment failed, please try again later',
showCancel: false
});
}
}
});
}
Testing Verification Points
Payment functionality testing must cover:
- Normal payment flow
- Payment interruption recovery
- Duplicate payment handling
- Refund flow verification
- Performance under different network environments
- Internationalization scenarios (e.g., multi-currency payments)
Recommend establishing automated test cases:
// Test case example
describe('Payment module test', () => {
it('Should complete WeChat Pay successfully', async () => {
const res = await mockPayment('wxpay');
expect(res).toHaveProperty('paid', true);
});
it('Should handle payment timeout', async () => {
mockNetworkTimeout();
const res = await payWithRetry(testOrder, 2);
expect(res).toHaveProperty('error', 'timeout');
});
});
User Experience Optimization
Details to improve payment conversion:
- Keep the payment process to no more than 3 steps
- Automatically remember frequently used payment methods
- Provide clear payment progress feedback
- Give specific reasons and solutions for failures
- Guide next steps after payment completion
// Payment progress feedback example
uni.showLoading({
title: 'Processing payment',
mask: true
});
uni.requestPayment({
// ...parameters
complete() {
uni.hideLoading();
}
});
Server-Side Requirements
Client-side payments require server-side support for the following interfaces:
- Pre-payment order creation interface
- Payment result query interface
- Refund processing interface
- Payment notification verification interface
- Order status synchronization interface
Typical interface response format:
{
"code": 200,
"data": {
"orderNo": "20231101123456",
"paid": true,
"amount": 99.00,
"paymentTime": "2023-11-01 12:34:56"
}
}
Payment Data Analysis
Recommended payment-related metrics to collect:
- Payment success rate
- Average payment duration
- Proportion of payment methods
- Failure reason distribution
- User payment behavior paths
Can be reported via custom events:
uni.reportAnalytics('payment_start', {
payment_type: 'wxpay',
amount: 100
});
International Payment Adaptation
For overseas users, consider:
- Automatic currency conversion
- Integration of local mainstream payment methods
- Multi-language payment interfaces
- Exchange rate fluctuation handling
- Cross-border payment compliance requirements
// Multi-currency payment example
function formatCurrency(amount, currency) {
return new Intl.NumberFormat(undefined, {
style: 'currency',
currency
}).format(amount);
}
// Output: ¥100.00 or $100.00 etc.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn