How can we help?

React Native SDK

Overview

Our React Native SDK enables you to integrate Cordial into your iOS and Android applications built with React Native. This lets you utilize Cordial's powerful functionality for push notifications, deep links, analytics, and inbox messages in your React Native iOS and Android apps. React Native’s hybrid framework means developers can code an app only once and easily maintain it for both iOS and Android.

We support React Native apps starting from v.0.68 and work to guarantee support for all the latest versions.

Initial setup

Adding Cordial's React Native SDK to your project involves these overall steps:

1. Add @cordialinc/react-native-sdk npm package to your project.

2. Configure the SDK in your React Native iOS app.

3. Configure the SDK in your React Native Android app.

4. Request push notification permission from React Native.

5. Validate the React Native SDK installation.

Add the Cordial React Native SDK to your project

You can add the Cordial React Native SDK beta via npm:

npm install @cordialinc/react-native-sdk  

Or yarn:

yarn add @cordialinc/react-native-sdk  

iOS

In addition to adding a dependency via npm or yarn in an iOS app, update your Podfile using one of these two methods:

1. For React Native apps using the previous architecture, add these two lines at the top of your Podfile (typically the file path is App/iOS/Podfile).

pod 'CordialSDK', :git => 'https://gitlab.com/cordialinc/mobile-sdk/ios-sdk.git',   
:branch => 'static_framework'
pod 'RTNCordialSDK', :path => '../node_modules/@cordialinc/react-native-sdk'

2. For React Native apps using the New Architecture, add this line at the top of your Podfile:

pod 'CordialSDK', :git => 'https://gitlab.com/cordialinc/mobile-sdk/ios-sdk.git',   
:branch => 'static_framework'

Configure the SDK in React Native Android app

1. Add google-services.json from your Firebase project to your Android project.

2. In your MainApplication.onCreate method, add the following SDK initialization code.

String accountKey = "your_account_key";  
String channelKey = "your_channel_key";
String eventsStreamUrl = "your_events_stream_service_url";
String messageHubUrl = "your_message_hub_url";

CordialApiConfiguration config = CordialApiConfiguration.getInstance();

config.setPushesConfiguration(PushesConfiguration.SDK);
config.initialize(this, accountKey, channelKey, eventsSreamUrl, messageHubUrl);

To learn about additional Android-specific configuration options, such as setting push notifications icon silhouettes, visit our Native Android SDK docs.  

Configure the SDK in React Native iOS app

In your AppDelegate.mm file, add the SDK initialization code.

NSString *accountKey = @ "your_account_key";  
NSString *channelKey = @ "your_channel_key";
NSString *eventsStreamURL = @"your_events_stream_service_url";
NSString *messageHubURL = @"your_message_hub_service_url";
[[[CordialApiConfiguration shared] loggerManager] setLoggerLevel:LoggerLevelAll];
[[CordialApiConfiguration shared] initializeWithAccountKey:accountKey
channelKey:channelKey eventsStreamURL:eventsStreamURL messageHubURL:messageHubURL];

[CordialApiConfiguration shared].cordialDeepLinksDelegate="[[RTNDeepLinksHandler"
alloc] init];

For additional iOS-specific configuration options, such as extending your code to display images in push notifications, visit our Native iOS SDK docs.

Request push notification permission

To request a push notification permission, invoke this code from your JavaScript/TypeScript:

CordialSDK.requestPushNotificationsPermission({ 
  alert: true
  sound: true
});

This method accepts an object with the following fields. The fields align with iOS push permission options and have no effect on Android:

  • alert
  • badge
  • sound
  • provisional

If a field is not present, it’s false by default.

Validate React Native SDK installation

To validate that you installed and initialized the React Native SDK correctly, follow these steps.

iOS

1. Run your app in Xcode.

2. Minimize and open your app.

3. Visit the logs in Xcode containing entries and validate that the crdl_app_open and crdl_app_close events have been sent.

4. In Cordial admin, you'll see a new contact created with the generated device ID GUID to search for the contact inside Cordial.

Android

1. Run your app in Android Studio.

2. Minimize and open your app.

3. Visit the logs in Android Studio containing entries and validate that the crdl_app_open and crdl_app_close events have been sent.

4. In Cordial admin, you'll see a new contact created with the generated device ID GUID to search for the contact inside Cordial.

Push notifications

After the React Native SDK is installed, your app is already capable of receiving push notifications. To verify, you can find your contact and send a push notification to them.

Associate a secondary key (such as email)

Android

After the config.initialize call, add this line to associate the device with a secondary key such as:

new CordialAPI().setContact("email:androidcontact@email.com");  

iOS

After the [CordialApiConfiguration shared] initializeWithAccountKey call, add this line to associate the device with a secondary key such as email:

CordialAPI *cordialAPI = [[CordialAPI alloc] init]:
[cordialAPI setContactWithPrimaryKey: @"email:ioscontact@email.com"];

