OkHi Documentation
  • 👋Welcome Home
  • OVERVIEW
    • OkHi Product Overview
    • Integration process overview
    • Verification terminology
    • Case Studies
  • Best Practices
    • Integration Best Practices
    • Live Examples
    • Tips for PMs & QA
      • Testing & QA Guide
      • Publishing to app stores
        • Google Play store
        • Apple App Store
    • Tips for designers
  • Code Libraries
    • Developer Quick Start
      • Environment setup
      • Release Notes
    • Android Guide
      • Android Dependencies
      • Migrating to the latest library
    • iOS Guide
    • React Native Guide
      • React Native Dependencies
      • React Native troubleshoot guide
    • Expo React Native Guide
    • Flutter Guide
      • Flutter Dependencies
    • JS library
      • API Reference
      • OkCollect Webhook
      • Changelog
    • WooCommerce Plugin
      • Changelog
  • Verification Status
    • Customer Dashboard
    • Verification Status Updates
      • Webhook v3
        • Webhook Signature Verification Guide
      • Webhook v2
      • Verification Status API
      • Proof Of Address Certificate API
      • FAQs
    • API reference docs
  • Troubleshooting
    • Error Responses
    • Common technical pitfalls
    • How to reduce "Unknowns"
    • FAQs
      • Technical FAQs
      • Compliance FAQs
    • Get in touch
Powered by GitBook
On this page
  • Installation
  • Configuration
  • Android
  • iOS
  • Initialisation
  • Create and verify addresses
  • Digital Verification (Default)
  • Physical Verification
  • Both Physical & Digital Verification
  • Address book only
  • Tips & Tricks
  • Create an address and verify it later
  • Making it yours
  • Customise notification icon & color
  • Prepare for submission to the Google Play store
  • Building with pro-guard
  • Create home or work addresses
  • Error handling
  • Known issues
  • Server side integration
  • Accessing address properties
  • Handling verification events
  • Testing
  • Next steps

Was this helpful?

  1. Code Libraries

Expo React Native Guide

Learn about OkHi's integration for verifying addresses.

PreviousReact Native troubleshoot guideNextFlutter Guide

Last updated 2 months ago

Was this helpful?

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

Installation

To install the OkHi React Native library, run the following command.

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

Configuration

Android

Maven repo set-up

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

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
    }
}​

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.FOREGROUND_SERVICE" android:foregroundServiceType="location"/>
    ...
    
    <application>
    ...
    </application>
​
</manifest>

iOS

Minimum OS support level

The OkHi React Native library supports iOS devices running OS 12+. Make sure you are targeting at-least the same by following these steps.

  1. In the Xcode project: Update the Deployment Target to iOS 12 or later:

    • Open your Xcode project.

    • Select your project in the Navigator.

    • Under the General tab, locate the Deployment Info section.

    • Set the iOS Deployment Target to 12.0 or higher.

  2. In the Podfile: Specify the platform version to ensure CocoaPods aligns with the iOS 12+ requirement:

    • Open your Podfile in a text editor.

    • Add or update the platform line at the top of the file as shown below

    platform :ios, '12.0'
    • Save the file and run pod install to apply the changes.

Background Modes

The library obtains and transmits verification signals in the background, to enable this make sure to add Location updates and Background fetch at Background Modes under Signing & Capabilities of your target

Permissions

Add the following permissions to your Info.plist located under the root directory of your iOS project.

<dict>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Grant to enable verifying your addresses.</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Grant to enable creating addresses at your current location.</string>
    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>Grant to enable creating and verifying your addresses.</string>
</dict>

AppDelegate file setup

Finally set up background location monitoring in your AppDelegate file. Open your AppDelegate file located under ios/<project name>/AppDelegate.swift and add in the following. If you are on React Native < 0.77, you'll have a AppDelegate.mm

import UIKit
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
import OkHi //<- add this

@main
class AppDelegate: RCTAppDelegate {
  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    
    OkVerify.startMonitoring() //<- add this
    
    self.moduleName = "OkHiRNVerificationDemo"
    self.dependencyProvider = RCTAppDependencyProvider()

    // 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)
  }

  override func sourceURL(for bridge: RCTBridge) -> URL? {
    self.bundleURL()
  }

  override func bundleURL() -> URL? {
#if DEBUG
    RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
    Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
  }
}
#import "AppDelegate.h"

// <-- import these
#import <OkHi/OkHi.h>
#import <OkHi/OkHi-Swift.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [OkVerify startMonitoring]; // <-- add this
  
  // -- rest of react native configuration -- //
  return YES;
}

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

Initialisation

Add the following initialisation code to your App.js file in such a way that the code is executed whenever your app is opened.

import React, {useEffect} from 'react';
import {View} from 'react-native';
import * as OkHi from 'react-native-okhi';
import AddressScreen from './AddressScreen';

