Logical Getting Started

React Native API Integration

Overview

The ReferralHero API is organized around REST. Our API has predictable, resource-oriented URLs. JSON is returned by all API responses, including errors.

1. Get Your ReferralHero Keys & Token

  1. API Token: Retrieve your API_TOKEN from the ReferralHero Dashboard by navigating to -> API: ReferralHero Dashboard.

  1. Branch.io Credentials:

    • If you already have a Branch.io account, keep your credentials ready.

    • If not, no worries — we’ll set it up for you.

      • Once you configure your referral tracking campaign and enable Mobile Apps:

        • We’ll email you and provide the credentials required for setup:

          • branch_key

          • branch_universal_link_domains

If you don’t receive the email, please contact ReferralHero Support at support@referralhero.com


2. Install Dependencies

  • Using NPM

    npm install axios
    npm install react-native-branch
  • Using yarn

    yarn add axios
    yarn add react-native-branch

3. Configure App

📱 iOS Configuration

  1. Bundle Identifier Ensure that the Apple Bundle ID in Xcode matches the one configured in the Branch.io dashboard.

    If you’ve already received your Branch.io credentials from us (as outlined in Step 1), you’ll find the correct Bundle Identifier listed there. Make sure it matches the Bundle ID set for your target in Xcode:

  2. Associated Domains

    In the Branch dashboard, you’ll find your Link Domains.

    If you’ve received credentials from us (see Step 1), your branch_universal_link_domains value will include the required subdomain.

    To configure:

    1. In Xcode, go to Target → Signing & Capabilities.

    2. Add a new Associated Domains entry using the following format:

    applinks:your-subdomain.app.link
  3. Info.plist Configuration Referralhero requires specific key/value pairs to be added to your project's Info.plist file:

    • branch_universal_link_domains: Specifies the associated domains your app will support for universal links.

    • branch_key: Your Branch live key (you can also include a test key for development purposes).

    • CFBundleURLTypes: Defines your app’s URL schemes and identifiers, allowing ReferralHero to correctly handle app openings via universal links.

    Add the following to your Info.plist:

    <key>branch_key</key>
    <string>key_test_kyqc*****************</string>
    
    <key>branch_universal_link_domains</key>
    <array>
      <string>i2koh.test-app.link</string>
      <string>i2koh-alternate.test-app.link</string>
    </array>
    
    <key>CFBundleURLTypes</key>
    <array>
      <dict>
        <key>CFBundleURLSchemes</key>
        <array>
          <string>app_name</string>
        </array>
      </dict>
    </array>
  4. AppDelegate.swift Setup In your AppDelegate.swift, add:

    import RNBranch
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Optional: Uncomment next line to use test instead of live key
        // RNBranch.useTestInstance()
        RNBranch.initSession(launchOptions: launchOptions)
    
        return true
      }
    
      func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        RNBranch.application(app, open:url, options:options)
        return true
      }
    
      func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        RNBranch.continue(userActivity)
        return true
      }
    }

🤖 Android Configuration

  1. AndroidManifest.xml Add the following inside the <application> tag:

    <meta-data
      android:name="io.branch.sdk.BranchKey"
      android:value="key_test_kyqc*****************" />
    <meta-data
      android:name="io.branch.sdk.TestMode"
      android:value="true" />
    
    <activity android:name=".MainActivity" ...>
      <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" android:host="i2koh.test-app.link" />
      </intent-filter>
    </activity>
  2. MainActivity.kt

    import io.branch.rnbranch.*
    import android.os.Bundle
    import android.content.Intent
    
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      RNBranchModule.initSession(intent?.data, this)
    }
    
    override fun onNewIntent(intent: Intent?) {
      super.onNewIntent(intent)
      setIntent(intent)
      RNBranchModule.reInitSession(this)
    }
  3. MainApplication.kt

    import io.branch.rnbranch.RNBranchModule
    import io.branch.rnbranch.RNBranchPackage
    
    override fun onCreate() {
      super.onCreate()
      RNBranchModule.getAutoInstance(this)
    }
    
    override fun getPackages(): List<ReactPackage> {
      return listOf(
        ...,
        RNBranchPackage()
      )
    }

