Expo React Native Guide

Learn about OkHi's integration for verifying addresses.

Make sure you are running an Android Expo development build. See how to enable development builds here.

Installation

To install the OkHi React Native library run the command bellow

npx expo install react-native-webview react-native-okhi

Android

Enable Expo Android Development build

If you haven't done this already, make sure you are running an android development build. You can achieve this by running the bellow command in your projects root directory.

npx expo run:android

At this point you should be able to navigate to android/

Configuration

Permissions

Add the following permissions to your AndroidManifest.xml located under android/app/src/main/AndroidManifest.xml

<manifest ...>
​    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    ...
    
    <application>
    ...
    </application>

</manifest>

Maven Repo

In your android/build.gradle add the OkHi Maven repo to the list of repositories i.e

```
allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url(new File(['node', '--print', "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), '../android'))
        }
        maven {
            // Android JSC is installed from npm
            url(new File(['node', '--print', "require.resolve('jsc-android/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim(), '../dist'))
        }

        google()
        mavenCentral()
        maven { url 'https://www.jitpack.io' }
        maven { url "https://repo.okhi.io/artifactory/maven" } // <- add this
    }
}

```

iOS

Enable Expo iOS Development build

If you haven't done this already, make sure you are running a ios development build. You can achieve this by running the bellow command in your projects root directory.

npx expo run:ios

At this point you should be able to navigate to ios/

Configuration

Enable Background modes

OkHi obtains verification signals in the background, to enable this make sure to add "Location updates" and "Background fetch" to your Background Modes under Signing & Capabilities of your target.

Permissions

Add necessary permissions to your info.plist file located under /ios/MyApp

<key>NSLocationWhenInUseUsageDescription</key>
<string>String that explains why you need this permission</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>String that explains why you need this permission</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>String that explains why you need this permission</string>

AppDelegate

Open your AppDelegate.mm file located under ios/MyApp/AppDelegate.mm and add the following lines

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTLinkingManager.h>

// --- add this --- //
#import "OkHi/OkHi-Swift.h"
// --------------- //

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [OkVerify startMonitoring]; // <-- add this
  self.moduleName = @"main";

  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

Install pods

If you have your project running, stop it and run the bellow command. It'll install all the necessary pods.

npx expo run:ios

Usage

important: initialisation has to be done each time on app start and shouldn't have any blocking operations before it. See full integration example

import { Button } from "react-native";
import { ThemedView } from "@/components/ThemedView";
import { useEffect, useState } from "react";
import { initialize as initializeOkHi, OkHiLocationManager, OkHiUser } from "react-native-okhi";

export default function App() {
  const [launch, setLaunch] = useState(false);

  useEffect(() => {
    // called each time on app start
    initializeOkHi({
      credentials: {
        branchId: "<branch_id>",
        clientKey: "<client_key>",
      },
      context: {
        mode: "prod",
      },
      notification: {
        title: "Address verification in progress",
        text: "Tap here to view your verification status.",
        channelId: "okhi",
        channelName: "OkHi Channel",
        channelDescription: "OkHi verification alerts",
      },
    });
  }, []);

  return (
    <ThemedView style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Button title="Verify an address" onPress={() => setLaunch(true)} />
      <OkHiLocationManager
        launch={launch}
        user={{ phone: "+254700......", firstName: "Jane", lastName: "Doe", email: "jane@okhi.io" }}
        onCloseRequest={() => setLaunch(false)}
        onError={console.log}
        onSuccess={async (response) => {
          const locationId = await response.startVerification();
          console.log(`started verification for: ${locationId}`);
        }}
      />
    </ThemedView>
  );
}

Add address endpoint (Server-side)

Here's a sample address payload that the client would get on successful address collection:

{
    "user": {
        "id": "B5QgvjE8WC",
        "phone": "+234xxxxx",
        "firstName": "Gift",
        "lastName": "Moore"
    },
    "location": {
        "id": "8F0yPK1Zdj",
        "lat": 6.442849499999999,
        "lon": 3.424421,
        "plusCode": "6FR5CCVF+4Q",
        "propertyName": "10",
        "streetName": "Raymond Njoku Street",
        "title": "Raymond Njoku Street",
        "subtitle": "10",
        "url": "https://okhi.me/8F0yPK1Zdj",
        "streetViewPanoId": "ufxEWf-zpKLcTxIe04o6Bg",
        "streetViewPanoUrl": "https://maps.googleapis.com/maps/api/streetview?size=640x640&fov=45&location=6.44275037195316%2C3.424513218681455&heading=321.4785708568841&pitch=-9.5945875978788",
        "userId": "B5QgvjE8WC",
        "displayTitle": "10, Raymond Njoku Street",
        "country": "Nigeria",
        "state": "Lagos",
        "city": "Eti-Osa",
        "countryCode": "ng"
    }
}

