Swift中ASWebAuthenticationSession回调未触发的Stripe OAuth配置问题
问题根源
你当前的核心矛盾是:Stripe OAuth要求redirect_uri必须是合法的http/https域名,但你给ASWebAuthenticationSession传的callbackURLScheme是自定义的auth-completion,两者完全不匹配——系统无法把Stripe重定向的HTTPS URL关联到你的自定义scheme,自然触发不了回调。
解决步骤
1. 配置通用链接(Universal Links)关联你的域名
通用链接是苹果官方支持的、让HTTPS域名直接唤起APP的机制,刚好适配Stripe的要求:
- 在苹果开发者后台,给你的APPID开启「关联域名」(Associated Domains)权限,添加
applinks:www.brandboost.app - 在APP的
Info.plist里添加Associated Domains条目,值为applinks:www.brandboost.app;如果你的域名是HTTPS,无需额外配置NSAppTransportSecurity例外 - 在你的网站根目录(
https://www.brandboost.app/.well-known/)放置apple-app-site-association文件,内容示例:
{ "applinks": { "apps": [], "details": [ { "appID": "你的TeamID.你的BundleID", "paths": ["/auth-completion/*"] } ] } }
确保这个文件能通过HTTPS直接访问,且无任何重定向。
2. 调整ASWebAuthenticationSession代码
无需再传自定义的callbackURLScheme,直接初始化session,系统会通过通用链接把回调URL传递过来:
let authURL = URL(string: "https://connect.stripe.com/express/oauth/authorize?redirect_uri=https://www.brandboost.app/auth-completion&client_id=YOURTESTID")! let authSession = ASWebAuthenticationSession(url: authURL, callbackURLScheme: nil) { (callbackURL, error) in guard let callbackURL = callbackURL, error == nil else { // 处理授权错误逻辑 return } // 解析回调URL中的授权code let components = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false) let authCode = components?.queryItems?.first(where: { $0.name == "code" })?.value // 用authCode向Stripe请求访问令牌 } // UIKit环境需设置presentationContextProvider,SwiftUI需用UIViewControllerRepresentable包装session authSession.presentationContextProvider = self authSession.start()
SwiftUI环境下,需要将ASWebAuthenticationSession包装成UIViewControllerRepresentable组件,确保能正确获取展示上下文。
3. 验证Stripe后台配置
在Stripe Dashboard的「Connect设置」里,确保填写的redirect_uri和通用链接路径完全一致:https://www.brandboost.app/auth-completion,无多余斜杠或拼写错误。
4. 测试回调流程
- 先在模拟器或真机安装APP,验证通用链接生效:在Safari打开
https://www.brandboost.app/auth-completion,确认能直接唤起你的APP - 启动授权流程,完成Stripe授权后,系统会自动唤起APP,并将包含授权code的回调URL传递到session的completion handler中。
内容的提问来源于stack exchange,提问作者Trevor
相关产品推荐
相关产品推荐

