How to Integrate the Device Data Collector into React Native Applications

To integrate the Mobile SDKs into a hybrid React Native application, there are three main steps:

  1. iOS Integration
  2. Android Integration
  3. Platform Selection Integration

Integrating Kount iOS SDK to React Native Hybrid Apps

Provide native support for your Kount solution by integrating the Kount iOS SDK into your React Native application. This allows you to use Kount's service without having to create API calls.

To integrate native iOS SDK into react native app(s), we need to first create a wrapper around iOS SDK and then integrate it in react native project. Here is the step by step guide of how it is done.

Integration Steps for iOS (include SDK in project)

There are three ways to integrate Kount iOS SDK with React Native App:

  1. Universal Static Library (libKountDataCollector.a)
    Refer to How to Integrate Mobile SDKs for iOS Universal Static Library.
  2. XCFramework (KountDataCollector.xcframework)
    Refer to How to Integrate the Kount Devices Data Collector XCFramework Package into an iOS 14.5 Application.
  3. Kount CocoaPods
    Refer to How to Integrate the Kount Device Data Collector CocoaPods Package into an iOS 13.5 Application.

Integration Steps for iOS (create wrapper)

Setup

  1. Open the iOS project within your React Native application in Xcode.
  2. In Finder, go to the project folder, iOS folder, and then open .xcworkspace (if pods)/.xcodeproj.

Objective-C

  1. Import KDataCollector.h and KountAnalyticsViewController.h in AppDelegate.h
  2. Add following code snippet in Appdelegate.m. Ensure you update these settings as appropriate.
        
        [[KDataCollector sharedCollector] setDebug:YES];
        // TODO Set your Merchant ID
        [[KDataCollector sharedCollector] setMerchantID:0];
        // TODO Set the location collection configuration
        [[KDataCollector sharedCollector]setLocationCollectorConfig:KLocationCollectorConfigRequestPermission];
        // For a released app, you'll want to set this to KEnvironmentProduction
        [[KDataCollector sharedCollector] setEnvironment:KEnvironmentTest];
        [[KountAnalyticsViewController sharedInstance] setEnvironmentForAnalytics: 
                    [KDataCollector.sharedCollector environment]];
        
  3. Create custom native modules: First step is to create our main custom native module header and implementation files. Create a new file called KountBridgeModule.h and add the following to it.
        #import <React/RCTBridgeModule.h>
        #import "KDataCollector.h"
        #import "KountAnalyticsViewController.h"
        
        @interface KountBridgeModule: NSObject <RCTBridgeModule>
        -(void) collect;
        @end
        
  4. Implement the native module. Create the implementation file KountBridgeModule.m (in the same folder as the .h file) and write the following code snippet:
       
        #import "KountBridgeModule.h"
         @implementation KountBridgeModule
        
            RCT_EXPORT_MODULE(KountBridgeModule);
            RCT_EXPORT_METHOD(collect){
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *sessionID = nil;
        
                    // By default set analyticsSwitch to false
                    [[KountAnalyticsViewController sharedInstance] collect:sessionID analyticsSwitch:false 
                    completion:^(NSString * _Nonnull sessionID, BOOL success, NSError * 
                           _Nullable error) {
                           if(success) {
                                   NSLog(@"Collection Successful");
                           }
                           else {
                                   if (error != nil) {
                                   NSLog(@"Collection failed with 
                           error:%@",error.description);
                               }
                               else {
                                   NSLog(@"Collection failed without error");
                               }
                      }
                }];
           });
        }
        
        RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getAppID) {
            NSString *sessionID = [KountAnalyticsViewController getAppSessionID];
            return sessionID;
        }
        
        @end
        

