微信小程序支付功能打通
This commit is contained in:
@@ -1,11 +1,14 @@
|
||||
import type { WechatJsapiPrepayParams } from '@dukang/shared-types';
|
||||
import { getRuntimePlatform } from './env';
|
||||
import { ensureJssdkReady } from './jssdk';
|
||||
import type { MiniProgramWx } from './types';
|
||||
|
||||
export type WechatPayInvokeConfig = {
|
||||
apiBase?: string;
|
||||
clientApp?: string;
|
||||
getAccessToken?: () => string | null;
|
||||
/** 显式指定运行端;Taro weapp 须传 mini */
|
||||
platform?: 'mini' | 'wechat-h5' | 'browser';
|
||||
};
|
||||
|
||||
/** wx.chooseWXPay 要求 timestamp 小写;服务端签名与 Bridge 使用 timeStamp */
|
||||
@@ -19,6 +22,13 @@ function toChooseWxPayOptions(prepay: WechatJsapiPrepayParams) {
|
||||
};
|
||||
}
|
||||
|
||||
function getMiniProgramWx(): MiniProgramWx | undefined {
|
||||
const g = globalThis as typeof globalThis & { wx?: MiniProgramWx };
|
||||
if (g.wx?.requestPayment) return g.wx;
|
||||
if (typeof window !== 'undefined' && window.wx?.requestPayment) return window.wx;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function invokeBridgePay(params: WechatJsapiPrepayParams): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const bridge = window.WeixinJSBridge;
|
||||
@@ -55,25 +65,37 @@ async function waitForWeixinBridge(): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
function invokeMiniProgramPay(prepay: WechatJsapiPrepayParams): Promise<void> {
|
||||
const wxApi = getMiniProgramWx();
|
||||
if (!wxApi?.requestPayment) {
|
||||
return Promise.reject(new Error('当前环境不支持微信支付'));
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
wxApi.requestPayment!({
|
||||
timeStamp: prepay.timeStamp,
|
||||
nonceStr: prepay.nonceStr,
|
||||
package: prepay.package,
|
||||
signType: prepay.signType,
|
||||
paySign: prepay.paySign,
|
||||
success: () => resolve(),
|
||||
fail: (err) => {
|
||||
const msg = err.errMsg || '支付失败';
|
||||
if (msg.includes('cancel')) reject(new Error('用户取消支付'));
|
||||
else reject(new Error(msg));
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** 调起微信支付 */
|
||||
export async function invokeWechatPay(
|
||||
prepay: WechatJsapiPrepayParams,
|
||||
config?: WechatPayInvokeConfig,
|
||||
): Promise<void> {
|
||||
const platform = getRuntimePlatform();
|
||||
const platform = config?.platform ?? getRuntimePlatform();
|
||||
|
||||
if (platform === 'mini' && window.wx?.requestPayment) {
|
||||
return new Promise((resolve, reject) => {
|
||||
window.wx!.requestPayment!({
|
||||
timeStamp: prepay.timeStamp,
|
||||
nonceStr: prepay.nonceStr,
|
||||
package: prepay.package,
|
||||
signType: prepay.signType,
|
||||
paySign: prepay.paySign,
|
||||
success: () => resolve(),
|
||||
fail: (err) => reject(new Error(err.errMsg || '支付失败')),
|
||||
});
|
||||
});
|
||||
if (platform === 'mini') {
|
||||
return invokeMiniProgramPay(prepay);
|
||||
}
|
||||
|
||||
if (platform === 'wechat-h5') {
|
||||
|
||||
Reference in New Issue
Block a user