Эх сурвалжийг харах

Keep the live H5 checkout bridge alongside native cashier

彭峰 17 цаг өмнө
parent
commit
cb11e0b59d

+ 152 - 5
common-page/pages/web-view/index.js

@@ -17,6 +17,16 @@ Page({
     data: {
         path: "",
         currentTitle: "", // 当前标题
+        miniPayVisible: false,
+        miniPayPrice: 0,
+        miniPayTradeNo: "",
+        miniPayOrderId: "",
+        miniPayOrderType: "shopgoods",
+        miniPayShowType: "all",
+        miniPayShowBonus: false,
+        miniPayProfileId: "",
+        miniPayProcessing: false,
+        miniPayRequestContext: null,
     },
 
     // 标题轮询定时器
@@ -211,12 +221,121 @@ Page({
         try {
             const messages = e.detail.data || [];
 
-            // 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.
+            // 找到最后一个标题更新消息
+            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;
+        }
+
+        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 || ''))
+                    : ''
+            }
+        };
+
+        this.setData({
+            miniPayVisible: false,
+            miniPayProcessing: false
+        });
+        this.notifyH5MiniPayResult(result);
     },
 
     returnFromNativePayment(payment, outcome) {
@@ -231,6 +350,34 @@ Page({
         });
     },
 
+    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);
+        }
+    },
+
     /**
      * 设置导航栏标题(统一方法)
      */

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

@@ -1 +1,13 @@
 <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"
+/>

+ 23 - 0
test/web-view-share.test.cjs

@@ -88,3 +88,26 @@ test('ordinary in-app launches retain the original auth and carousel paths', asy
   assert.ok(carousel.data.path.startsWith(origin + '/home?'));
   assert.match(carousel.data.path, /fromStartup=1/);
 });
+
+test('the live H5 payment message still reaches the existing component', () => {
+  const page = newPage();
+  let calls = 0;
+  page.setData = function (update, done) { Object.assign(this.data, update); done?.(); };
+  page.selectComponent = selector => {
+    assert.equal(selector, '#miniPayComponent');
+    return { pay() { calls += 1; } };
+  };
+  page.handleMessage({ detail: { data: [{ type: 'requestMiniPay', payload: {
+    tradeNo: 'ORDER123456', orderId: 'testOrder1', price: 2,
+  } }] } });
+  assert.equal(calls, 1);
+  assert.equal(page.data.miniPayTradeNo, 'ORDER123456');
+});
+
+test('the native cashier still returns to the intended H5 order page', () => {
+  const page = newPage();
+  page.returnFromNativePayment({ orderId: 'testOrder1', kind: 'recharge' }, 'submitted');
+  assert.match(page.data.path, /^https:\/\/www\.yuban\.co\/user-profile\/account-recharge\?/);
+  assert.match(page.data.path, /miniPayOrder=testOrder1/);
+  assert.match(page.data.path, /miniPayOutcome=submitted/);
+});