Send a test push notification

1. To send a test push notification to androidcontact@email.com and ioscontact@email.com, follow the steps described in this article.

2. After you’ve sent the push notification test message, you'll see it displayed on the device.

There are multiple ways for users to click deep links:

  • Tap on a push notification with a deep link
  • Tap on a deep link outside of the app (such as an email)
  • Tap on inbox or in-app message.

To set up deep links, make sure to follow initial set up and Push notifications sections above. 

The goal of setting up deep links is to get a callback in your JavaScript/TypeScript app to be invoked when a user clicks on a deep link:

CordialSDK.setDeepLinkListener((event) => { 
   // use event.deepLinkURL or event.fallbackURL
});

Setting up deep links involves configuring the Android app, iOS app, and React Native app (JavaScript or TypeScript).

Deep links for Android

Before using the CordialApiConfiguration.intiailize method, add the following code:

CordialApiConfiguration.getInstance().setNotificationClickActivity(MainActivity.class);

ReactInstanceManager reactInstanceManager = getReactNativeHost().getReactInstanceManager();
config.setDeepLinkListener(new ReactNativeDeepLinkListener(reactInstanceManager));
config.setPushNotificationListener(new
ReactNativePushNotificationListener(appContext));

This code passes MainActivity class to the SDK, which enables the SDK to determine which activity to launch when a push notification is tapped.

In AndroidMainifest.xml, configure MainActivity to open deep links from your domain:

<activity android:name=".MainActivity" /* other elements */> 
...
<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="yourdomain.com"
          android:pathpattern=" /.*" />
  </intent-filter>
</activity>

In MainActivity send notification clicked broadcasts from onCreate and onNewIntent methods:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
new ActivityBroadcastSender().sendNotificationClickedBroadcast(this, getIntent().getExtras(), true); } @Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent); setIntent(intent);
new ActivityBroadcastSender().sendNotificationClickedBroadcast(this, intent.getExtras(), false); }

After calling initializeWithAccountKey, add the following code:

[CordialApiConfiguration shared].cordialDeepLinksDelegate = [[RTNDeepLinksHandler 
alloc] init];

[CordialApiConfiguration shared].deepLinksConfiguration =
CordialDeepLinksConfigurationTypeAPP;

To import RTNDeepLinksHandler, use the following import:

#import <RTNCordialSDK/RTNDeepLinksHandler.h> 

Add the application(_:continue:restorationHandler:) and application(_:open:options:) methods to your AppDelegate.mm:

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity
*)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> *
_Nullable))restorationHandler {
return [RCTLinkingManager application:application continueUserActivity:userActivity
restorationHandler:restorationHandler];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
return [RCTLinkingManager application:app openURL:url options:options];
}

Enable React Native to receive deep links

Here is the code that will set up React Native to receive deep links.

This code is for apps built with the old architecture, but a similar approach works for New Architecture apps.

const App = () => {  
  useEffect(() => {
      CordialSDK.setDeepLinkListener((event) => {
          // this is where you will receive event.deepLinkURL and event.fallbackURL
      });

      CordialSDK.processPushNotificationDeepLink();

      const url = await Linking.getInitialURL();
      CordialSDK.processDeepLink(url);

      Linking.addEventListener('url', ({ url }) => {
       CordialSDK.processDeepLink(url);
      });
}, []);

Analytics

This section describes how to invoke the following methods in the Cordial React Native SDK using JavaScript/TypeScript:

setContact

To associate a contact with the device, use the setContact method.

CordialSDK.setContact('email:contact@email.com');  

unsetContact

When a contact logs out of your app, use unsetContact if you want to remove the current device from the current contact.

CordialSDK.unsetContact(); 

upsertContact

To update a contact’s attributes, use upsertContact.

CordialSDK.upsertContact{
name: "John",
  age: 25,
  birthday: "1995-12-12",
  lastPurchase: new Date (2023, 11, 17, 3, 24, 0),
  tags: ["email", "sms"],
  shippingaddress: {="{"
      city: "Los_Angeles",
      country: "USA",
      postal_code: "90001",
      state: "California",
      street_address: "street_address",
      street_address2: "street_address2",
      tz: "America/Los_Angeles"
  }
});

In the above payload, each field is an attribute. The following attributes are supported:

  • String 
  • Numeric
  • Date
  • Array
  • Geo

sendCustomEvent

To send a custom event, use the sendCustomEvent method.

CordialSDK.sendCustomEvent('customEventName', {  
  name: "Doe",
  age: 30,
  birthday: "2000-01-01",
  lastPurchase: new Date (2020, 11, 17, 3, 24, 0),
  interests: ["work", "study"],
  shippingaddress: {
        city: "Los_Angeles",
        country: "USA",
        postal_code: "90001",
        state: "California",
        street_address: "street_address",
        street_address2: "street_address2",
        tz: "America/Los_Angeles"
  }
});

