ASWebAuthenticationSession
Para el uso en iOS, usar ASWebAuthenticationSession es uno de los enfoques recomendados.
Después de crear la transacción y obtener el enlace de la transacción, se recomienda la siguiente implementación:
- En tu flujo habitual (que incluye Verificación de Tarjeta No Presente), abrirás el ASWebAuthenticationSession con el enlace generado a través de la API.
- Puedes personalizar esta apertura de la forma que mejor funcione para tu app.
- Monitorearás si la URL ha cambiado (hacia
redirectUrl) y luego cerrarás la página.
Para que el flujo funcione, debes seguir los siguientes pasos:
Paso 1: Crear el controlador de autenticación de pago
El primer paso es crear el controlador de autenticación de pago. Para hacerlo, crea una clase llamada IDPayAuthenticationController (o cualquier nombre que prefieras).
A continuación, importa el framework AuthenticationServices en la parte superior de la clase.
Declara la clase como NSObject e implementa el protocolo ASWebAuthenticationPresentationContextProviding.
El resultado debería ser:
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()
}
}
Paso 2: Implementar la autenticación
Abre el archivo donde realizarás la autenticación y agrega los imports necesarios (en nuestro ejemplo, lo hacemos en ContentView.swift).
import SwiftUI
import AuthenticationServices
Para controlar el estado de la autenticación, crearemos una propiedad @State.
@State private var isAuthenticated = false
Crea una instancia de la clase IDPayAuthenticationController fuera del body de la estructura ContentView.
let idPayController = IDPayAuthenticationController()
Para validar el pago, crea una función llamada 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()
}
Recuerda cambiar la URL URL_AUTHENTICATION por la URL de autenticación recibida en tu transacción, y también el callbackURLScheme BUNDLE por la redirección proporcionada al crear tu transacción (recomendamos usar el Bundle Identifier de tu app).
Es importante configurar prefersEphemeralWebBrowserSession como true para garantizar una autenticación única por transacción.
Se requieren algunos permisos para que funcione correctamente, tales como:
- Cámara
- Geolocalización
Para obtener más información, recomendamos leer la documentación oficial de ASWebAuthenticationSession.