Create a secure endpoint on your server that your app can use to pass address details to your server. Remember to handle corner cases such as, address updates & multiple addresses if your app supports it.

//Secure new address endpoint
app.post("/users/addresses", async (req) => {
  const { user, location } = req.body;
  const { id, firstName, lastName, phone } = user;
  const {
    id: locationId, displayTitle, title, subtitle, country, state, city, countryCode, lat, lon, plusCode, propertyName, streetName, url, streetViewPanoId, streetViewPanoUrl
  } = location;
  console.log(user, location);
  // Store the location.id. Used to match webhook updates
  return;
});

Handle verification events (Server-side)

OkHi sends verification status updates over a few days while verification is on going. Follow the webhook guide to setup a webhook and receive these verification status updates and run actions such as upgrading a user's KYC level.

Show verification status in app(Server- & Client-side)

Create a secure endpoint to enable your app to retrieve address details, including the verification status received from the webhook

// Secure address retrieval endpoint
app.get("/users/addresses", (req) => {
  // Get data from db. Example result:
  const dbResult = {
    "id": "8F0yPK1Zdj",
    "status": "verified",
    "displayTitle": "10, Raymond Njoku Street",
    "title": "Raymond Njoku Street",
    "subtitle": "10",
    "country": "Nigeria",
    "state": "Lagos",
    "city": "Eti-Osa",
    "countryCode": "ng",
  }
  return dbResult;
});

Show the resulting address details and status on the address page in your app.

Test the integration

TitleScenarioHow to test

Create an address

Address creation succeeds and verification is initiated

Launch OkHi's address manager via the button you created and create an address. A sticky notification appears on android.

Dashboard

When verification is initiated, the address shows up on OkDash

Check OkDash, you should see a list of all the addresses created. It takes ~3min for addresses to show up on OkDash

Proof of address

When an address is verified, the webhook receives the status update and the app shows the correct verification status.

A proof of address certificate is made available on OkDash.

Install your app on your personal device that you move around with and create your home address. Check OkDash in 3 days for your proof of address certificate once your address has been verified.

Business logic

When an address is verified or not, the correct business logic is applied successfully.

Conduct a comprehensive test with multiple users, wherein they create various addresses to observe diverse outcomes. These outcomes may include successful creation of home addresses, entering incorrect addresses, refusing to grant necessary location permissions, or uninstalling the app immediately after initiating the address verification process, among other scenarios.

Customise the integration

Create a location permissions primer (Required)

Create your custom location permissions primer to educate your user on the requirement for location permissions. Make sure to follow our design best practices to ensure you meet the Google Play store and AppStore requirements.

Customise OkCollect (optional)

It is possible to completely transform the default appearance of OkHiLocationManager to better match your brand by providing values to the theme prop

const theme = {
 colors: {primary: '#005D67'},
 appBar: {
   backgroundColor: '#005D67',
   logo: 'https://mydomain.com/logo.png'
  },
};

<OkHiLocationManager
 user={user}
 launch={launch}
 theme={theme} // customizes apperance of buttons and app bar
 style={styles.locationManager} // customizes apperance of the wrapping container
 onSuccess={handleOnSuccess}
 onCloseRequest={handleCloseRequest}
 onError={handleOnError}
/>

Customising address type

You may turn off either of the OkHi address types. This is to allow your users to create either home or work addresses to better suit your use-case. By default both address types are on.

<OkHiLocationManager
  ...// normal configuration
  config={{ addressTypes: { home: true, work: false } }}
/>

Customise notification icon & color

You can specify a custom default icon and a custom default color by adding these lines inside the application tag to set the custom default icon and custom color. You'll need to have already created the icon resource in your android application. Icon assets can be created by following these steps

<application>
    <!-- Set custom default icon for OkVerify's foreground service -->
    <meta-data android:name="io.okhi.android_background_geofencing.foreground_notification_icon" android:resource="@drawable/ic_person_pin" />
    <!-- Set custom default icon color for OkVerify's foreground service -->
    <meta-data android:name="io.okhi.android_background_geofencing.foreground_notification_color" android:resource="@color/colorAccent" />
    
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Getting ready to go live

Production credentials

Notify us that you'd like to cut a production build so we can supply production credentials.

Prepare for submission to Google Play store and App Store

Submitting an app to Google Play store and App Store that has background location permissions has a few extra requirements. Follow these guide to know what to expect and how to handle the extra requirements:

Publishing to Google Play store

Publishing to App Store

Troubleshooting

Incase you run into problems while integrating, review common issues here:

React Native troubleshoot guide

Next steps

Review Full integration sample project

Review React Native library documentation

Review OkHi integration best practices

Last updated