Add the following in your app’s entry point (e.g., App.js):

import React, { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import branch from 'react-native-branch';

function App() {
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = branch.subscribe(({ error, params }) => {
      if (error) {
        console.error('Branch error:', error);
        return;
      }

      if (params['+clicked_branch_link']) {
        const visitorId = params['visitor_id'];
        const referralCode = params['referral_code'];

        if (visitorId) {
          AsyncStorage.setItem("visitor_id", visitorId);
        }
        if (referralCode) {
          AsyncStorage.setItem("referral_code", referralCode);
        }
      }
    });

    checkLoginStatus();
    return () => unsubscribe();
  }, []);

  const checkLoginStatus = async () => {
    try {
      const token = await AsyncStorage.getItem("loggedIn");
      // your login logic
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) return null;

  return (
    // your navigation container or main view
  );
}

export default App;

You can now use the visitor_id and referral_code from the link when calling ReferralHero APIs during user registration and start tracking referrals!

For that, you will need 2 things:

  1. Universal Link

  2. Your Integrated App

The RH SDK Pulls information from your Device, like this:

final referralParams = {
  'email': 'user@example.com', // Capture this from user
  'hosting_url': 'https://a.domain.co/', // Optional value, and set as default by admin
  'name': 'User Name', // Capture this from user
  'referrer': 'referrerCode', // Optional value, Get from the deep link as referral_code. only necessary if you want to capture the referrer code from user
  'uuid': 'MFcd4113d4bf', // Get this from RH Dashboard
  'device': getDeviceType(), // Get device type
  'os_type': getOperatingSystem(), // Get operating system type
  'visitor_id': sub_********, // Get this from the deep link params
  'status': 'custom_event_pending' //Use 'custom_event_pending' to set the referral status to pending
};

5. Getting started with API

Base URL: Calls for ReferralHero API are relative to the URL

https://app.referralhero.com/api/sdk/v1/

Request Headers

  1. Authorization - Your access token

  2. Accept - application/vnd.referralhero.v1

  3. Content-Type - application/json

To summarize, your request headers should look like this

{ 
  'Content-Type': 'application/json',
  'Accept': 'application/vnd.referralhero.v1',
  'Authorization': 'xxxxxxxxxx'
}

Step 1: Set Up Your Project

  1. Open your React Native project.

  2. Install a library for making HTTP requests, such as axios or use the built-in fetch API.

Step 2: Make Your First API Call

  1. Import your HTTP library:

import axios from 'axios';
  1. Set up your API call:

const apiUrl = 'https://app.referralhero.com/api/sdk/v1/';
const apiToken = 'Your-api-token';

axios.get(`${apiUrl}endpoint`, {
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/vnd.referralhero.v1',
    'Authorization': apiToken
  }
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Error making API call', error);
});

Step 3:

  1. On the ReferralHero overview, click to edit your desired Campaign.

  2. Then the Installation tab, then Mobile App Installation.

  3. Get your UUID: The 12-letter ID that starts with ‘MF’ in Edit Campaign > launch > Mobile app installation, e.g. MF15298bba6d.

  4. Add the Campaign Token obtained from the campaign, and UUID from the installation Tab.

Step 4:

In the Goal section of your Campaign settings, ensure you have added the Google Play and Apple App Store links and a default referral link for desktop web users.

Well done! You should now be able to build and run your campaign. Before using the more advanced features of the API, you should learn about a couple of important concepts.

Helper Functions

Get Device Type

You can use the react-native-device-info library to get the device type.

import DeviceInfo from 'react-native-device-info';