The first argument is the event name, the second argument is an object where each field is a property that gets stored with the event. The following property types are supported:

  • String
  • Numeric
  • Date
  • Array
  • Nested objects containing any of the above types

upsertContactCart

To update the current contact’s cart, use the upsertContactCart method.

CordialSDK.upsertContactCart([
  {
      productID: "1",
      name: "The Cotton Crew",
      sku: "ab26ec3a-6110-11e9-8647-d663bd873d93",
      category: "Mens",
      qty: 1,
      itemPrice: 30,
      salePrice: 30,
      images: [
         "https://i.imgur.com/XlboRqm.png"
      ]
  },
  {
       productID: "2",
       name: "The Basic Shirt",
       sku: "ab26efdc-6110-11e9-8647-d663bd873d93",
       category: "Mens",
       qty: 1,
       itemPrice: 45,
       salePrice: 45,
       images: [
           "https://i.imgur.com/vsv5Ay9.png"
       ]
  }
]);

The method accepts an array of cart items.

sendContactOrder

To send an order for the current contact, use the sendContactOrder method:

CordialSDK.sendContactOrder({
  orderID: "22DDF8F2-A8CF-4259-ABD6-02E801C335AC",
  status: "orderStatus",
  storeID: "storeID",
  customerID: "customerID",
  purchaseDate: "2024-03-27T10:45:09.032Z",
  shippingAddress: {
      name: "shippingAddressName",
      address: "shippingAddress",
      city: "shippingAddressCity",
      state: "shippingAddressState",
      postalCode: "shippingAddressPostalCode",
      country: "shippingAddressCountry"
  },
  billingAddress: {
      name: "billingAddressName",
      address: "billingAddress",
      city: "billingAddressCity",
      state: "billingAddressState",
      postalCode: "billingAddressPostalCode",
      country: "billingAddressCountry"
  },
  items: [
      {
          productID: "2",
          name: "The Basic Shirt",
          sku: "ab26efdc-6110-11e9-8647-d663bd873d93",
          category: "Mens",
          qty: 1,
          itemPrice: 45,
          salePrice: 45,
          images: [
             "https://i.imgur.com/vsv5Ay9.png"
          ]
      }
  ]
});

Inbox messages

Use CordialSDK.inbox to access inbox messages from your app. This the entry point for all inbox messages. The API supports the following operations.

Fetch all inbox messages for a currently logged in contact

CordialSDK.inbox.fetchInboxMessages(
     {
      page: 1 ,
      size: 10
     }, {
      isRead: 'none' // or 'yes' or 'no'
     },
     (inboxPage) => {

     },
     (error) => {

     }
   );

The parameters for the method are: page number, page size, and a flag indicating whether the messages to be returned are read.

If a successful response is returned, the InboxPage object contains a paginated list of inbox messages. The content property of the InboxPage object is an array of InboxMessage objects. Each InboxMessage represents a single inbox message, containing its mcID, metadata, read status, and the timestamp of when it was sent.

The metadata is a special field that's populated in the admin panel when creating the message content. It's specific to each message and should contain the data to be used when a page of inbox messages is loaded. For example, it may include an image thumbnail, title, and subtitle to generate a preview without loading the full message content.

Fetch inbox message content

To get the full inbox message content, call:

CordialSDK.inbox.fetchInboxMessageContent(this.mcID,  
(response) => {

      },
      (error) => {

      }
    );

Set up an inbox message is read event

This method should be called to signal that a message is read by the user and should be triggered every time a contact reads (or opens) a message.

CordialSDK.inbox.sendInboxMessageReadEvent(this.mcID); 

Mark messages as read

This operation marks a message as read or unread, which toggles the isRead flag on the corresponding InboxMessage object. To mark messages as read:   

CordialSDK.inbox.markInboxMessagesRead(["mcid value1", "mcid value2" ]);  

Mark messages as unread

CordialSDK.inbox.markInboxMessagesRead(["mcid value1", "mcid value2"]);  

Delete an inbox message

CordialSDK.inbox.deleteInboxMessage(this.mcID);  

Receive a notification about new incoming inbox message

CordialSDK.inbox.setNewInboxMessageListener((mcID) = {
    console.log('New inbox message has been received. mcID: ' + mcID);
});

Additional operations

Get current device id

const deviceId = await CordialSDK.getDeviceID();

Get current mcid

const mcid = await CordialSDK.getCurrentMcID();

Set current mcid

CordialSDK.setCurrentMcID("example.mcid");

Switch to in-app delayedShow mode

CordialSDK.inApp.delayedShow();

Switch to in-app show mode

CordialSDK.inApp.show(CordialSDK.inApp.delayType.immediately);

// or

CordialSDK.inApp.show(CordialSDK.inApp.delayType.nexAppOpen);

Changelog

You can find the latest updates to the React Native SDK in the changelog.

Comments

0 comments

Please sign in to leave a comment.