## Minimum requirements

**React Native**: Initial React Native library installation

**iOS**: iOS 13 or later

**Android**: Target SDK 34

**Android**: Minimum SDK version 21

**Android**: Kotlin version 1.8.10 or later

**Android**: Gradle version 8.0 or later

## Initial React Native library installation

Follow the instructions below to add the react native library to your project. Alternatively, you can use this sample app as a starting point.

Add the following dependency to `package.json`:

```json
{`
   "dependencies":{
      .....,
      "@socure-inc/react-native-device-risk": "${sigmaReleaseDetails.react.version}"
   }
}```

## iOS installation

You can install the Digital Intelligence iOS SDK using CocoaPods or by manually downloading and installing it.

### CocoaPods installation

Inside of your target, add the corresponding pod lines:

```ruby
use_frameworks!

pod 'SocureDeviceRisk'
```

Update your pods from the terminal:

```undefined
pod install
```

You can also copy the folder `react-native-device-risk` and add it along with your other React Native pods.

### Run the build

Run `react-native run-ios`.

## Android installation

Add the Socure Maven URL to the root/project level in `build.gradle`.

```groovy
allprojects {
   repositories {
       .....
       maven {
           url "https://sdk.socure.com/"
       }
   }
}
```

Ensure Kotlin plugin is added in the dependencies section:

```groovy
buildscript {
             .....
             dependencies {
               .....
               classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:x.x.x"
             }
           }
```

> 📘  
> **Note**:  
> Socure has tested the build with plugin version `1.8.10`.

### Add the Kotlin dependency

In the main module `(<root project dir>/android/app/build.gradle)` add the below dependency in the dependencies section:

```groovy
dependencies {
  .....
  implementation "org.jetbrains.kotlin:kotlin-stdlib:x.x.x"
  .....
}
```

> 📘  
> **Note**:  
> Socure has tested the build with plugin version `1.8.10`.

Build and run:

- Run `yarn install`.
- Run `react-native run-android` from the root folder.

## Configuration and usage

The React Native Digital Intelligence SDK's main class is `RnSigmaDevice`. At a high level the SDK provides the following methods to collect data to send it to the Socure backend:

- `initializeSDK()`
- `processDevice()`

### `initializeSDK()`

Prior to interacting with the SDK, it must be initialized with `sdkKey` obtained from the **[Developer Workbench > SDK Keys](https://help.socure.com/riskos/docs/integration-guide-authentication#/)** page in RiskOS™.

The `initializeSDK()` function configures the SDK. It requires the `sdkKey` and optionally a set of `SigmaDeviceOptions` and returns a promise with the created `sessionToken`. The `sessionToken` can then be used on the respective device endpoints to fetch the data associated with the Session. Once retrieved, this `sessionToken` should be recorded by your application for use in the API requests associated with this transaction. The `sessionToken` will be passed in the API call in the `di_session_token` field. For example:

```javascript
// Initialize the SDK
try {
   const { sessionToken } = await RnSigmaDevice.initializeSDK(<YOUR SDK KEY>, null);
   setResultText('Session Token :: ' + sessionToken);
} catch (error) {
   Alert.alert('Failed', `${error}`);
}
```

#### `SigmaDeviceOptions`

These options can be passed into the `initializeSDK()` method to customize the SDK operation. It is represented as below:

```javascript
const options = {
   omitLocationData : <Optional boolean flag, defaults to false>,
   advertisingID : '<Optional string value>',
   useSocureGov : <Optional boolean flag, defaults to false>,
   configBaseUrl: '<Optional string value>'
   customerSessionId: '<Optional string value>'
}
```

- `omitLocationData`: A boolean flag used to omit the location data from being sent as part of data collection. By default, it is set to `false`. When set to `true,` the location data will not be included during data collection regardless of the location permission given by the user.
- `advertisingID`: An optional string value that, when passed, will allow the advertising ID information to be sent as a part of data collection. Defaults to `null`.
- `useSocureGov`: A boolean flag used to configure the DeviceRisk SDK to communicate with the SocureGov backend. Defaults to `false`. This only applies to customers provisioned in the SocureGov environment. This flag is ignored if a `configBaseUrl` is provided.
- `configBaseUrl`: An optional string that configures the SDK to use a custom base URL for retrieving SDK configuration information.
- `customerSessionId`: An optional value that allows a customer provided identifier to be used in place of the SDK generated session token when calling Socure services.

### `getSessionToken()`

This API lets the caller fetch the latest `sessionToken` generated by the SDK(including the one generated by `initializeSDK()`). The returned `sessionToken` can then be forwarded to the device endpoints to fetch the data associated with the Session:

```javascript
try {
   const { sessionToken } = await RnSigmaDevice.getSessionToken();
   console.log('Session Token:: ', sessionToken);
} catch (error) {
   console.log('Failed', `${error}`);
}
```

### Controlling Data Collection

By default the SDK will begin collecting data automatically. This includes data about the device and the way the user is interacting with the application. This data will be tracked as long as the application is in the foreground. Data collection is paused automatically when the application is backgrounded and automatically resumed when foregrounded.

In the event that further control over data collection is needed, two methods are supplied by the SDK:

- `RnSigmaDevice.pauseDataCollection()` \- Will pause ongoing user behavior and interaction data collection. Data collection will not resume until `SigmaDevice.resumeDataCollection()` is called.
- `RnSigmaDevice.resumeDataCollection()` \- Will resume data collection if collection was paused.

## Advanced Usage

### `processDevice()`

The `initializeSDK()` method automatically collects the data when initialized. Typically the data collected by `initializeSDK()` should be sufficient for most use cases. In cases where you need to explicitly invoke a data collection step, you can make use of `processDevice()`. Here we provide a `SigmaDeviceContext` to define the flow or screen within which the call occurs.

```javascript
try {
   const { sessionToken } = await RnSigmaDevice.processDevice('homepage');
   console.log('Session Token:: ', sessionToken);
} catch (error) {
      console.log('Failed', `${error}`);
}
```

#### `SigmaDeviceContext`

The following context values can be provided when calling `processDevice()`:

The following is the list of standard `sigmaDeviceContext` values. If your context does not match any of these standard values, you can send a custom string value:

```undefined
'default'
'homepage'
'signup'
'login'
'profile'
'password'
'transaction'
'checkout'
```

Note the `initializeSDK()` call uses the `'default'` value of `SigmaDeviceContext`.

## React Navigation Integration

The SDK supports automatic navigation context tracking for React Navigation v5, v6, and v7.

### `registerNavigationContextTracking()`

Registers automatic navigation context tracking with your React Navigation container. This method listens for navigation state changes and automatically reports the current screen name to the SDK.

The `registerNavigationContextTracking()` method should be called in the `onReady` callback of your `NavigationContainer` to ensure the navigation container is fully initialized before tracking begins.

```javascript
import { RnSigmaDevice } from '@socure-inc/react-native-device-risk';
import { NavigationContainer } from '@react-navigation/native';

