ASWebAuthenticationSession
对于 iOS 使用场景,使用 ASWebAuthenticationSession 是推荐的方式之一。
创建交易并获取交易链接后,建议按以下方式实现:
- 在您的常规流程(包含无卡验证)中,使用通过 API 生成的链接打开 ASWebAuthenticationSession。
- 您可以按最适合您应用的方式自定义此打开方式。
- 监控 URL 是否已变化(变为
redirectUrl),然后关闭该页面。
要使该流程正常运行,您需要按照以下步骤操作:
第一步:创建支付身份验证控制器
第一步是创建支付身份验证控制器。为此,请创建一个名为 IDPayAuthenticationController 的类(或您喜欢的任何名称)。
接下来,在类的顶部导入 AuthenticationServices 框架。
将该类声明为 NSObject,并实现 ASWebAuthenticationPresentationContextProviding 协议。
结果应如下所示:
import AuthenticationServices
class IDPayAuthenticationController: NSObject, ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
if let mainWindow = windowScene.windows.first {
return mainWindow
}
}
return ASPresentationAnchor()
}
}
第二步:实现身份验证
打开您将执行身份验证的文件,并添加必要的导入项(在我们的示例中,我们在 ContentView.swift 中进行此操作)。
import SwiftUI
import AuthenticationServices
为控制身份验证状态,我们将创建一个 @State 属性。
@State private var isAuthenticated = false
在 ContentView 结构体的 body 之外,创建 IDPayAuthenticationController 类的实例。
let idPayController = IDPayAuthenticationController()
要验证支付,请创建一个名为 authenticatePayment 的函数。
func authenticatePayment() {
guard let url = URL(string: "URL_AUTHENTICATION") else { return }
var session: ASWebAuthenticationSession?
session = ASWebAuthenticationSession(url: url, callbackURLScheme: "BUNDLE") { callbackURL, error in
guard callbackURL != nil else {
if let error = error {
return print("Error during authentication: \(error.localizedDescription)")
}
return
}
// Processes the callback URL to check whether authentication succeeded
session?.cancel()
isAuthenticated = true
}
session?.presentationContextProvider = idPayController
session?.prefersEphemeralWebBrowserSession = true
session?.start()
}
危险
请记得将 URL URL_AUTHENTICATION 更改为您交易中收到的身份验证 URL,并将 callbackURLScheme 中的 BUNDLE 更改为创建交易时提供的重定向地址(我们建议使用您应用的 Bundle Identifier)。
备注
请务必将 prefersEphemeralWebBrowserSession 设置为 true,以确保每笔交易都拥有唯一的身份验证。
备注
需要一些权限才能正常运行,例如:
- 摄像头
- 地理位置
如需了解更多信息,我们建议阅读官方 ASWebAuthenticationSession 文档。