Learn about OkHi's integration for verifying addresses.
1. Set up OkHi (Client-side)
The React Native Library internally uses the native iOS and android libraries. To install the OkHi React Native library, run one of the following commands in your project's directory (depending on which package manager you use):
yarnaddreact-native-okhireact-native-webview
npminstallreact-native-okhireact-native-webview
Next, configure your android and iOS apps as follows:
Android
Add the following permissions to your AndroidManifest.xml located under android/app/src/main/AndroidManifest.xml
All OkHi react-native libraries target Android devices >= SDK 21. Make sure you're targeting at least the same by modifying your android/build.gradle file
ext { minSdkVersion =21 ..//}
In your android/build.gradle add the OkHi Maven repo to the list of repositories i.e
You would require the latest versions of Xcode & Swift.
Enable Background modes in your application.
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.
All OkHi react-native libraries target ios devices >= 12. Make sure you're targeting at-least the same by modifying your both your Podfile and deployment target.
Podfile located under: ios/Podfile
platform :ios, '12.0'
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>
Finally install all required pods by running the following command in the ios directory
pod install
Set up OkVerify in your AppDelegate file
Open your AppDelegate.mm file located under ios/MyApp/AppDelegate.mm and add the following lines
#import "OkHi/OkHi-Swift.h" // -- add this top of file
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[OkVerify startMonitoring]; // -- add this
// -- rest of react native configuration -- //
return YES;
}
OkHi 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.
Replace my_branch_id and my_client_key with the keys provided to you after sign up.
import React, {useEffect} from'react';import {View} from'react-native';import*as OkHi from'react-native-okhi';import AddressScreen from'./AddressScreen';constApp= () => {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> );};exportdefault 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.
Building with pro-guard enabled
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 classcom.esotericsoftware.** {*;}-keep classjava.beans.** { *; }-keep classsun.reflect.** { *; }-keep classsun.nio.ch.** { *; }-keep classcom.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
2. Create and verify an address (Client-side)
Add a button to your UI that would enable launching of OkHi address collection tool.
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.
import React, {useState} from'react';import {Button, View} from'react-native';import { isLocationServicesEnabled, OkHiLocationManager, request, openAppSettings} from'react-native-okhi';constAddressScreen= () => {const [launch,setLaunch] =useState(false);// TODO 1: Change these to your own user detailsconstuser= { phone: '+234xxxxx', // It is important to provide your actual phone number, as a message will be sent to this number
firstName:'Gift', lastName:'Moore', email: 'giftmoore@okhi.com', // It is important to use your actual email address, an email may be sent to the provided address
};consthandleOnSuccess= response => {console.log(response); response.startVerification().then(async locationId => {console.log('started verification for: '+ locationId); }).catch(error => {console.log(error.code);console.log(error.message); }); };return ( <View> <Buttontitle="Create address"onPress={() =>setLaunch(true)} /> <OkHiLocationManagerlaunch={launch}user={user}onCloseRequest={() =>setLaunch(false)}onError={console.log}onSuccess={handleOnSuccess}config={{streetView:true}} /> </View> );};exportdefault AddressScreen;
import React, {useEffect, useState} from'react';import {ActivityIndicator, Button, Text, View} from'react-native';import { isLocationServicesEnabled, OkHiLocationManager, request, openAppSettings} from'react-native-okhi';import AsyncStorage from'@react-native-async-storage/async-storage';constAddressScreen= () => {const [launch,setLaunch] =useState(false);const [loading,setLoading] =useState(true);const [homeAddressId,setHomeAddressId] =useState(null);// TODO 1: Change these to your own user detailsconstuser= { phone:'+2348000000000', firstName:'Gift', lastName:'Moore', email:'giftmoore@okhi.com' }constpersistAddressId=async (id, type) => {try {awaitAsyncStorage.setItem(`OkHiAddress:${type}`, id); } catch (error) {// Error saving data } };constretrieveAddress=async type => {try {constres=awaitAsyncStorage.getItem(`OkHiAddress:${type}`);return res; } catch (error) {// Error retrieving data } };useEffect(() => {setLoading(true);retrieveAddress('home').then(res => {setHomeAddressId(res); }).finally(() => {setLoading(false); }); }, []);conststyle= { flex:1, justifyContent:'center', alignItems:'center', };constrationale= { title:'Location permissions', text: "To verify your address, allow YOUR_APP_NAME_HERE to check your phone's location, even when you're not using the app",
successButton: {label:'Grant'}, denyButton: {label:'Deny'}, };consthandleOnPress= () => {// TODO 2: Show a location permissions educational primer before requesting for background location permissions.request('always', rationale,async (status, error) => {constlocationServicesAvailable=awaitisLocationServicesEnabled();console.log(error);if (status ==='authorizedAlways'&& locationServicesAvailable) {setLaunch(true); }/* TODO 3: When the user does not grant location permission the first time. 1. Show a primer to educate them on how to do this in settings 2. Provide a button to send them to settings. You may use `openAppSettings()` helper function */ }); };consthandleOnSuccess= response => {console.log(response); response.startVerification().then(async locationId => {console.log('started verification for: '+ locationId);awaitpersistAddressId(locationId,'home');setHomeAddressId(locationId); }).catch(error => {console.log(error.code);console.log(error.message); }).finally(() => {setLaunch(false); }); };constRenderLoader= () => {return ( <Viewstyle={style}> <ActivityIndicator /> </View> ); };if (loading) {return <RenderLoader />; }if (homeAddressId) {return <Text>Verification started for {homeAddressId}</Text>; }return ( <Viewstyle={style}> <Buttontitle="Create address"onPress={handleOnPress} /> <OkHiLocationManagerlaunch={launch}user={user}onCloseRequest={() =>setLaunch(false)}onError={console.log}onSuccess={handleOnSuccess}config={{streetView:true}} /> </View> );};exportdefault AddressScreen;
If you're targeting Android versions >= 8 and you're using the OkVerify library you need to make sure your users select on "Allow always" when granting permissions otherwise the verification process won't work.
Test
If verification has started successfully:
Android:
a persistent notification should show, indicating that verification is on going
iOS
when you simulate a change in the location of the device, you should see the GPS icon lighting up at the top of the screen
Common issues:
if background location permission is not granted, verification will not start
3. Add address endpoint (Server-side)
Here's a sample address payload that the client would get on successful address collection:
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 endpointapp.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 updatesreturn;});
4. 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.
5. 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 endpointapp.get("/users/addresses", (req) => {// Get data from db. Example result:constdbResult= {"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.
6. Test the integration
7. 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
consttheme= { colors: {primary:'#005D67'}, appBar: { backgroundColor:'#005D67', logo:'https://mydomain.com/logo.png' },};<OkHiLocationManageruser={user}launch={launch}theme={theme} // customizes apperance of buttons and app barstyle={styles.locationManager} // customizes apperance of the wrapping containeronSuccess={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.
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" />
<activityandroid:name=".MainActivity"> <intent-filter> <actionandroid:name="android.intent.action.MAIN" /> <categoryandroid:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application>
8. 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: