> For the complete documentation index, see [llms.txt](https://docs.caf.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.caf.io/caf-sdk/caf-sdk-pt-br/react-native/migrating-from-cafsdk.md).

# Migrando do CafSdk

Migre um app React Native da API sequencial useCafSdk para o Certta DevX no @caf.io/react-native-sdk 5.4.0. Compare configuração, inicialização do módulo e tratamento de eventos.

{% hint style="warning" %}
Este guia aborda **@caf.io/react-native-sdk 5.4.0** e acima (Certta DevX). Para o sequencial anterior `useCafSdk` fluxo, veja o [documentação legada](https://docs.caf.io/caf-sdk/react-native/getting-started-with-the-sdk).
{% endhint %}

A partir de **@caf.io/react-native-sdk 5.4.0**, **Certta DevX** (`useCerttaSdk` + por módulo `open()`) é a API recomendada para novas integrações. A API sequencial `useCafSdk` API continua disponível no mesmo pacote. Os `initialize` / `startSDK` fluxos existentes continuam funcionando.

Esta página mapeia a API sequencial legada para módulos independentes `open()` chamadas.

## Comparação de APIs

| Área                    | useCafSdk (legado)                                                                   | Certta DevX (5.4.0+)                                                                                  |
| ----------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| Hook de sessão          | `useCafSdk`                                                                          | `useCerttaSdk`                                                                                        |
| Configuração da sessão  | `initialize({ configuration, mobileToken, personId, ... })`                          | `configureSDK(CerttaConfiguration)`                                                                   |
| Ordem dos módulos       | `presentationOrder` executa Face Liveness e Document Detector em uma única sequência | Cada módulo é aberto independentemente                                                                |
| Inicialização           | Uma `startSDK()` inicia todo o pipeline                                              | `useCafFaceLiveness().open`, `useCafDocumentDetector().open`, `useCafDocumentDetectorUI().open`       |
| Configuração do módulo  | `applyCafFaceLiveness` / `applyCafDocumentDetector` antes `initialize`               | Passe `CerttaLivenessConfiguration` / `CerttaDocumentDetectorConfiguration` diretamente para `open()` |
| Eventos                 | Único `response` objeto em `useCafSdk`                                               | Por hook `evento` estado + `logs` em `useCerttaSdk`                                                   |
| Identificador da pessoa | `personId`                                                                           | `userId`                                                                                              |
| Flag de segurança       | `enableSecurityModule` na configuração do builder                                    | `securityEnabled` em `CerttaConfiguration`                                                            |
| Cores                   | `colorConfiguration` na configuração do builder                                      | `colorConfiguration` em `CerttaConfiguration`                                                         |

Seleção de módulos (`caf-modules-config.json`), repositórios Maven, CocoaPods, permissões e ProGuard **não mudam**. Siga o [Guia de Instalação](/caf-sdk/caf-sdk-pt-br/react-native/installation-guide.md).

## 1. Configure a sessão uma vez

```typescript
// Antes (useCafSdk)
const { initialize, startSDK, response } = useCafSdk();
const { applyCafFaceLiveness } = useCafFaceLiveness();
const { applyCafDocumentDetector } = useCafDocumentDetector();

await initialize(
  {
    configuration: {
      presentationOrder: [
        CafModuleType.FACE_LIVENESS,
        CafModuleType.DOCUMENT_DETECTOR,
      ],
      enableSecurityModule: true,
    },
    mobileToken: 'token',
    environment: CafEnvironment.PROD,
    personId: 'personId',
  },
  async () => {
    await applyCafFaceLiveness({ maxRetryAttempts: 3 });
    await applyCafDocumentDetector({
      flow: [{ document: CafDocument.RG_FRONT }],
    });
    return true;
  },
);

// Depois (Certta DevX)
const { configureSDK, updateUserId, updateMobileToken } = useCerttaSdk();

try {
  await configureSDK({
    mobileToken: 'token',
    userId: 'personId',
    environment: CafEnvironment.PROD,
    securityEnabled: true,
  });
} catch {
  // Trate BRIDGE_EXCEPTION
}
```

Depois `configureSDK`, atualize as credenciais sem reconstruir a configuração completa:

```typescript
updateUserId('new-user-id');
updateMobileToken('new-jwt-token');
```

## 2. Abra um módulo por vez

Não há `presentationOrder` na Certta. Inicie Face Liveness ou Document Detector quando o fluxo do seu produto precisar.

```typescript
// Vivacidade facial
const { open: openLiveness } = useCafFaceLiveness();
try {
  await openLiveness({
    maxRetryAttempts: 3,
    faceAuthEnabled: false,
    showLoading: true,
    useFaceLivenessUi: true,
  });
} catch {
  // Trate BRIDGE_EXCEPTION
}

// Detector de documentos (sem interface)
const { open: openDocumentDetector } = useCafDocumentDetector();
try {
  await openDocumentDetector({
    flow: [
      { document: CafDocument.RG_FRONT },
      { document: CafDocument.RG_BACK },
    ],
  });
} catch {
  // Trate BRIDGE_EXCEPTION
}

// Detector de documentos (interface)
const { open: openDocumentDetectorUI } = useCafDocumentDetectorUI();
try {
  await openDocumentDetectorUI({
    flow: [{ document: CafDocument.RG_FRONT }],
  });
} catch {
  // Trate BRIDGE_EXCEPTION
}
```

| apply legado + configuração do módulo | Inicialização da Certta                                                  |
| ------------------------------------- | ------------------------------------------------------------------------ |
| `applyCafFaceLiveness`                | `useCafFaceLiveness().open(CerttaLivenessConfiguration)`                 |
| `applyCafFaceLivenessUI`              | `open({ useFaceLivenessUi: true, ... })`                                 |
| `applyCafDocumentDetector`            | `useCafDocumentDetector().open(CerttaDocumentDetectorConfiguration)`     |
| `applyCafDocumentDetectorUI`          | `useCafDocumentDetectorUI().open(CerttaDocumentDetectorUIConfiguration)` |

A configuração de vivacidade da Certta é um conjunto menor: `maxRetryAttempts`, `faceAuthEnabled`, `showLoading`, `useFaceLivenessUi`, e `payFaceDebugMode` (iOS). URLs de proxy, certificados e campos da tela de instruções de `CafFaceLivenessConfiguration` não fazem parte do objeto de configuração da Certta.

## 3. Ouça eventos tipados do módulo

```typescript
// Antes — um único objeto de resposta em useCafSdk
useEffect(() => {
  response.success?.forEach((item) => {
    // item.moduleName + item.signedResponse
  });
  if (response.failure) { /* CafFailureType */ }
  if (response.error) { /* CafErrorType */ }
}, [response]);

// Depois — estado de evento por hook
const { event: livenessEvent } = useCafFaceLiveness();
const { event: documentEvent } = useCafDocumentDetector();
const { logs } = useCerttaSdk();

useEffect(() => {
  if (livenessEvent.success) { /* JWT em livenessEvent.success.response */ }
  if (livenessEvent.failed) { /* CerttaLivenessFailure */ }
  if (livenessEvent.error) { /* CerttaError */ }
}, [livenessEvent]);

useEffect(() => {
  if (documentEvent.success) { /* JWT */ }
  if (documentEvent.error) { /* CerttaError */ }
}, [documentEvent]);
```

| useCafSdk `response`     | Equivalente na Certta                           |
| ------------------------ | ----------------------------------------------- |
| `success.signedResponse` | `event.success.response`                        |
| `success.moduleName`     | Implícito pelo hook que recebeu o evento        |
| `failure`                | `useCafFaceLiveness().event.failed`             |
| `error`                  | `event.error` (`CerttaError`)                   |
| `log`                    | `useCerttaSdk().logs`                           |
| `loading` / `loaded`     | Não é encaminhado nos hooks de módulo da Certta |

As rejeições do mapeador de bridge rejeitam a `configureSDK` / `open()` promessa com `CerttaPlatformException` e código `BRIDGE_EXCEPTION` (`CerttaErrorCode.BridgeException`) em vez de aparecer apenas nos eventos do hook.

## 4. Pipelines sequenciais

Se você usou `presentationOrder`, telas de transição (`enableTransitionScreens`), ou `waitForAllServices` com `useCafSdk`, o mesmo fluxo do produto pode ser construído com a Certta DevX: configure a sessão uma vez e, em seguida, encadeie chamadas de módulo `open()` a partir da lógica do seu app (por exemplo, iniciar Face Liveness quando Document Detector `event.success` estiver definido).

A versão sequencial `useCafSdk` API continua disponível em `@caf.io/react-native-sdk` e está documentada em [Guia de início rápido legado](/caf-sdk/caf-sdk-pt-br/react-native/getting-started-with-the-sdk.md). Ambas as APIs são compatíveis e cobrem necessidades de integração equivalentes — prefira a Certta DevX para novos desenvolvimentos e ao migrar apps existentes.

## Próximos passos

{% content-ref url="/pages/ee16df9288cf94f23261720284c4efca724fc2c8" %}
[Guia de Instalação](/caf-sdk/caf-sdk-pt-br/react-native/installation-guide.md)
{% endcontent-ref %}

{% content-ref url="/pages/a6456da207c8b8aed6bee17b024cf67619d1364d" %}
[Face Liveness](/caf-sdk/caf-sdk-pt-br/react-native/face-liveness.md)
{% endcontent-ref %}

{% content-ref url="/pages/1e1279259ffc8e30bf8c30a7c687900fe4ab864f" %}
[Document Detector](/caf-sdk/caf-sdk-pt-br/react-native/document-detector.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.caf.io/caf-sdk/caf-sdk-pt-br/react-native/migrating-from-cafsdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
