徐锦洪 发表于 7 天前

iOS 微信 H5 付出无法返回 APP 的问题

针对 iOS 微信 H5 付出无法返回 APP 的问题,结合 Universal Links 的办理方案,以下是综合多篇技术文档和实践经验的完整指南:
一、核心原理

微信 H5 付出默认通过 redirect_url 参数控制付出后跳转,但 iOS 的沙盒机制会逼迫在 Safari 中打开该 URL。通过 ​Universal Links 可绕过此限制,实现从微信直接返回 APP。其优势在于无需用户确认跳转,且支持 HTTPS 安全校验。
二、具体实现步骤

1. 配置 Universal Links

(1) 服务端配置


[*]创建 apple-app-site-association 文件(无后缀),内容示比方下: {
"applinks": {
    "details": [
      {
      "appIDs": ["TeamID.com.yourdomain.app"],
      "components": [
          { "/": "/wxpay/*", "?": { "redirect_url": "*" } }
      ]
      }
    ]
}
}
[*]将该文件摆设到 HTTPS 服务器的根目次或 .well-known 子目次。
(2) 客户端配置


[*]在 Xcode 的 Signing & Capabilities 中启用 Associated Domains,填写格式:applinks:yourdomain.com 
[*]在 AppDelegate 中添加 Universal Links 处理惩罚逻辑: func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping (?) -> Void) -> Bool {
    guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
          let url = userActivity.webpageURL else { return false }
    // 解析支付结果并跳转对应页面
    NotificationCenter.default.post(name: .wxPayCallback, object: url.query)
    return true
}
2. 付出请求改造

(1) 修改 redirect_url 参数


[*]将 H5 付出请求中的 redirect_url 替换为 Universal Links 格式:
// 前端示例(需 URL 编码)
const universalLink = 'https://yourdomain.com/wxpay?order_id=123';
window.location.href = `https://wx.tenpay.com/...&redirect_url=${encodeURIComponent(universalLink)}`; 留意:yourdomain.com 需与 apple-app-site-association 中配置的域名一致。
(2) 请求头添加 Refere。
3. 付出结果处理惩罚

(1) Universal Links 回调解析


[*]当用户付出完成后,微信会通过 Universal Links 唤醒 APP,在 AppDelegate 中解析 URL 参数: func handlePaymentCallback(url: URL) {
    let params = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems
    let status = params?.first(where: { $0.name == "result" })?.value
    if status == "success" {
      // 刷新订单状态页面
      NotificationCenter.default.post(name: .refreshOrderStatus, object: nil)
    }
}
(2) WebView 状态恢复


[*]通过通知机制逼迫刷新 WebView: NotificationCenter.default.addObserver(self, selector: #selector(reloadWebView), name: .wxPayCallback, object: nil)

@objc func reloadWebView() {
    webView.load(URLRequest(url: URL(string: "https://yourdomain.com/order/123")!))
}
三、避坑指南


[*] ​Universal Links 缓存问题
iOS 可能缓存关联域配置,测试时需在「设置」-「开发者」-「Associated Domains Development」中清除缓存。
[*] ​Referer 格式要求
部分案例表明,Referer 必要以 :// 末端(如 https://yourdomain.com://)才能通过微信校验。
[*] ​HTTPS 逼迫要求
Universal Links 必须使用 HTTPS 且证书有用,测试环境可用 Let's Encrypt 免费证书。
[*] ​微信白名单限制
需确保 yourdomain.com 已添加到微信商户平台的「H5付出授权域名」列表中。
四、扩展方案(混合模式)

若 Universal Links 配置复杂,可结合 URL Scheme 作为备用方案:

[*]​双重回调地址 const redirectURL = isIOS ? universalLink : 'your_app_scheme://wxpay';
[*]​AppDelegate 兼容处理惩罚
同时监听 Universal Links 和 URL Scheme 回调。
通过上述方案,可实现微信 H5 付出在 iOS 端的闭环跳转。建议在关键节点添加日志追踪,并和谐后端配合举行付出状态轮询,以应对网络延迟等非常场景。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: iOS 微信 H5 付出无法返回 APP 的问题