function App() {
  const navigationContainerRef = React.useRef(null);

return (
    <NavigationContainer
      ref={navigationContainerRef}
      onReady={() => {
        RnSigmaDevice.registerNavigationContextTracking(navigationContainerRef);
      }}
    >
      {/* Your navigation structure */}
    </NavigationContainer>
  );
}
```

The `navigationContainerRef` parameter accepts either the ref object directly or `ref.current`.

## Silent Network Authentication

The Digital Intelligence React Native SDK provides the `performSilentNetworkAuth()` method to perform Silent Network Authentication using SIM-based verification. This allows you to verify device possession of a specified mobile number without requiring user interaction.

Silent Network Authentication is performed asynchronously. The result is not returned directly to the caller, but is made available for use within RiskOS™ decisioning workflows.

**Requirements:**

- The device must have an active SIM card and cellular data enabled.
- Devices on Wi-Fi will be automatically switched to cellular for authentication.
- Devices without cellular connectivity or with no SIM will not complete authentication, but this status is still reported for workflow decisioning.
- Your account must be provisioned for the `SilentNetworkAuth` feature.

**Usage Example:**

```javascript
try {
  await RnSigmaDevice.performSilentNetworkAuth("+12345678901")
  console.log('Silent Network Authentication initiated')
} catch (error) {
   console.log('Failed', `${error}`);
}
```

The `mobileNumber` parameter should be provided in E.164 format (for example, "+12345678901").

> 📘  
> **Note**:  
> The Silent Network Authentication process is not complete until the promise returned by the `performSilentNetworkAuth(...)` method is resolved.

> 📘  
> **Note**:  
> The result of the authentication is not returned directly. It is available for use in RiskOS™ workflows.
