当 App 壳内嵌 H5 支付页出现跨域时,如何利用 postMessage 透传 token?
解读
在国内电商场景下,App 壳(WebView) 与 Magento 支付 H5 页 往往部署在不同域名下(如 app:// 与 https://pay.magento.cn),导致 Cookie、LocalStorage 无法共享,而支付环节又必须携带用户 token 完成身份校验。postMessage 是 WebView 与 H5 之间唯一安全且被微信、支付宝官方认可的跨域通信通道,因此面试官想确认候选人是否:
- 理解 WebView 与 H5 的双向通信模型
- 能在 Magento 端最小侵入地改造支付页,接收 token 并注入后续请求头
- 能防范中间人、重放、XSS 等国内监管重点关注的支付安全风险
知识点
- WebView 安全域:iOS WKWebView、Android AndroidX WebKit 在 file:// 或自定义 scheme 下默认禁止跨域读写 Cookie
- postMessage 双向通道:window.postMessage(data, origin) 与 window.addEventListener('message', handler)
- Magento 支付页路由:checkout/#payment、sales/guest/form、multishipping/checkout/payment 等,均通过 RequireJS 模块渲染
- token 载体:Bearer JWT 或 OAuth2 access_token,国内通常放在 Authorization 请求头,而非 Cookie
- 国密与合规:中国银联《移动支付技术规范》要求敏感信息不得明文落地,token 只能内存持有,且单次有效、有效期≤5 min
- 防重放:在 postMessage 中附带时间戳 + nonce + 签名(HMAC-SHA256),由 App 壳使用预置的 WebView 白名单公钥验签
- Hyvä/PWA Studio 适配:Hyvä 主题移除 Knockout.js,使用 Alpine.js,可直接监听 window.postMessage;PWA Studio 则需改写 checkoutPage 组件的 useEffect 钩子
答案
-
App 壳侧(Native)
a. 在加载 Magento 支付页之前,先通过原生登录接口换取一次性支付 token(有效期 300 s,附带 jti)。
b. 构造消息体:const payload = { type: 'PAYMENT_TOKEN', token: 'eyJhbGciOiJSUzI1NiIs...', ts: Date.now(), nonce: uuid.v4(), sign: hmac256(ts + nonce + token, appSecret) }c. WebView 加载完成后注入 JS:
webView.evaluateJavascript( "window.postMessage(" + JSON.stringify(payload) + ", 'https://pay.magento.cn');", null ); -
Magento H5 支付页(Hyvä 主题示例)
a. 在主题目录app/design/frontend/Vendor/hyva/Magento_Checkout/templates/onepage/payment.phtml顶部加入:<script> window.addEventListener('message', function (e) { if (e.origin !== 'https://app-embedded.magento.cn') return; const {type, token, ts, nonce, sign} = e.data; if (type !== 'PAYMENT_TOKEN') return; // 验签:向后端 /rest/V1/app/verifyMessage 发送 ts+nonce+token+sign fetch('/rest/V1/app/verifyMessage', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ts, nonce, token, sign}) }).then(r => r.json()).then(res => { if (res.valid) { // 注入 axios 默认头,后续支付接口统一携带 window.checkoutConfig.authorizationToken = token; axios.defaults.headers.common['Authorization'] = 'Bearer ' + token; } }); }, false); </script>b. 后端新增
VerifyMessageREST 接口,使用预共享的 appSecret 复算签名并缓存 nonce 防止重放。 -
生命周期管理
- token 注入成功后,立即调用
Magento_Checkout/js/action/place-order走原有队列,不再依赖 Cookie。 - 支付完成或 300 s 后,前端主动
delete axios.defaults.headers.common['Authorization']并通知 App 壳window.parent.postMessage({type: 'PAYMENT_DONE'}, '*'),由 Native 关闭 WebView。
- token 注入成功后,立即调用
拓展思考
- 如果微信内置浏览器也嵌入同一支付页,微信限制
file://协议下 postMessage 回传,此时可让 Native 把 token 写入微信 JSAPI 的 URL 锚点(#token=xxx),Magento 前端路由守卫解析锚点并立即销毁,避免泄露。 - 当 Magento 使用GraphQL checkout 时,可在
resolver层新增@appTokendirective,只允许请求头携带由上述流程注入的 Bearer token,拒绝 Cookie 中的 session,从而彻底解耦 WebView 与浏览器 Cookie 体系,满足国内监管“断直连”要求。 - 高并发场景下,postMessage 验签接口可下沉到 OpenResty + Lua,利用共享字典 1 ms 级防重放,减少 PHP-FPM 压力;同时 Magento 端通过消息队列异步消费支付结果,实现柔性事务与库存对冲,保障大促稳定性。