Captura no Ionic
Abra a captura a partir de um app Ionic com um plugin Capacitor local.
Seu back-end cria o processo no Human Plugin com um fluxo Journey e um callbackUri que usa o URL scheme do seu app. Um plugin Capacitor local abre o link da resposta em Custom Tabs no Android e em ASWebAuthenticationSession no iOS. Quando a captura termina, o plugin resolve e o app assume o controle.
Guarde o id do Human Plugin retornado pelo create. Seu back-end lê o resultado com ele.
Pré-requisitos
- Ionic com Capacitor 4 ou superior
- Xcode 14 ou superior, e Android Studio
- Um URL scheme exclusivo do seu app, como
myapp
1. Crie o processo com o seu scheme
Seu back-end envia o scheme como callbackUri:
{
"flow": "humantoken",
"clientId": "client-a",
"correlationId": "order-1001",
"credential": { "type": "DUI_TYPE_NG_BVN", "value": "<document number>" },
"callbackUri": "myapp://callback"
}
e devolve id e link ao app.
2. Defina a interface do plugin
// src/plugins/capture-plugin.ts
import { registerPlugin } from '@capacitor/core';
export interface CapturePlugin {
openSession(options: { url: string }): Promise<{ callbackUrl: string }>;
}
const Capture = registerPlugin<CapturePlugin>('CapturePlugin');
export default Capture;
3. Implemente o plugin iOS
import Capacitor
import AuthenticationServices
@objc(CapturePlugin)
public class CapturePlugin: CAPPlugin, ASWebAuthenticationPresentationContextProviding {
private var session: ASWebAuthenticationSession?
@objc func openSession(_ call: CAPPluginCall) {
guard let urlString = call.getString("url"),
let url = URL(string: urlString) else {
call.reject("Invalid URL")
return
}
DispatchQueue.main.async {
let newSession = ASWebAuthenticationSession(
url: url,
callbackURLScheme: "myapp"
) { callbackURL, error in
self.session = nil
if let callbackURL = callbackURL {
call.resolve(["callbackUrl": callbackURL.absoluteString])
} else {
call.reject(error?.localizedDescription ?? "Session cancelled")
}
}
newSession.presentationContextProvider = self
newSession.prefersEphemeralWebBrowserSession = true
newSession.start()
self.session = newSession
}
}
public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let window = windowScene.windows.first else {
return ASPresentationAnchor()
}
return window
}
}
4. Implemente o plugin Android
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import com.getcapacitor.JSObject
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin
@CapacitorPlugin(name = "CapturePlugin")
class CapturePlugin : Plugin() {
private var pendingCall: PluginCall? = null
@PluginMethod
fun openSession(call: PluginCall) {
val url = call.getString("url") ?: return call.reject("Missing URL")
pendingCall = call
activity.runOnUiThread {
CustomTabsIntent.Builder().build()
.launchUrl(activity, Uri.parse(url))
}
}
override fun handleOnNewIntent(intent: Intent) {
super.handleOnNewIntent(intent)
intent.data?.let { uri ->
if (uri.scheme == "myapp") {
pendingCall?.resolve(JSObject().put("callbackUrl", uri.toString()))
pendingCall = null
}
}
}
}
5. Registre o seu scheme
- iOS
- Android
No Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
</array>
</dict>
</array>
No AndroidManifest.xml, dentro da sua <activity> principal:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="callback" />
</intent-filter>
No build.gradle:
implementation("androidx.browser:browser:1.5.0")
6. Inicie a captura
Um serviço Angular em torno do plugin:
import { Injectable } from '@angular/core';
import Capture from '../plugins/capture-plugin';
@Injectable({ providedIn: 'root' })
export class CaptureService {
/** Resolve true quando a captura terminou, false quando a pessoa a fechou. */
async open(link: string): Promise<boolean> {
try {
await Capture.openSession({ url: link });
return true;
} catch {
return false;
}
}
}
const ended = await this.captureService.open(link);
if (ended) {
// A captura terminou. Peça ao seu back-end para ler o resultado
// com GET /v1/processes/{id}, usando o id do Human Plugin.
}
Resumo
| Arquivo | Finalidade |
|---|---|
capture-plugin.ts | Interface do plugin Capacitor |
CapturePlugin.swift | iOS: ASWebAuthenticationSession |
CapturePlugin.kt | Android: Custom Tabs |
Info.plist | URL scheme do iOS |
AndroidManifest.xml | Intent filter do Android |
capture.service.ts | Serviço Angular |