const App = () => {
  useEffect(() => {
    OkHi.initialize({
      credentials: {
        branchId: '', // your branch ID
        clientKey: '', // your 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',
      },
    })
      .then(() => console.log('init done'))
      .catch(console.log); 
  }, [])
  return (
    <View>
      <AddressScreen />
    </View>
  );
};

export default App;

Test

To confirm that initialisation is working as expected, the `init done` log should be printed out in your console every time your app is opened.

Create and verify addresses

Always use your phone number or a phone number you own during testing as a message will be sent to this number after an address is created.

We recommend that you persist the verification state of the user in your app local storage. This state can be used to ensure that a user may only verify a predefined number of addresses. Usually one address for most use cases.

Digital Verification (Default)

import React, { useEffect, useState } from "react";
import { ActivityIndicator, Button, View, ViewStyle } from "react-native";
import {
  initialize as initializeOkHi,
  OkCollectSuccessResponse,
  OkHiException,
  OkHiLocationManager,
  OkHiLocationManagerProps,
  OkHiUser,
} from "react-native-okhi";

const App = () => {
  const [launch, setLaunch] = useState(false);
  const style: ViewStyle = {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  };
  const user: OkHiUser = {
    firstName: "John",
    lastName: "Doe",
    phone: "+234......",
    appUserId: "abcd1234",
    email: "john@okhi.co",
  };
  const theme: OkHiLocationManagerProps["theme"] = {
    appBar: {
      backgroundColor: "#333",
      logo: "https://cdn.okhi.co/icon.png",
    },
    colors: {
      primary: "#333",
    },
  };

  useEffect(() => {
    const handleInit = async () => {
      await initializeOkHi({
        credentials: {
          branchId: "", // your branch ID
          clientKey: "", // your 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",
        },
      });
    };
    handleInit();
  }, []);

  const handleOnSuccess = async (response: OkCollectSuccessResponse) => {
    try {
      const locationId = await response.startVerification();
      console.log("started verification for: " + locationId);
    } catch (error) {
      const err = error as OkHiException;
      console.log(err.code);
      console.log(err.message);
    } finally {
      setLaunch(false);
    }
  };

  const handleError = (error: OkHiException) => {
    console.log(error.code);
    console.log(error.message);
  };

  return (
    <View style={style}>
      <Button title="Verify an address (digital)" onPress={() => setLaunch(true)} />
      <OkHiLocationManager
        launch={launch}
        user={user}
        onCloseRequest={() => setLaunch(false)}
        onError={handleError}
        onSuccess={handleOnSuccess}
        theme={theme}
      />
    </View>
  );
};

export default App;

Physical Verification

If you'd like to only have physical verification done you can include usage types as part of the config object that's passed to OkHiLocationManager

<OkHiLocationManager
  ..//
  config={{usageTypes: ["physical_verification"]}} 
/>

Both Physical & Digital Verification

It's possible to have both physical and digital verification to run at the same time for a given address. Include both usage types as part of the array.

<OkHiLocationManager
  ..//
  config={{usageTypes: ["physical_verification", "digital_verification"]}} 
/>

Address book only

If you'd like to only create the address and still obtain usage data that will help verification later, you can include the usage type as part of the configuration object that's passed to OkHiLocationManager

<OkHiLocationManager
  ..//
  config={{usageTypes: ["address_book"]}} 
/>

Tips & Tricks

Create an address and verify it later

It's possible to create an address, obtain usage data that will help verification and initiate either physical and/or digital at a later time.

The example assumes:

  1. You've securely stored previous address information either on device or server and have access to the locationId obtained in the success response of okcollect.

import React, { useEffect, useRef, useState } from "react";
import { ActivityIndicator, Button, View, ViewStyle } from "react-native";
import {
  initialize as initializeOkHi,
  OkCollectSuccessResponse,
  OkHiException,
  OkHiLocationManager,
  OkHiLocationManagerProps,
  OkHiUser,
  UsageType,
} from "react-native-okhi";

