feat: 接入微信小程序支付
This commit is contained in:
83
miniprogram/pages/wechat-pay/index.js
Normal file
83
miniprogram/pages/wechat-pay/index.js
Normal file
@@ -0,0 +1,83 @@
|
||||
function parsePayParams(rawValue) {
|
||||
try {
|
||||
const params = JSON.parse(decodeURIComponent(String(rawValue || '')));
|
||||
if (!params || typeof params !== 'object') {
|
||||
return null;
|
||||
}
|
||||
return params;
|
||||
} catch (error) {
|
||||
console.error('[wechat-pay] parse params failed', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function requestPayment(payParams) {
|
||||
return new Promise((resolve) => {
|
||||
wx.requestPayment({
|
||||
timeStamp: String(payParams.timeStamp || ''),
|
||||
nonceStr: String(payParams.nonceStr || ''),
|
||||
package: String(payParams.package || ''),
|
||||
signType: payParams.signType || 'RSA',
|
||||
paySign: String(payParams.paySign || ''),
|
||||
success() {
|
||||
resolve('success');
|
||||
},
|
||||
fail(error) {
|
||||
const errMsg = error && error.errMsg ? error.errMsg : '';
|
||||
resolve(/cancel/i.test(errMsg) ? 'cancel' : 'fail');
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function appendPayResult(url, requestId, status) {
|
||||
const value = `${requestId}:${status}`;
|
||||
const hashIndex = String(url || '').indexOf('#');
|
||||
const baseUrl =
|
||||
hashIndex >= 0 ? String(url).slice(0, hashIndex) : String(url || '');
|
||||
const rawHash = hashIndex >= 0 ? String(url).slice(hashIndex + 1) : '';
|
||||
const params = new URLSearchParams(rawHash);
|
||||
params.set('wx_pay_result', value);
|
||||
return `${baseUrl}#${params.toString()}`;
|
||||
}
|
||||
|
||||
function notifyPreviousWebView(requestId, status) {
|
||||
const pages = getCurrentPages();
|
||||
const previousPage = pages.length >= 2 ? pages[pages.length - 2] : null;
|
||||
if (previousPage && typeof previousPage.setData === 'function') {
|
||||
previousPage.setData({
|
||||
webViewUrl: appendPayResult(
|
||||
previousPage.data.webViewUrl,
|
||||
requestId,
|
||||
status,
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Page({
|
||||
data: {
|
||||
title: '正在拉起支付',
|
||||
errorMessage: '',
|
||||
},
|
||||
|
||||
async onLoad(query) {
|
||||
const requestId = String(query.requestId || '');
|
||||
const payParams = parsePayParams(query.payParams);
|
||||
if (!requestId || !payParams) {
|
||||
this.setData({
|
||||
title: '支付失败',
|
||||
errorMessage: '缺少支付参数。',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const status = await requestPayment(payParams);
|
||||
notifyPreviousWebView(requestId, status);
|
||||
wx.navigateBack();
|
||||
},
|
||||
|
||||
handleBack() {
|
||||
wx.navigateBack();
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user