function getDeviceType() { 
  let deviceType = "Desktop";
  if (Platform.OS === 'ios') 
    { if (DeviceInfo.getModel().toLowerCase().includes("ipad")) { 
      deviceType = "iPad"; 
    } else if (DeviceInfo.getModel().toLowerCase().includes("ipod")) {
       deviceType = "iPod"; 
    } else { deviceType = "iPhone"; } 
  } else if (Platform.OS === 'android') { 
    deviceType = "Android"; 
  } else if (Platform.OS === 'windows') { 
    deviceType = "Windows Phone"; 
  } else if (Platform.OS === 'blackberry') {
     deviceType = "BlackBerry"; 
  } else { 
    deviceType = "Unknown Device";
  } 
  return deviceType; 
}

Get Operating System

You can use the Platform module from React Native to get the operating system type.

import { Platform } from 'react-native';

function getOperatingSystem() {
  return Platform.OS; // Returns 'ios' or 'android'
}

Adding the Subscriber Data

With this information, you should be able to add the subscriber data using the addSubscriber method to automatically identify or track a referral:

function formSubmit() {
  axios.post(`https://app.referralhero.com/api/sdk/v1/lists/MFxxxxxxxxx/subscribers`, referralParams, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/vnd.referralhero.v1',
      'Authorization': apiToken
    }
  })
  .then(response => {
    console.log('Subscriber added successfully:', response.data);
  })
  .catch(error => {
    console.error('Error adding subscriber', error);
  });
}

6. Embedding ReferralHero Widget in React Native WebView

1. Identify the Subscriber Using the API

To begin, call the Add Subscriber Endpoint using the following endpoint:

Endpoint: https://app.referralhero.com/api/sdk/v1/lists/UUID/subscribers

Send the necessary mobile parameters and subscriber details. The API response will include a subscriber ID, which is required for authentication. It is crucial to store the subscriber ID securely as it will be used for future authentication. Make sure that the API call is handled properly and errors are logged for debugging.

2. Set Authentication Cookies in the WebView

Before loading the widget, ensure the WebView injects the subscriber ID as a cookie. These cookies allow the widget to automatically recognize the user without requiring manual authentication. This step helps in reducing friction for users, enabling a smoother experience without the need for repeated logins.

3. Embed the Widget Inside a WebView

The RH-hosted page, containing the widget, should be loaded within a WebView inside the React Native app. This ensures that the widget functions exactly as it does in a standard browser environment. Additionally, ensure that WebView settings allow JavaScript execution and storage access, which is necessary for proper widget functionality.

4. Auto-Redirect to the Share Screen

Once the widget detects the authentication cookies, it will bypass the login screen and directly load the share screen. This creates a seamless user experience, similar to accessing the widget from a logged-in web browser.

To further enhance user experience, consider adding loading indicators while the WebView is initializing to inform users of ongoing processes.

Implementation

import React, { useEffect, useState, useRef } from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { WebView } from 'react-native-webview';
import AsyncStorage from '@react-native-async-storage/async-storage';

const ReferralWidget = () => {
  const webViewRef = useRef(null);
  const [injectedJS, setInjectedJS] = useState('');

  useEffect(() => {
    const fetchId = async () => {
      const id = await AsyncStorage.getItem("id");
      if (id) {
        const script = `
          document.cookie = "__maitre-anonymous-MFxxxxxxxxx=${id}; path=/; max-age=86400";
          document.cookie = "__maitre-session-MFxxxxxxxxx=${id}; path=/; max-age=86400";
          window.ReactNativeWebView.postMessage(document.cookie);
        `;
        setInjectedJS(script);
      }
    };
    fetchId();
  }, []);

  const handleMessage = (event) => {
    //Alert.alert("Cookies", event.nativeEvent.data);
  };

  return (
    <View style={styles.container}>
      {injectedJS ? (
        <WebView 
          ref={webViewRef}
          source={{ uri: 'https://campaign.referralhero.com/MFxxxxxxxx/dashboard' }}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          startInLoadingState={true} 
          onLoadEnd={() => console.log("WebView Loaded Successfully")}
          injectedJavaScript={injectedJS}
          onMessage={handleMessage}
        />
      ) : null}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  }
});

export default ReferralWidget;

This implementation ensures that the subscriber authentication process is seamless, automatically logging users into the referral widget inside the React Native WebView.

Last updated