Skip to main content

unico_check 4.65.0 copy "unico_check: ^4.65.0" to clipboard
unico_check: ^4.65.0 copied to clipboard

Esta biblioteca visa implementar a tecnologia unico check na plataforma flutter.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unico_check/unico_check.dart';
import 'config.dart';
import 'silent_auth_process.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'unico check',
      theme: ThemeData(
        primaryColor: const Color(0xFF0B38E7),
      ),
      home: const MyHomePage(title: 'unico | check'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage>
    implements UnicoListener, UnicoSelfie, UnicoSdks, UnicoDocument {
  late UnicoCheckBuilder _unicoCheck;
  late UnicoCheckBuilder _unicoCheckWebAppToken;
  late UnicoCheckCameraOpener _opener;
  final _webAppTokenController = TextEditingController();
  final _referenceProcessIdController = TextEditingController();
  final _subjectCodeController = TextEditingController();

  bool _silentAuthInitEnabled = true;

  static const String _silentAuthInitKey = 'silentAuthInit';

  Future<void> _loadSilentAuthInitFlag() async {
    final prefs = await SharedPreferences.getInstance();
    if (!mounted) return;
    setState(() {
      _silentAuthInitEnabled = prefs.getBool(_silentAuthInitKey) ?? true;
    });
  }

  Future<void> _setSilentAuthInitFlag(bool enabled) async {
    setState(() => _silentAuthInitEnabled = enabled);

    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_silentAuthInitKey, enabled);

    _showAlertDialog(
      enabled
          ? 'O initializeSDK volta a rodar no launch. Feche e abra o app para valer.'
          : 'O initializeSDK deixa de rodar no launch. Feche e abra o app para valer.',
      title: 'Revalidação Silenciosa',
    );
  }

  /// CPF da sessao de teste, perguntado ao abrir o app e reusado depois. O
  /// mesmo valor vai para o `startSilentValidation` e para o processo.
  String? _subjectCode;

  /// Pergunta o CPF e guarda para o resto da sessao. Devolve nulo quando quem
  /// testa cancela ou deixa vazio.
  Future<String?> _askSubjectCode() async {
    _subjectCodeController.text = _subjectCode ?? '';
    _subjectCodeController.selection = TextSelection.collapsed(
      offset: _subjectCodeController.text.length,
    );

    final typed = await showDialog<String>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Revalidação Silenciosa'),
          content: TextField(
            controller: _subjectCodeController,
            keyboardType: TextInputType.number,
            autofocus: true,
            decoration: const InputDecoration(
              labelText: 'CPF',
              hintText: 'usado como externalUserId e subject do processo',
            ),
          ),
          actions: [
            TextButton(
              child: const Text('Cancelar'),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              child: const Text('Continuar'),
              onPressed: () => Navigator.of(context)
                  .pop(_subjectCodeController.text.trim()),
            ),
          ],
        );
      },
    );

    if (typed == null || typed.isEmpty) return null;
    if (mounted) setState(() => _subjectCode = typed);
    return typed;
  }

  /// Usa o CPF perguntado no launch; sem ele, pergunta na hora.
  Future<String?> _subjectCodeOrAsk() async {
    final current = _subjectCode;
    if (current != null && current.isNotEmpty) return current;
    return _askSubjectCode();
  }

  Future<void> startSilentValidation() async {
    final subjectCode = await _subjectCodeOrAsk();
    if (subjectCode == null || subjectCode.isEmpty) return;

    try {
      await UnicoSilentAuthDefault().startSilentValidation(
        UnicoCheckPrepareInfo(
          externalUserId: subjectCode,
          useCase: 'login',
        ),
      );
    } on UnicoError catch (error) {
      _showAlertDialog(
        'code: ${error.code}\n'
        'description: ${error.description}\n'
        'info: ${error.info ?? 'não informado'}',
        title: 'Revalidação Silenciosa',
      );
      return;
    }

    if (!hasProcessCredentials) {
      _showAlertDialog(
        'Validação silenciosa concluída com sucesso.\n\n'
        'Veredito não consultado: rode com as credenciais em --dart-define '
        'para ver processId, status e resultado.',
        title: 'Revalidação Silenciosa',
      );
      return;
    }

    try {
      final process = await SilentAuthProcess().submit(subjectCode);
      _showAlertDialog(
        'processId: ${process.processId ?? 'não informado'}\n'
        'status: ${process.status ?? 'não informado'}\n'
        'resultado: ${process.verdict ?? 'não informado'}',
        title: 'Revalidação Silenciosa',
      );
    } catch (error) {
      _showAlertDialog(
        'Validação silenciosa concluída, mas a consulta do veredito falhou.\n\n'
        '$error',
        title: 'Revalidação Silenciosa',
      );
    }
  }

  void _showAlertDialog(String content, {String? title}) {
    Future.microtask(() {
      if (!mounted) return;
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(title ?? "Debug"),
            content: Text(content),
            actions: [
              TextButton(
                child: const Text("OK"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    });
  }

  final _theme = UnicoTheme(
      colorSilhouetteSuccess: "#4ca832",
      colorSilhouetteError: "#fcdb03",
      colorTextMessage: '#000000',
      colorBackground: "#3295a8",
      colorProgressBar: "#4ca832",
      colorCancelButtonIcon: "#4ca832");

  @override
  void initState() {
    super.initState();
    initUnicoCamera();
    configUnicoCamera();
    _loadSilentAuthInitFlag();
    WidgetsBinding.instance.addPostFrameCallback((_) => _askSubjectCode());
  }

  void initUnicoCamera() {
    _unicoCheck = UnicoCheck(
        listener: this,
        unicoConfigIos: configIos,
        unicoConfigAndroid: configAndroid);

    _unicoCheckWebAppToken = UnicoCheck(
        listener: this,
        unicoConfigIos: configIos,
        unicoConfigAndroid: configAndroid);
  }

  void configUnicoCamera() {
    _unicoCheck
        .setTheme(unicoTheme: _theme)
        .setTimeoutSession(timeoutSession: 55)
        .setEnvironment(unicoEnvironment: UnicoEnvironment.UAT);

    _unicoCheckWebAppToken
        .setTheme(unicoTheme: _theme)
        .setTimeoutSession(timeoutSession: 55)
        .setEnvironment(unicoEnvironment: UnicoEnvironment.UAT);
  }

  @override
  void dispose() {
    _webAppTokenController.dispose();
    _referenceProcessIdController.dispose();
    _subjectCodeController.dispose();
    super.dispose();
  }

  /// Unico callbacks
  @override
  void onErrorUnico(UnicoError error) {
    _showAlertDialog(
        'onErrorUnico: code=${error.code} description=${error.description}');
  }

  @override
  void onUserClosedCameraManually() {
    _showAlertDialog('onUserClosedCameraManually');
  }

  @override
  void onSystemChangedTypeCameraTimeoutFaceInference() {
    _showAlertDialog('onSystemChangedTypeCameraTimeoutFaceInference');
  }

  @override
  void onSystemClosedCameraTimeoutSession() {
    _showAlertDialog('onSystemClosedCameraTimeoutSession');
  }

  /// Selfie callbacks
  @override
  void onSuccessSelfie(ResultCamera result) {
    _showAlertDialog('onSuccessSelfie: base64 length=${result.base64?.length}; encrypted length=${result.encrypted?.length}');
  }

  @override
  void onErrorSelfie(UnicoError error) {
    _showAlertDialog(
        'onErrorSelfie: code=${error.code} description=${error.description}');
  }

  /// webAppToken callback
  @override
  void onSuccess(SuccessResult result) {
    _showAlertDialog('onSuccess: processId=${result.processId}');
  }

  /// Document callbacks
  @override
  void onSuccessDocument(ResultCamera resultCamera) {
    _showAlertDialog(
        'onSuccessDocument: base64 length=${resultCamera.base64?.length}; encrypted length=${resultCamera.encrypted?.length}');
  }

  @override
  void onErrorDocument(UnicoError error) {
    _showAlertDialog(
        'onErrorDocument: code=${error.code} description=${error.description}');
  }

  void setCameraSmart() {
    _opener = _unicoCheck
        .setAutoCapture(autoCapture: true)
        .setSmartFrame(smartFrame: true)
        .build();
  }

  void setCameraNormal() {
    _opener = _unicoCheck
        .setAutoCapture(autoCapture: false)
        .setSmartFrame(smartFrame: false)
        .build();
  }

  void setCameraSmartWithButton() {
    _opener = _unicoCheck
        .setAutoCapture(autoCapture: false)
        .setSmartFrame(smartFrame: true)
        .build();
  }

  void openCamera() {
    setCameraSmart();
    _opener.openCameraSelfie(listener: this);
  }

  void openCameraNormal() {
    setCameraNormal();
    _opener.openCameraSelfie(listener: this);
  }

  void openCameraSmartWithButton() {
    setCameraSmartWithButton();
    _opener.openCameraSelfie(listener: this);
  }

  void openCameraWithWebAppToken() {
    final webAppToken = _webAppTokenController.text;
    if (webAppToken.isEmpty) {
      _showAlertDialog('Informe um webAppToken');
      return;
    }

    _opener = _unicoCheckWebAppToken
        .setAutoCapture(autoCapture: true)
        .setSmartFrame(smartFrame: true)
        .build();
    _opener.openCameraSelfie(
      listener: this,
      webAppToken: webAppToken,
    );
  }

  void openCameraWithIDSmartOptions() {
    final referenceProcessId = _referenceProcessIdController.text;
    if (referenceProcessId.isEmpty) {
      _showAlertDialog('Informe um referenceProcessId');
      return;
    }

    _opener = _unicoCheck
        .setAutoCapture(autoCapture: true)
        .setSmartFrame(smartFrame: true)
        .build();
    _opener.openCameraSelfie(
      listener: this,
      idSmartOptions: UnicoIDSmartOptions(
        referenceProcessId: referenceProcessId,
      ),
    );
  }

  void openCameraDocumentCNH() {
    _unicoCheck
        .build()
        .openCameraDocument(documentType: DocumentType.CNH, listener: this);
  }

  void openCameraDocumentCNHFront() {
    _unicoCheck.build().openCameraDocument(
        documentType: DocumentType.CNH_FRENTE, listener: this);
  }

  void openCameraDocumentCNHVerso() {
    _unicoCheck.build().openCameraDocument(
        documentType: DocumentType.CNH_VERSO, listener: this);
  }

  void openCameraDocumentRGFront() {
    _unicoCheck.build().openCameraDocument(
        documentType: DocumentType.RG_FRENTE, listener: this);
  }

  void openCameraDocumentRGVerso() {
    _unicoCheck.build().openCameraDocument(
        documentType: DocumentType.RG_VERSO, listener: this);
  }

  void openCameraDocumentCPF() {
    _unicoCheck
        .build()
        .openCameraDocument(documentType: DocumentType.CPF, listener: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: const EdgeInsets.only(top: 50),
              child: const Text(
                'Bem-vindo a poc do unico | check !',
                style: TextStyle(fontSize: 20.0),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(25),
              child: const Text(
                'Teste agora nossa tecnologia:',
                style: TextStyle(fontSize: 16.0),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 10, bottom: 10),
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Revalidação Silenciosa',
                        style: TextStyle(fontSize: 15.0),
                      ),
                      Text(
                        'initializeSDK no launch — vale no próximo',
                        style: TextStyle(fontSize: 11.0, color: Colors.grey),
                      ),
                    ],
                  ),
                  Switch(
                    value: _silentAuthInitEnabled,
                    onChanged: _setSilentAuthInitFlag,
                  ),
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: Column(
                children: [
                  TextButton(
                    onPressed: _askSubjectCode,
                    child: Text(
                      (_subjectCode?.isNotEmpty ?? false)
                          ? 'CPF: $_subjectCode — trocar'
                          : 'Definir CPF',
                    ),
                  ),
                  TextButton(
                    onPressed: startSilentValidation,
                    child: const Text('startSilentValidation'),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Text(
                      _silentAuthInitEnabled
                          ? 'Ligado: o initializeSDK rodou no launch, então a validação deve concluir e a captura seguinte não repete assinatura nem BUILD.'
                          : 'Desligado: sem initializeSDK, a validação falha com 75001 e a captura envia assinatura e BUILD normalmente, como antes desta entrega.',
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 11.0, color: Colors.grey),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 10, bottom: 10),
              child: const Text(
                'Camera para selfie',
                style: TextStyle(fontSize: 15.0),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraNormal,
                child: const Text('Camera normal'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCamera,
                child: const Text('Camera inteligente'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraSmartWithButton,
                child: const Text('Camera smart button'),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 10, bottom: 10),
              child: const Text(
                'Camera com webAppToken',
                style: TextStyle(fontSize: 15.0),
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 25),
              child: TextField(
                controller: _webAppTokenController,
                decoration: const InputDecoration(
                  labelText: 'webAppToken',
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraWithWebAppToken,
                child: const Text('Camera com webAppToken'),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 10, bottom: 10),
              child: const Text(
                'Camera SDK-S (processo de referencia)',
                style: TextStyle(fontSize: 15.0),
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 25),
              child: TextField(
                controller: _referenceProcessIdController,
                decoration: const InputDecoration(
                  labelText: 'referenceProcessId',
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraWithIDSmartOptions,
                child: const Text('Camera com processo de referencia'),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 10, bottom: 10),
              child: const Text(
                'Camera para documentos',
                style: TextStyle(fontSize: 15.0),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                  onPressed: openCameraDocumentCNH,
                  child: const Text('Documentos CNH')),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraDocumentCNHFront,
                child: const Text('Documentos CNH Frente'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraDocumentCNHVerso,
                child: const Text('Documentos CNH Verso'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraDocumentRGFront,
                child: const Text('Documentos RG Frente'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraDocumentRGVerso,
                child: const Text('Documentos RG verso'),
              ),
            ),
            Container(
              margin: const EdgeInsets.all(10),
              child: TextButton(
                onPressed: openCameraDocumentCPF,
                child: const Text('Documentos CPF'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
15
likes
140
points
15.2k
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Esta biblioteca visa implementar a tecnologia unico check na plataforma flutter.

Homepage

License

MIT (license)

Dependencies

flutter

More

Packages that depend on unico_check

Packages that implement unico_check