소스 검색

Add native WeChat cashier for WebView orders

彭峰 1 일 전
부모
커밋
395bb79c5f

+ 2 - 1
app.json

@@ -9,7 +9,8 @@
       "name": "common",
       "pages": [
         "pages/web-view/index",
-        "pages/map-open/index"
+        "pages/map-open/index",
+        "pages/native-payment/index"
       ]
     },
     {

+ 96 - 0
common-page/pages/native-payment/index.js

@@ -0,0 +1,96 @@
+const ORDER_ID = /^[A-Za-z0-9]{10,32}$/;
+
+function loginCode() {
+    return new Promise((resolve, reject) => wx.login({
+        success: result => result.code ? resolve(result.code) : reject(new Error()),
+        fail: reject,
+    }));
+}
+
+function requestPayment(params) {
+    return new Promise((resolve, reject) => wx.requestPayment({
+        timeStamp: params.timeStamp,
+        nonceStr: params.nonceStr,
+        package: params.package,
+        signType: params.signType,
+        paySign: params.paySign,
+        success: resolve,
+        fail: reject,
+    }));
+}
+
+Page({
+    data: { title: '确认微信支付', amount: '', paying: false, valid: false, error: '' },
+
+    onLoad(options) {
+        const { orderId, kind } = options;
+        const expectedFen = Number(options.fen);
+        const valid = typeof orderId === 'string' && ORDER_ID.test(orderId) &&
+            ['membership', 'recharge'].includes(kind) && Number.isSafeInteger(expectedFen) && expectedFen > 0;
+        if (!valid) {
+            this.setData({ error: '缺少有效订单,请返回重新下单。' });
+            return;
+        }
+        const pages = getCurrentPages();
+        const opener = pages[pages.length - 2];
+        if (opener?.route === 'common-page/pages/web-view/index') this.opener = opener;
+        this.payment = { orderId, kind, expectedFen };
+        this.setData({
+            valid,
+            amount: (expectedFen / 100).toFixed(2),
+            title: kind === 'membership' ? '会员续费' : '陪伴值充值',
+        });
+    },
+
+    async pay() {
+        if (!this.payment || this.data.paying || this.returned) return;
+        const Parse = getApp().Parse;
+        if (!Parse?.User.current()?.id) {
+            this.setData({ error: '请在小程序登录同一账号,然后返回订单重试。' });
+            return;
+        }
+        this.setData({ paying: true, error: '' });
+        let phase = 'prepare';
+        try {
+            const params = await Parse.Cloud.run('prepareYubanMiniPayment', {
+                ...this.payment, loginCode: await loginCode(),
+            });
+            if (this.returned) return;
+            phase = 'cashier';
+            await requestPayment(params);
+            this.finish('submitted');
+        } catch (error) {
+            if (!this.returned) {
+                if (phase === 'cashier' && /cancel/i.test(error?.errMsg || '')) {
+                    this.finish('cancelled');
+                } else {
+                    this.setData({ error: phase === 'cashier' ? '微信支付未完成,请返回核对订单。' :
+                        error?.code === 209 ? '小程序微信身份与订单账号不一致,请重新登录。' :
+                            error?.code === 142 ? '订单或收银台参数无法确认,请返回核对。' : '暂时无法打开微信支付,请稍后重试。' });
+                }
+            }
+        } finally {
+            if (!this.returned) this.setData({ paying: false });
+        }
+    },
+
+    notifyParent(outcome) {
+        if (this.returned || !this.payment) return;
+        this.returned = true;
+        this.opener?.returnFromNativePayment?.(this.payment, outcome);
+    },
+
+    finish(outcome) {
+        if (this.returned) return;
+        this.notifyParent(outcome);
+        wx.navigateBack();
+    },
+
+    back() {
+        if (!this.data.paying) this.finish('cancelled');
+    },
+
+    onUnload() {
+        this.notifyParent(this.data.paying ? 'pending' : 'cancelled');
+    },
+});

+ 4 - 0
common-page/pages/native-payment/index.json

@@ -0,0 +1,4 @@
+{
+  "navigationStyle": "default",
+  "navigationBarTitleText": "微信支付"
+}

+ 7 - 0
common-page/pages/native-payment/index.wxml

@@ -0,0 +1,7 @@
+<view class="checkout">
+  <view class="checkout-title">{{title}}</view>
+  <view wx:if="{{valid}}" class="checkout-amount">¥{{amount}}</view>
+  <view class="checkout-error" wx:if="{{error}}">{{error}}</view>
+  <button wx:if="{{valid}}" type="primary" bindtap="pay" loading="{{paying}}" disabled="{{paying}}">确认支付</button>
+  <button bindtap="back" disabled="{{paying}}">返回订单</button>
+</view>

+ 5 - 0
common-page/pages/native-payment/index.wxss

@@ -0,0 +1,5 @@
+.checkout { padding: 48rpx; }
+.checkout-title { font-size: 36rpx; font-weight: 600; }
+.checkout-amount { margin: 32rpx 0; font-size: 58rpx; font-weight: 600; }
+.checkout-error { margin: 24rpx 0; color: #a82727; }
+.checkout button { margin: 24rpx 0; }

+ 13 - 148
common-page/pages/web-view/index.js

@@ -17,16 +17,6 @@ Page({
     data: {
         path: "",
         currentTitle: "", // 当前标题
-        miniPayVisible: false,
-        miniPayPrice: 0,
-        miniPayTradeNo: "",
-        miniPayOrderId: "",
-        miniPayOrderType: "shopgoods",
-        miniPayShowType: "all",
-        miniPayShowBonus: false,
-        miniPayProfileId: "",
-        miniPayProcessing: false,
-        miniPayRequestContext: null,
     },
 
     // 标题轮询定时器
@@ -221,149 +211,24 @@ Page({
         try {
             const messages = e.detail.data || [];
 
-            // 找到最后一个标题更新消息
-            let lastTitleMessage = null;
-            let lastPayMessage = null;
-            for (let i = messages.length - 1; i >= 0; i--) {
-                const msg = messages[i];
-                if (msg.type === 'updateTitle' && msg.title) {
-                    lastTitleMessage = msg;
-                }
-                if (!lastPayMessage && msg.type === 'requestMiniPay') {
-                    lastPayMessage = msg;
-                }
-                if (lastTitleMessage && lastPayMessage) {
-                    break;
-                }
-            }
-
-            // 更新标题
-            if (lastTitleMessage) {
-                this.setNavigationTitle(lastTitleMessage.title);
-            }
-
-            if (lastPayMessage) {
-                this.handleMiniPayRequest(lastPayMessage.payload || {});
-            }
-        } catch (error) {
-            console.error('❌ 处理消息失败:', error);
-        }
-    },
-
-    normalizeMiniPayPayload(payload = {}) {
-        const price = Number(payload.price);
-        return {
-            tradeNo: payload.tradeNo || '',
-            price: Number.isFinite(price) ? price : 0,
-            orderId: payload.orderId || '',
-            orderType: payload.orderType || 'shopgoods',
-            showType: payload.showType || 'all',
-            showBonus: !!payload.showBonus,
-            profileId: payload.profileId || '',
-            scene: payload.scene || '',
-            bizId: payload.bizId || '',
-            callbackUrl: payload.callbackUrl || ''
-        };
-    },
-
-    handleMiniPayRequest(payload = {}) {
-        const parsed = this.normalizeMiniPayPayload(payload);
-        if (!parsed.tradeNo) {
-            wx.showToast({
-                title: '支付参数缺少tradeNo',
-                icon: 'none'
-            });
-            return;
-        }
-        if (parsed.price < 0) {
-            wx.showToast({
-                title: '支付金额无效',
-                icon: 'none'
-            });
-            return;
-        }
-        if (this.data.miniPayProcessing) {
-            wx.showToast({
-                title: '支付进行中,请稍后',
-                icon: 'none'
-            });
-            return;
+            // WebView messages can be delayed. They are used for the navigation title only.
+            const title = [...messages].reverse().find(msg => msg.type === 'updateTitle' && msg.title);
+            if (title) this.setNavigationTitle(title.title);
+        } catch (_) {
+            // Ignore malformed WebView messages.
         }
-
-        this.setData({
-            miniPayVisible: false,
-            miniPayPrice: parsed.price,
-            miniPayTradeNo: parsed.tradeNo,
-            miniPayOrderId: parsed.orderId,
-            miniPayOrderType: parsed.orderType,
-            miniPayShowType: parsed.showType,
-            miniPayShowBonus: parsed.showBonus,
-            miniPayProfileId: parsed.profileId,
-            miniPayProcessing: true,
-            miniPayRequestContext: parsed
-        }, () => {
-            const paymentComp = this.selectComponent('#miniPayComponent');
-            if (!paymentComp || typeof paymentComp.pay !== 'function') {
-                this.setData({ miniPayProcessing: false });
-                wx.showToast({
-                    title: '支付组件未就绪',
-                    icon: 'none'
-                });
-                return;
-            }
-            paymentComp.pay();
-        });
     },
 
-    onMiniPayResult(e) {
-        const detail = e.detail || {};
-        const payState = detail.params;
-        const result = {
-            type: 'miniPayResult',
-            payload: {
-                success: payState === 'ok',
-                tradeNo: detail.no || this.data.miniPayTradeNo,
-                payType: detail.type || 'wxpay',
-                cancelled: payState === 'Cancel the payment',
-                errMsg: payState && payState !== 'ok' && payState !== 'Cancel the payment'
-                    ? (typeof payState === 'string' ? payState : (payState.errMsg || ''))
-                    : ''
-            }
-        };
-
+    returnFromNativePayment(payment, outcome) {
+        const route = payment.kind === 'membership' ? 'membership-renewal' :
+            payment.kind === 'recharge' ? 'account-recharge' : '';
+        if (!route || !/^[A-Za-z0-9]{10,32}$/.test(payment.orderId) ||
+            !['submitted', 'cancelled', 'pending'].includes(outcome)) return;
         this.setData({
-            miniPayVisible: false,
-            miniPayProcessing: false
+            path: withQuery('https://www.yuban.co/user-profile/' + route, {
+                miniPayOrder: payment.orderId, miniPayOutcome: outcome, miniPayReturnAt: Date.now(),
+            }),
         });
-        this.notifyH5MiniPayResult(result);
-    },
-
-    notifyH5MiniPayResult(result) {
-        const ctx = this.data.miniPayRequestContext || {};
-        console.log('miniPayResult:', result);
-
-        // web-view 不支持直接由小程序向 H5 反向 postMessage,
-        // 若 H5 传入 callbackUrl,则通过刷新 web-view URL 回传支付结果。
-        if (!ctx.callbackUrl) return;
-        try {
-            const callback = requestedTarget({path:ctx.callbackUrl});
-            if (!callback) return;
-            const query = [
-                'miniPayResult=1',
-                `success=${result.payload.success ? 1 : 0}`,
-                `tradeNo=${encodeURIComponent(result.payload.tradeNo || '')}`,
-                `payType=${encodeURIComponent(result.payload.payType || '')}`,
-                `cancelled=${result.payload.cancelled ? 1 : 0}`,
-                `errMsg=${encodeURIComponent(result.payload.errMsg || '')}`
-            ].join('&');
-            const hashAt = callback.indexOf('#');
-            const base = hashAt < 0 ? callback : callback.slice(0,hashAt);
-            const hash = hashAt < 0 ? '' : callback.slice(hashAt);
-            const callbackPath = base + (base.includes('?') ? '&' : '?') + query + hash;
-            this.setData({ path: callbackPath });
-        } catch (error) {
-            console.error('❌ 回传支付结果失败:', error);
-        }
     },
 
     /**

+ 0 - 12
common-page/pages/web-view/index.wxml

@@ -1,13 +1 @@
 <web-view wx:if="{{path}}" src="{{path}}" bindmessage="handleMessage"></web-view>
-<payment
-  id="miniPayComponent"
-  show="{{miniPayVisible}}"
-  price="{{miniPayPrice}}"
-  tradeNo="{{miniPayTradeNo}}"
-  orderId="{{miniPayOrderId}}"
-  orderType="{{miniPayOrderType}}"
-  showType="{{miniPayShowType}}"
-  showBonus="{{miniPayShowBonus}}"
-  profileId="{{miniPayProfileId}}"
-  bind:payResult="onMiniPayResult"
-/>

+ 59 - 0
test/native-webview-payment.test.js

@@ -0,0 +1,59 @@
+const assert = require('node:assert/strict');
+const { readFileSync } = require('node:fs');
+const { test } = require('node:test');
+const vm = require('node:vm');
+
+function fixture({ result, prepareFails } = {}) {
+    let definition;
+    const calls = [];
+    const opener = {
+        route: 'common-page/pages/web-view/index',
+        returnFromNativePayment: (order, outcome) => calls.push(['return', order.orderId, outcome]),
+    };
+    const app = { Parse: {
+        User: { current: () => ({ id: 'fixture-user' }) },
+        Cloud: { run: async (name, input) => {
+            calls.push([name, input.orderId, input.loginCode]);
+            if (prepareFails) throw { code: 209 };
+            return { timeStamp: '1796000000', nonceStr: 'fixture', package: 'prepay_id=fixture', paySign: 'stub', signType: 'MD5' };
+        } },
+    } };
+    const wx = {
+        login: ({ success }) => success({ code: 'fixture-code' }),
+        requestPayment: ({ package: payPackage, success, fail }) => {
+            calls.push(['cashier', payPackage]);
+            if (result) fail({ errMsg: result });
+            else success();
+        },
+        navigateBack: () => calls.push(['back']),
+    };
+    vm.runInNewContext(readFileSync('common-page/pages/native-payment/index.js', 'utf8'), {
+        Page: x => { definition = x; }, getApp: () => app, getCurrentPages: () => [opener, {}], wx,
+    });
+    const page = { ...definition, data: { ...definition.data }, setData(patch) { Object.assign(this.data, patch); } };
+    page.onLoad({ orderId: 'testOrder1', kind: 'recharge', fen: '9900' });
+    return { page, calls };
+}
+
+test('native cashier prepares the same order once and reports submitted, not settled', async () => {
+    const { page, calls } = fixture();
+    await Promise.all([page.pay(), page.pay()]);
+    page.onUnload();
+    assert.deepEqual(calls, [
+        ['prepareYubanMiniPayment', 'testOrder1', 'fixture-code'], ['cashier', 'prepay_id=fixture'],
+        ['return', 'testOrder1', 'submitted'], ['back'],
+    ]);
+});
+
+test('native cancellation returns the order without marking it paid', async () => {
+    const { page, calls } = fixture({ result: 'requestPayment:fail cancel' });
+    await page.pay();
+    assert.deepEqual(calls.at(-2), ['return', 'testOrder1', 'cancelled']);
+});
+
+test('backend validation failure never invokes the native cashier', async () => {
+    const { page, calls } = fixture({ prepareFails: true });
+    await page.pay();
+    assert.equal(calls.length, 1);
+    assert.match(page.data.error, /身份.*不一致/);
+});