# React Native SDK (Legacy)

_Encrypt data and embed UI Components with React Native_

> **Deprecated**
>
> This is the legacy version of our React Native SDK. It is no longer actively
>   maintained. If you are on React Native 0.76 or higher you can migrate to our
>   new [React Native SDK](/sdks/react-native#migration-guide).

You can use our React Native SDK to:

- Encrypt data client-side
- Collect Card Data securely
- Perform 3D Secure authentication

## Quickstart

### Install SDK

Our React Native SDK is distributed via `npm`, and can be installed using your preferred package manager.

```bash
## Using npm
npm install @evervault/evervault-react-native

## Using yarn
yarn add @evervault/evervault-react-native
```

### Add the EvervaultProvider

Wrap your app with the `EvervaultProvider` component and pass your Team and App ID as props.

Your Team and App ID can be found in the [Evervault Dashboard](https://app.evervault.com).

```tsx
import { EvervaultProvider } from "@evervault/evervault-react-native";

function App() {
  return (
    <EvervaultProvider teamId="team_id" appId="app_id">
      <YourApp />
    </EvervaultProvider>
  );
}
```

### Collect card data

You can use the `<Card />` component to collect card data securely.

```tsx
import { Card, type CardPayload } from "@evervault/evervault-react-native";

function CardData() {
  const [cardData, setCardData] = useState<CardPayload | undefined>(undefined);

  const handleCardChange = (card: CardPayload) => {
    if (card.isComplete) {
      // note that the user can enter further data even when the Card is in a complete state.
      // For example entering the remainder of their name after the first few characters.
      console.log("Card is complete!");
    }

    setCardData(card);
  };

  return (
    <Card onChange={handleCardChange}>
      <Card.Number />
      <Card.Expiry />
      <Card.CVC />
      <Card.Holder />
    </Card>
  );
}
```

If you don't need to collect all four types of supported Card Data, you can omit the relevant components.

However, the components cannot be used individually outside of the `<Card />` component.

### Perform 3D Secure Authentication

You can use the [`<ThreeDSecure />`](#three-d-secure) component in combination with the Evervault API to perform 3DS authentications. In order to use the 3DS component you must first [create a 3DS session on your backend](/api#createThreeDSSession) and pass it to your frontend. You can then use the [`<ThreeDSecure.Frame>`](#three-d-secure-frame) component to display the 3DS webview.

```tsx
import {
  ThreeDSecure,
  useThreeDSecure,
} from "@evervault/evervault-react-native";
import { createThreeDSSession, finalizePayment } from "./api";
import { Modal, TouchableOpacity, Text, View } from "react-native";

function Checkout() {
  const tds = useThreeDSecure();

  const handlePayment = async () => {
    // Create a 3DS session on your backend
    const sessionId = await create3DSecureSession();

    tds.start(sessionId, {
      onSuccess: () => {
        console.log("3DS successful");
      },
      onFailure: (error: Error) => {
        console.error("3DS failed", error);
      },
      onError: (error: Error) => {
        console.log("3DS errored", error);
      },
    });
  };

  const close3DS = async () => {
    await tds.cancel();
  };

  return (
    <ThreeDSecure state={tds}>
      <Modal animationType="slide" transparent={true}>
        <View style={[styles.modalContainer]}>
          <View style={[styles.modalContent]}>
            <View style={[styles.titleBar]}>
              <TouchableOpacity style={[styles.closeButton]} onPress={close3DS}>
                <Text style={[styles.closeButtonText]}>"X"</Text>
              </TouchableOpacity>
              <Text style={[styles.titleText]}>"Verification"</Text>
            </View>
            <ThreeDSecure.Frame />
          </View>
        </View>
      </Modal>
    </ThreeDSecure>
  );
}
```

### Proguard Rules

If you are using code shrinking with ProGuard for Android, you will need to specify exclusion rules for several Evervault dependencies. The required ProGuard rules can be found in [our Android SDK docs](/sdks/android#proguard-rules).

## Reference

### {'<EvervaultProvider />'}

```tsx
import { EvervaultProvider } from "@evervault/evervault-react-native";

function App() {
  return (
    <EvervaultProvider teamId="team_123" appId="app_123">
      <YourApp />
    </EvervaultProvider>
  );
}
```

**Props**

- `teamId` `string` _(required)_ — The Team ID found in the [Evervault Dashboard](https://app.evervault.com).
- `appId` `string` _(required)_ — The App ID found in the [Evervault Dashboard](https://app.evervault.com).

### CardPayload

```tsx
import { type CardPayload } from "@evervault/evervault-react-native";
```

The Payload returned by the onChange callback of the `<Card />` component.

**Properties**

- `card.name` `string` — The card holder name.
- `card.number` `string` — The encrypted card number. This will only be present if the number is valid.
- `card.brand` `string` — The global payment card brand associated with the card.
- `card.localBrands` `Array<String>` — The local payment card brands that are accepted by the card
- `card.lastFour` `string` — The last 4 digits of the card. This will only be present if the number is valid.
- `card.bin` `string` — The bin for the card. This will only be present if the number id valid.
- `card.expiry.month` `string` — The month for the card expiry field.
- `card.expiry.year` `string` — The year for the card expiry field.
- `card.cvc` `string` — The encrypted card CVC.
- `card.errors` `Object` — Validation errors related to the card details.
- `card.isValid` `boolean` — Whether or not there are any errors shown in the component.
- `card.isComplete` `boolean` — Whether or not all of the fields have been filled out successfully with valid values.

### {"<Card />"}

```tsx
import {
  init,
  Card,
  type CardPayload,
} from "@evervault/evervault-react-native";

function App() {
  const submitCardData = (payload: CardPayload) => {
    console.log("Card Data", payload);
  };

  useEffect(() => {
    init("team_id", "app_id");
  }, []);

  return (
    <Card>
      <Text>Card Number</Text>
      <Card.Number />
    </Card>
  );
}
```

The Card component is used to collect card data securely. It is a wrapper component that manages the state of the child components.

Make sure you have initialized the Evervault SDK before using the Card component.

You may render some or all of the available Card Sub-Components.

The `isComplete` field of the payload will be `true` when all of the **currently rendered** fields are filled out successfully with valid values. For example, if you were to omit the `<Card.CVC />` component and render the `<Card.Number />`, `<Card.Expiry />` and `<Card.Holder />` components. The `isComplete` field will be true, when the three rendered components have valid values.

**Props**

- `config` `CardConfig` — The config for the card component.
  - `acceptedBrands` `Array<CardBrandName>` — An array of card brands that are accepted. If not provided, all brands are accepted. Possible values are 'american-express', 'visa', 'mastercard', 'discover', 'jcb', 'diners-club', 'unionpay', 'maestro', 'mir', 'elo', 'hipercard', 'hiper', 'szep', 'uatp', 'rupay'.
- `initialValue` `CardForm` — Initial Values for the card fields.
  - `number` `String` — The unencrypted card number field.
  - `expiry` `String` — The expiry date for the card. Takes the format MMYY
  - `cvc` `String` — The unencrypyted three digit CVC code for the card.
  - `holder` `String` — The card holder name.
- `onChange` `(payload: CardPayload) => void` — A callback function that is called whenever the card data changes.
- `style` `StyleProp<TextStyle>` — The style to apply to the container component.

### Card Input Components

The `Card` component has support for collecting Card Number, Expiry, CVC and Card Holder information. These components accept almost all the same properties as the standard React Native TextInput component.

```ts
import { type TextInputProps } from "react-native";

// Props accepted by the Card Input Components
Omit<
  TextInputProps,
  "onChange" | "onChangeText" | "inputMode" | "autoComplete" | "value"
>;
```

### {'<Card.Number />'}

Used as a child of [{'<Card />'}](#card) to collect a card number.

```tsx
import { Card } from "@evervault/evervault-react-native";

function App() {
  return (
    <Card>
      <Card.Number
        autofocus
        placeholder="4242 4242 4242 4242"
        style={{ borderWidth: 1 }}
      />
    </Card>
  );
}
```

### {'<Card.Expiry />'}

Used as a child of [{'<Card />'}](#card) to collect a card expiry.

```tsx
import { Card } from "@evervault/evervault-react-native";

function App() {
  return (
    <Card>
      <Card.Number />
      <Card.Expiry placeholder="MM / YY" />
    </Card>
  );
}
```

### {'<Card.CVC />'}

Used as a child of [{'<Card />'}](#card) to collect a card CVC.

```tsx
import { Card } from "@evervault/evervault-react-native";

function App() {
  return (
    <Card>
      <Card.Number />
      <Card.CVC placeholder="123" />
    </Card>
  );
}
```

### {'<Card.Holder />'}

Used as a child of [{'<Card />'}](#card) to collect the name of a card holder.

```tsx
import { Card } from "@evervault/evervault-react-native";

function App() {
  return (
    <Card>
      <Card.Number />
      <Card.Holder placeholder="John Doe" />
    </Card>
  );
}
```

### {'useThreeDSecure()'}

The `useThreeDSecure` hook is used to manage the 3DS authentication process. It returns an object with `start()` and `cancel()` methods. The returned object should be used with the [`<ThreeDSecure />`](#three-d-secure) component.

#### Returns

##### {"start()"}

The start function is used to kick off the 3DS authentication process.

**Parameters**

- `sessionId` `String` _(required)_ — The 3DS session ID. A 3DS session can be created using the [Evervault API](/api#createThreeDSSession).
- `callbacks` `ThreeDSSessionCallbacks` _(required)_ — The callbacks to be called when the 3DS authentication process is finished.
  - `onSuccess` `Function` — The 'success' event will be fired once the 3DS authentication process has been completed successfully. You should use this event to trigger your backend to finalize the payment. Your backend can use the [Retrieve 3DS Session](/api#retrieveThreeDSSession) endpoint to retrieve the cryptogram for the session and complete the payment.
  - `onFailure` `Function` — The 'failure' event will be fired if the 3DS authentication process fails. You should use this event to handle the failure and inform the user and prompt them to try again. If the user cancels the 3DS authentication process this event will be fired.
  - `onError` `Function` — The error event will be fired if the component fails to load.

##### {"cancel()"}

The `cancel()` function is used to cancel the ongoing 3DS authentication process. This can be particularly useful for canceling a session when a custom cancel button is triggered.

### {"<ThreeDSecure />"}

This is a provider module which provides access to the 3DS authentication process. It should be used in combination with the [`useThreeDSecure`](#usethreedsecure) hook. The `<ThreeDSecure />` provider component allows you to use the [`<ThreeDSecure.Frame>`](#three-d-secure-frame) component to display the 3DS webview. Any custom components you want to display alongside the 3DS webview should be wrapped in the `<ThreeDSecure />` component.

**Props**

- `state` `ThreeDSecureState` — The 3DS session state returned from the [`useThreeDSecure`](#useThreeDSecure) hook.

### {"<ThreeDSecure.Frame />"}

The `<ThreeDSecure.Frame />` component is used to display the 3DS webview inside your own custom components. It is available within the [`<ThreeDSecure />`](#three-d-secure) provider component. It should be used in combination with the [`useThreeDSecure`](#usethreedsecure) hook. The component returns a webview which will handle the authentication process. You will need to use the `cancel()` method, returned from the [`useThreeDSecure`](#usethreedsecure) hook, to handle the user closing the 3DS webview before completion.

```tsx
import { ThreeDSecure, useThreeDSecure} from '@evervault/evervault-react-native';
import { createThreeDSSession, finalizePayment } from "./api"
import { CustomIcon } from "./CustomIcon"

function CustomCheckout() {
  const tds = useThreeDSecure();

  const handlePayment = async () => {
    // Create a 3DS session on your backend
    const sessionId = await create3DSecureSession();

    tds.start(sessionId, {
      onSuccess: () => {
        console.log("3DS successful");
        setPaymentStatus("success");
      },
      onFailure: (error: Error) => {
        console.error("3DS failed", error);
        setPaymentStatus("failed");
      },
      onError: (error: Error) => {
        console.log("3DS errored", error);
        setPaymentStatus("failed");
      },
    });
  }

  const cancelSession = async () => {
    await tds.cancel();
  };

  return (
    <ThreeDSecure state={tds}>
      <View>
        <CustomIcon onPress={cancelSession}> // Use ThreeDSecure.Frame to display the 3DS webview with your own components
        <ThreeDSecure.Frame />
      </View>
    </ThreeDSecure>
  );
}
```

### {'encrypt()'}

```tsx
import { encrypt } from "@evervault/evervault-react-native";

async function encryptData(data: string) {
  try {
    const encrypted = await encrypt(data);
    console.log("Encrypted Data", encrypted);
  } catch (err) {
    console.log("There was an error encrypting the data");
  }
}
```

**Parameters**

- `data` `any` _(required)_ — The data to encrypt.

On iOS you can pass data types like Booleans, Objects and Arrays to the encrypt function. The full list of supported data types can be found in our [iOS SDK Documentation](/sdks/ios#encrypting-data).

Currently on Android only encrypting Strings is supported.

### {'init()'}

> **Deprecated**
>
> The init method has been deprecated and will be removed from the Evervault SDK in a future release.
>
> Use the [EvervaultProvider](#evervault-provider) component to initialize the Evervault SDK instead.

```tsx
import { init } from "@evervault/evervault-react-native";

function App() {
  useEffect(() => {
    init("team_id", "app_id");
  }, []);
}
```

The init function initializes the Evervault SDK with your Team and App ID. You only need to do this once in your application, but must run the command before using any other Evervault functions or components.

**Parameters**

- `teamId` `String` _(required)_ — The Team ID found in the [Evervault Dashboard](https://app.evervault.com).
- `appId` `String` _(required)_ — The App ID found in the [Evervault Dashboard](https://app.evervault.com).