Swift

  1. Import KDataCollector.h and KountAnalyticsViewController.h in <ProjectName>-Bridging-Header.h if bridging header already created or you create one and import above header files.
  2. Add following code snippet in Appdelegate.swift. Make sure to update these settings as needed.
        // Set the location collection configuration
        KDataCollector.shared().locationCollectorConfig = KLocationCollectorConfig.requestPermission
            KDataCollector.shared().debug = true
            // Set your Merchant ID
            KDataCollector.shared().merchantID = 999999
            // For a released app, you'll want to set this to KEnvironmentProduction
            KDataCollector.shared().environment = KEnvironment.test
            KountAnalyticsViewController().setEnvironmentForAnalytics(KDataCollector.shared().environment)
        
  3. Create custom native modules: First step is to create our main custom native module .swift and .m files. Create a new file called KountBridgeModule.swift and add the following to it.
        import UIKit
        
        @objc(KountBridgeModule)
        
        class KountBridgeModule: NSObject {
        
        @objc
        func collect() {
          DispatchQueue.main.async {
            KountAnalyticsViewController().collect(KountAnalyticsViewController.getAppSessionID(), analyticsSwitch: false) {
                (sessionID, success, error) in
                    if (success) {
                        print("IDK",KountAnalyticsViewController.getAppSessionID())
                        print("Collection Successful")
                    }
                    else {
                        if((error) != nil) {
                            print("Collection failed with error",error?.localizedDescription as Any)
                        }
                        else {
                            print("Collection failed without error")
                        }
                }
            }
          }
  4. Create a new file called KountBridgeModule.m and add following to it to make Native code access available to .js files.
        #import <Foundation/Foundation.h>
        #import "React/RCTBridgeModule.h"
        
         @interface RCT_EXTERN_MODULE(KountBridgeModule, NSObject)
         
         RCT_EXTERN_METHOD(collect)
        + (BOOL)requiresMainQueueSetup
        {
            return YES;
        }
        
        RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getAppID) {
    			        NSString *sessionID = [KountAnalyticsViewController getAppSessionID];
    			        return sessionID;
    		       }
        
         @end
        

Integrating Kount Android SDK to React Native Hybrid Apps

Integrate the Kount Analytics SDK into your React Native application to collect additional end-user information. This assists in detecting suspicious devices and preventing fraud.

Integration steps for Android (include in project)

You have two project integration options. Choose the one that best fits your project. Kount recommends using the Gradle option if you do not have a preference.

  1. Gradle
    Refer to How to Integrate the Android Gradle for Mobile Apps.
  2. Android Library File
    Refer to How to Integrate the Android Library JAR for Mobile Applications.
NOTE: If android:allowbackup attribute is false in your <application> tag, add tools:replace="android:allowBackup" to your application tag.

Integrations steps for Android (create wrapper)

  1. In the main activity of your application, initialize the collector and assign the<MERCHANT_ID> you received from Kount. Optionally, you can provide a sessionID if you need to generate your own. If not, the SDK will generate one for you. You must send this sessionID back to your severs in order to make calls to the Kount API (see the Kount API section below).
    Add the following initialization in your MainActivity:
        import com.kount.api.analytics.AnalyticsCollector;
        import com.kount.api.analytics.AnalyticsConstants;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
          ...
          // REQUIRED SECTION
          AnalyticsCollector.setMerchantId(<MERCHANT_ID>);
          // END REQUIRED SECTION
          AnalyticsConstants.collectDeviceDataForSession=true
      
          //For production need to add AnalyticsCollector.ENVIRONMENT_PRODUCTION
          AnalyticsCollector.setEnvironment(AnalyticsCollector.ENVIRONMENT_TEST);
      
          // OPTIONAL SESSION_ID SECTION
          final String deviceSessionID UUID.randomUUID().toString();
          AnalyticsCollector.setSessionId(deviceSessionID);
          // END OPTIONAL SESSION_ID SECTION
          ...
         }
        
  2. To support Location Collection in Android API 23 and above, add the following permissions to your main activity, onCreate method:
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
          if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AnalyticsCollector.REQUEST_PERMISSION_LOCATION);
          } else {
              ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AnalyticsCollector.REQUEST_PERMISSION_LOCATION);
          }
        }
        
  3. Create custom native modules: The first step is to create the KountModule.java Java file inside android/app/src/main/java/com/your-app-name/ folder. This Java file contains your native module Java class.
    Add the following content:
        import androidx.annotation.NonNull;
        import com.facebook.react.bridge.ReactApplicationContext;
        import com.facebook.react.bridge.ReactContextBaseJavaModule;
        import com.facebook.react.bridge.ReactMethod;
        import com.kount.api.analytics.AnalyticsCollector;
    
        public class KountModule extends ReactContextBaseJavaModule {
          private static ReactApplicationContext reactContext;
      
          KountModule(ReactApplicationContext context) {
              super(context);
              reactContext = context;
          }
      
          @ReactMethod
          public void collect() {
              AnalyticsCollector.collectDeviceDataForSession(reactContext);
          }
      
          @NonNull
          @Override
          public String getName() {
              return "KOUNT_MODULE";
          }
        }
        
  4. Register the Module: To add your Native Module to ReactPackage, first create a new Java Class named KountModulePackage.java that implements ReactPackage inside the android/app/src/main/java/com/your-app-name/ folder:
    Then add the following content:
        import androidx.annotation.NonNull;
    
        import com.facebook.react.ReactPackage;
        import com.facebook.react.bridge.NativeModule;
        import com.facebook.react.bridge.ReactApplicationContext;
        import com.facebook.react.uimanager.ViewManager;
        
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.List;
        
        public class KountModulePackage implements ReactPackage {
          @NonNull
          @Override
          public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
            List<NativeModule> modules = new ArrayList<>();
            modules.add(new KountModule(reactContext));
            return modules;
          }
        
          @NonNull
          @Override
          public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
              return Collections.emptyList();
          }
        }
        
  5. Open up your MainApplication.java file, which can be found in the following path: android/app/src/main/java/com/your-app-name/MainApplication.java and Locate ReactNativeHost’s getPackages() method and add your package to the packages list like below:
        @Override
        protected List<ReactPackage> getPackages() { 
         @SuppressWarnings("UnnecessaryLocalVariable")   
         List<ReactPackage> packages = new PackageList(this).getPackages();  
         packages.add(new KountModulePackage()); 
         return packages;
        }
        
  6. Create a JavaScript wrapper for the module.
    1. Create a new JavaScript file named KountModule.js in your project root folder with the following content:
            import { NativeModules } from "react-native";
            const {KOUNT_MODULE}=NativeModules;
            export default KOUNT_MODULE;
            

Platform Selection Integration in React Native App

Once both the Android and iOS portions of the SDK are set up, you can add the component to the React Native App.

  1. In the React Native application, go to App.js and write the following code snippet. This sample code snippets shows how to call native SDK methods based on application platform.
  2. Importing Native Modules
        import React from 'react';
        import { Text, View, NativeModules, Platform } from 'react-native';
        import KOUNT_MODULE from './KountModule';
        import { Button } from 'react-native';
        import { Component } from 'react';
        
        const {KountBridgeModule} =  NativeModules;
        
  3. Below are the examples of how to call the Kount methods based on platforms. Below methods are the onPress events of buttons.
        export default class App extends Component {
        
        /Platform specific code
        onPressCollect = () => {
          if (Platform.OS == 'ios') {
              console.log("Started");
              KountBridgeModule.collect();
          } else if (Platform.OS == 'android') {
              KOUNT_MODULE.collect();
          }
        }
         render() {
            return (
            <View style={{paddingTop: 50}}>
            <Button title="Collect" onPress={ this.onPressCollect} />
            </View>
            )
          }
        
        }
        
  4. Run react native app and it should capture the data points for device data collector and device fingerprinting data collector in both iOS and Android Platforms.
Was this article helpful?
0 out of 1 found this helpful