const App = () => {
  const [launch, setLaunch] = useState(false);
  const createdLocationId = useRef<string | undefined>(undefined);

  const style: ViewStyle = {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  };
  const user: OkHiUser = {
    firstName: "John",
    lastName: "Doe",
    phone: "+234...",
    appUserId: "abcd1234",
    email: "john@okhi.co",
  };
  const theme: OkHiLocationManagerProps["theme"] = {
    appBar: {
      backgroundColor: "#333",
      logo: "https://cdn.okhi.co/icon.png",
    },
    colors: {
      primary: "#333",
    },
  };

  useEffect(() => {
    const handleInit = async () => {
      await initializeOkHi({
        credentials: {
          branchId: "", // your branch ID
          clientKey: "", // your 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",
        },
      });
    };
    handleInit();
  }, []);

  const handleOnSuccess = async (response: OkCollectSuccessResponse) => {
    try {
      createdLocationId.current = response.location.id;
      const locationId = await response.startVerification();
      console.log("started verification for: " + locationId);
    } catch (error) {
      const err = error as OkHiException;
      console.log(err.code);
      console.log(err.message);
    } finally {
      setLaunch(false);
    }
  };

  const handleError = (error: OkHiException) => {
    console.log(error.code);
    console.log(error.message);
  };

  const renderOkHiLocationManager = () => {
    const usageTypes: UsageType = createdLocationId.current ? ["digital_verification"] : ["address_book"];
    return (
      <OkHiLocationManager
        launch={launch}
        user={user}
        onCloseRequest={() => setLaunch(false)}
        onError={handleError}
        onSuccess={handleOnSuccess}
        theme={theme}
        config={{
          usageTypes,
        }}
        location={{ id: createdLocationId.current }} // pass id if created location
      />
    );
  };

  return (
    <View style={style}>
      <Button title="Create an address (address book)" onPress={() => setLaunch(true)} />
      <Button title="Verify saved address (digital)" onPress={() => setLaunch(true)} />
      {renderOkHiLocationManager()}
    </View>
  );
};

export default App;

Making it yours

Customise address creation experience

It is possible to completely transform the default appearance of OkHiLocationManager to better match your brand by creating a theme object and passing it to OkHiLocationManager as shown below.

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}
/>

Customise notification icon & color

<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>

Prepare for submission to the Google Play store

Submitting an app to the Google Play 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:

Building with pro-guard

If you have minifyEnabled set to true in your build.gradle file located android/app/build.gradle, you'll need to modify your proguard-rules.pro file, located android/app/proguard-rules.proas shown bellow to include classes required by the library to run.

-dontwarn sun.reflect.**
-dontwarn java.beans.**
-dontwarn sun.nio.ch.**
-dontwarn sun.misc.**

-keep class com.esotericsoftware.** {*;}

-keep class java.beans.** { *; }
-keep class sun.reflect.** { *; }
-keep class sun.nio.ch.** { *; }

-keep class com.snappydb.** { *; }
-dontwarn com.snappydb.**

# If you don't use OkHttp as a dep and the following

-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn javax.annotation.**
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn okhttp3.internal.platform.ConscryptPlatform
-dontwarn org.conscrypt.ConscryptHostnameVerifier

In instances where the web module cannot fire the OS functions i.e. Location permission requests and enabling GPS on QuickStart, after building with Progard enabled, add the following rule to the progard-rules.pro file:

-keepclassmembers class io.okhi.android_okcollect.interfaces.WebAppInterface {
    @android.webkit.JavascriptInterface <methods>;
}

Create home or work addresses

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 } }}
/>

Error handling

The OkHiLocationManager has an onError prop where you can handle errors. The OkHiException object has both code and message properties that will help you diagnose what went wrong with the either the address creation process or address verification process.

const handleError = (error) => {
// handle errors
  console.log(error.code + ":" + error.message);
}

<OkHiLocationManager
  launch={launch}
  user={user}
  onCloseRequest={() => setLaunch(false)}
  onError={handleError}
  onSuccess={handleOnSuccess}
  theme={theme}
  config={{
    usageTypes: ["digital_verification"],
  }}
/>

Known issues

unsupported_platform error code when launching the OkHiLocationManager on Android OS < 7

Due to known browser limitations on devices running Android OS versions below 7, the OkHiLocationManager is not supported on these devices. This is because the necessary browser APIs required to accurately create and verify addresses are unavailable. We are aware of this issue and are actively working on an update to address it. In the meantime, please ensure you capture and track errors as demonstrated above to better understand the impact on your users.

Server side integration

Accessing address properties

const handleOnSuccess = async (response: OkCollectSuccessResponse) => {
    console.log(response.user.id); // access user properties
    console.log(response.location.id); // access location properties
    await sendToServer(response.user, response.location) // send address info to your server
    await response.startVerification(); // start verification
}

Handling verification events

Testing

Title
Scenario
How 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 OkHi Dashboard

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.

Next steps

Review integration examples

Replace my_branch_id and my_client_key with the keys provided to you after .

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

See full integration example .

See full integration example .

See full integration example .

See full integration example .

You created an address using address_book usage type. See .

Once verification starts a persistent notification is visible (Android < 13). 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

On the client/app, within your onSucess handler you can access both user and address information which you can use to transit securely to your servers. See the API reference for complete list of properties on and .

Once an address has been created and you've configured a webhook in the OkHi , you'll be able to receive updates regarding address verification in your backend, which you can use to enable certain services in your app. The OkHi Dashboard allows you to do much more; please see the full documentation here.

Review

sign up
integration example
here
here
here
here
steps
Publishing to Google Play store
user
location
Customer Dashboard
webhook
Digital Verification Example
Physical Verification Example
Digital and Physical Verification Example
Create and verify an address later Example
API ref
OkHi integration best practices
here
here