Skip to content
Eduardo Zatoni edited this page Aug 23, 2022 · 46 revisions

Contents

Usage

import Emarsys from "react-native-emarsys-wrapper";

Initialization

1. Init

Emarsys setup should be implemented nativity to ensure setup method is the first thing to be called.

Please, follow the steps on the EmarsysSDK documentation to install the SDK in your iOS project.

iOS

⚠️ If you are using RN version 0.62 or higher: Make sure to place Emarsys imports outside #ifdef FB_SONARKIT_ENABLED condition!

#import <EmarsysSDK/Emarsys.h>
#import <EmarsysSDK/EMSConfig.h>
#import <RNEmarsysWrapper/RNEmarsysEventHandler.h>

The SDK initialisation should be done in didFinishLaunchingWithOptions in AppDelegate.

EMSConfig *config = [EMSConfig makeWithBuilder:^(EMSConfigBuilder * builder) {
  [builder setMobileEngageApplicationCode:@"EMSXX-XXXXX"]; // your application code
  [builder setMerchantId:@"XXXXXXXXXXXXX"];  // predict merchant ID
}];
[Emarsys setupWithConfig:config];

Android

Firebase

Follow Google's instructions to add the Google Play Services gradle plugin to your project: https://developers.google.com/android/guides/google-services-plugin

In order for push notifications to work, you need to obtain Firebase Cloud Messaging credentials for your app. Follow the instruction for the native SDK here: https://github.com/emartech/android-emarsys-sdk/wiki/Obtaining-Firebase-Cloud-Messaging-credentials, then copy the google-services.json file to the android/app directory of your React Native project.

Emarsys SDK dependency

For the SDK initialization to work, an Emarsys SDK version corresponding to the one used by the wrapper has to be added to the Android project as a dependency. In the dependencies section of the android/app/build.gradle, add:

dependencies {
	implementation "com.emarsys:emarsys-sdk:‹emarsys-sdk_version_used_by_wrapper›"
        implementation "com.emarsys:emarsys-firebase:‹emarsys-sdk_version_used_by_wrapper›"
}

Messaging service

When the push token arrives from Firebase, we need to set it using Emarsys.push.setPushToken(). The recommended way of using the Android SDK is to enable the SDK to automatically handle setPushToken and trackMessageOpen calls for you, please register the service in your android/app/AndroidManifest.xml file.

        <service android:name="com.emarsys.service.EmarsysFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

Additionally, you can set a custom notification icon, by specifying it as a meta-data in your application tag:

<meta-data
android:name="com.emarsys.mobileengage.small_notification_icon"
android:resource="@drawable/notification_icon"
>

For receiving push notifications in the background to work, the SDK has to be initialised in the onCreate method of the MainApplication.java file.

public void onCreate() {
  super.onCreate();
  SoLoader.init(this, /* native exopackage */ false);
  EmarsysConfig config = new EmarsysConfig.Builder()
            .application(this)
            .applicationCode("EMSAA-00000") // your application code
            .merchantId("XXXXXXXXXXXXX") // predict merchant ID
            .enableVerboseConsoleLogging()
            .build();
  Emarsys.setup(config);
  createNotificationChannels();
}

2. Set Contact

The setContactFieldId should not be set to 3 (email). In order to prevent your customers' personal data (PII) being stored in our cloud infrastructure, we require use of unique, non-guessable and immutable contact identifiers. Customer ID's are considered secure. Salted email hash is no longer supported for new Mobile Engage implementations. To make sure the behavioural tracking is cross devices (i.e. mobile and web), the Web Extend contact ID should also use Customer ID and match that used on mobile.

After the application setup is finished, you can use setContact method to identify the user with contactFieldId and contactFieldValue. Without setContact all events will be tracked as anonymous usage.

async setContact() {
  let contactFieldId = 100010824;
  let contactFieldValue = "7c3df9f3";

  try {
    let result = await Emarsys.setContact(contactFieldId, contactFieldValue);
  } catch (e) {
    console.log(e);
  }
}

3. Clear Contact

When the user signs out, we should use the clearContact method. The method is going to automatically log in an anonymous user instead of the one leaving.

Note

No need to call clearContact every time, even if the user isn't logged in. Just make sure it is called when the user logs out of the application.

async clearContact() {
  try {
    let result = await Emarsys.clearContact();
  } catch (e) {
    console.log(e);
  }
}

4. Track Custom Event

If you want to track custom events, the trackCustomEvent method should be used, where the eventName parameter is required, but the eventAttributes are optional.

async trackCustomEvent() {
  let eventName = "customEventName";
  let eventAttributes = {
    "customEvent-key1": "customEvent-value1",
    "customEvent-key2": "customEvent-value2",
  }
  try {
    let result = await Emarsys.trackCustomEvent(eventName, eventAttributes);
  } catch (e) {
    console.log(e);
  }
}

5. Event Handler

iOS

In order to react to an event triggered by push notification or in-app message, you should add the RNEmarsysEventHandler as the handler of the Emarsys events in the didFinishLaunchingWithOptions method of the AppDelegate.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  //...  
  [Emarsys setupWithConfig:config];
  
  UNUserNotificationCenter.currentNotificationCenter.delegate = [Emarsys push];
  RNEmarsysEventHandler *rnEMSEventHandler = [RNEmarsysEventHandler allocWithZone: nil];
  [rnEMSEventHandler setEventHandlers];

  return YES;
}

Android

In order to react to an event triggered by push notification or in-app message, you should add the RNEmarsysEventHandler as the handler of the Emarsys events in the onCreate method of the MainApplication.java file.

public void onCreate() {
  super.onCreate();
  // ...
  // Has to come after SoLoader.init and after Emarsys set up
  RNEmarsysEventHandler eventHandler = RNEmarsysEventHandler.getInstance();
  eventHandler.setEventHandlers();
}

setEventHandler

Add setEventHandler to your App.js constructor.

constructor() {
  super();
  Emarsys.setEventHandler(function (eventName, payload) {
    showAlert(eventName, JSON.stringify(payload))
  });
}

6. Rich Push Notifications

iOS

Push notification could show media content and action buttons besides the title and body. Push notifications with these types of contents are called Rich Notifications.

  1. Add a new Notification Service Extension target to your project.

  2. Add the EmarsysNotificationService to this target in the Podfile.

target "Emarsys Sample" do
  pod 'EmarsysSDK'
end

target "EMSNotificationService" do
  pod 'EmarsysNotificationService'
end
  1. Install pods with the pod install command in the workspace directory via terminal.

  2. Open the NotificationService.h in the target, then: Import the <EmarsysNotificationService/EMSNotificationService.h>. Extend the class EMSNotificationService instead of UNNotificationServiceExtension.

#import <EmarsysNotificationService/EMSNotificationService.h>

@interface NotificationService : EMSNotificationService

@end

Push

1. Set Push Token

Android

The Emarsys SDK automatically handles setPushToken for the device and it is recommended to leave this to the SDK. However if you have your custom implementation of MessagingService, please use the setPushToken() method, to set the pushToken.

iOS

The pushToken has to be set natively when it arrives in didRegisterForRemoteNotificationsWithDeviceToken in the AppDelegate:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [Emarsys.push setPushToken:deviceToken
               completionBlock:^(NSError *error) {
               }];
}

2. Clear Push Token

If you want to remove pushToken for the Contact, please use clearPushToken() method.

async clearPushToken() {
	try {
		let result = await Emarsys.push.clearPushToken();
	} catch (e) {
		console.log(e);
	}
}

3. Get Push Token

If you want to get the pushToken for the Contact, please use pushToken() method.

async pushToken() {
	try {
		let pushToken = await Emarsys.push.pushToken();
	} catch (e) {
		console.log(e);
	}
}

InApp

1. Pause

When a critical activity starts and should not be interrupted by InApp, use pause to pause InApp messages.

async pause() {
	try {
		let result = await Emarsys.inApp.pause();
	} catch (e) {
		console.log(e);
	}
}

2. Resume

In order to show in-app messages after being paused, use the resume method.

async resume() {
	try {
		let result = await Emarsys.inApp.resume();
	} catch (e) {
		console.log(e);
	}
}

Predict

We won't go into the details to introduce how Predict works, and what its capabilities are, rather we aim to explain the mapping between the Predict commands and our interface. Please visit Predict's documentation for more information.

1. Initialization

To use the Predict functionality you have to setup your merchantId during the initialization of the SDK. In order to track Predict events, you can use the methods available on our Predict interface.

2. Track Cart

When you want to track the cart items in the basket, you can call the trackCart method with a list of CartItems. CartItem is an interface that can be used in your application for your own CartItems and then simply use the same items with the SDK.

async trackCart() {
	let cartItems = [{
		itemId: "cartId-1", 
		price: 1.66, 
		quantity: 26.4, 
	}, {
		itemId: "cartId-2", 
		price: 2.88, 
		quantity: 56.5, 
	}];

	try {
		let result = await Emarsys.predict.trackCart(cartItems);
	} catch (e) {
		console.log(e);
	}
}

When you want to track empty basket.

async trackEmptyCart() {
	let emptyCartItems = [];

	try {
		let result = await Emarsys.predict.trackCart(emptyCartItems)
	} catch (e) {
		console.log(e);
	}
}

3. Track Purchase

To report a purchase event, you should call trackPurchase with the items purchased and with an orderId.

async trackPurchase() {
	let orderId = "TrackPurchase-OrderID";
	let cartItems = [{
		itemId: "cartId-1",
		price: 2.22,
		quantity: 27.56,
	}, {
		itemId: "cartId-2",
		price: 28.11,
		quantity: 5.6,
	}];

	try {
		let result = await Emarsys.predict.trackPurchase(orderId, cartItems);
	} catch (e) {
		console.log(e);
	}
}

To report a purchase event with empty basket.

async trackEmptyPurchase() {
	let emptyOrderId = "TrackPurchase-Empty-OrderID";
	let emptyCartItems = [];

	try {
		let result = await Emarsys.predict.trackPurchase(emptyOrderId, emptyCartItems);
	} catch (e) {
		console.log(e);
	}
}

4. Track Item View

If an item was viewed, use the trackItemView method with an itemId as required parameter.

async trackItemView() {
	let itemId = "TrackItemId";

	try {
		let result = await Emarsys.predict.trackItemView(itemId);
	} catch (e) {
		console.log(e);
	}
}

5. Track Category View

When the user navigates between the categories, you should call trackCategoryView in every navigation. Be aware to send categoryPath in the required format. Please visit Predict's documentation for more information.

async trackCategoryView() {
	let categoryPath = "Bikes > Road Bikes";

	try {
		let result = await Emarsys.predict.trackCategoryView(categoryPath);
	} catch (e) {
		console.log(e);
	}
}

6. Track Search Term

To report search terms entered by the contact, use trackSearchTerm method.

async trackSearchTerm() {
	let searchTerm = "searchTerm";

	try {
		let result = await Emarsys.predict.trackSearchTerm(searchTerm);
	} catch (e) {
		console.log(e);
	}
}

7. Track Tag

To track custom tags, use the trackTag method, where, the eventName parameter is required, but the tagAttributes is optional.

async trackTag() {
	let tagName = "tagName";
	let tagAttributes = {
		"tag-key1": "tag-value1",
		"tag-key2": "tag-value2",
	}

	try {
		let result = await Emarsys.predict.trackTag(tagName, tagAttributes);
	} catch (e) {
		console.log(e);
	}
}

8. Recommended Products

8.1 Logic

With the Emarsys SDK you can ask for product recommendations based on different recommendation logics.

Note

For more information of the recommender logics, please visit documentation.

The currently supported logics are:

  • SEARCH - based on searchTerm
  • CART - based on cartItems
  • RELATED - based on itemViewId
  • CATEGORY - based on categoryPath
  • ALSO_BOUGHT - based on itemViewId
  • POPULAR - based on categoryPath
  • PERSONAL - based on current browsing and activity
  • HOME - based on most recent browsing behaviour

8.2 Query

Query string parameter extends recommended logics.

8.3 Limit

You can limit the number of recommended products received by defining a limit.

8.4 Filters

You can filter product recommendations with the SDK by building RecommendationFilters.

  • type (String)- There are two types of filters: exclude or include.
  • field (String) - This argument extends Type of recommended logics.
  • comparison (String) - In every case there are four types of comparators you can use to compare your chosen field to expectations:
    • is - checking if the field is matching the value.
    • in - any of the values has a match with the field.
    • has - One of the field values is equal to expectation value (applicable only to fields containing multiple values).
    • overlaps - One or more of the field values are found in expectation values (applicable only to fields containing multiple values).
  • expectations - (String/Array of strings) - This argument extends Comparison of recommended logics.
async recommendProducts() {
	let logic = "CATEGORY";

	try {
		let result = await Emarsys.predict.recommendProducts(logic);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsQuery() {
	let logic = "POPULAR";
	let query = "Shoes>Pump";

	try {
		let result = await Emarsys.predict.recommendProductsQuery(logic, query);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsCartItems() {
	let logic = "CART";
	let cartItems = [{
		itemId: "103",
		price: 9.22,
		quantity: 2.4,
	}, {
		itemId: "108",
		price: 89.99,
		quantity: 6.5,
	}];

	try {
		let result = await Emarsys.predict.recommendProductsCartItems(logic, cartItems);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsLimit() {
	let logic = "RELATED";
	let limit = 1;

	try {
		let result = await Emarsys.predict.recommendProductsLimit(logic, limit);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsQueryLimit() {
	let logic = "POPULAR";
	let query = "Shoes>Pump";
	let limit = 2;

	try {
		let result = await Emarsys.predict.recommendProductsQueryLimit(logic, query, limit);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsCartItemsLimit() {
	let logic = "CART";
	let cartItems = [{
		itemId: "103",
		price: 299,
		quantity: 26.4,
	}, {
		itemId: "108",
		price: 289.99,
		quantity: 56.5,
	}];
	let limit = 4;

	try {
		let result = await Emarsys.predict.recommendProductsCartItemsLimit(logic, cartItems, limit);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsFilters() {
	let logic = "POPULAR";
	let filters = {
		type: "include",
		field: "category",
		comparison: "is",
		expectations: "For Women",
	};

	try {
		let result = await Emarsys.predict.recommendProductsFilters(logic, filters);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsQueryFilters() {
	let logic = "CATEGORY";
	let query = "Shoes>Pump";
	let filters = {
		type: "include",
		field: "category",
		comparison: "IN",
		expectations: [ "Shoes>Pump", "For Women>Shoes>Golf"],
	};

	try {
		let result = await Emarsys.predict.recommendProductsQueryFilters(logic, query, filters);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsCartItemsFilters() {
	let logic = "CART";
	let cartItems = [{
		itemId: "103",
		price: 299,
		quantity: 26.4,
	}, {
		itemId: "108",
		price: 289.99,
		quantity: 56.5,
	}];
	let filters = {};

	try {
		let result = await Emarsys.predict.recommendProductsCartItemsFilters(logic, cartItems, filters);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsLimitFilters() {
	let logic = "POPULAR";
	let limit = 5;
	let filters = {};

	try {
		let result = await Emarsys.predict.recommendProductsLimitFilters(logic, limit, filters);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsQueryLimitFilters() {
	let logic = "CATEGORY";
	let query = "Shoes>Pump";
	let limit = 5;
	let filters = {};

	try {
		let result = await Emarsys.predict.recommendProductsQueryLimitFilters(logic, query, limit, filters);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsCartItemsLimitFilters() {
	let logic = "CART";
	let cartItems = [
		{
			itemId: "103",
			price: 299,
			quantity: 26.4,
		},
		{
			itemId: "108",
			price: 289.99,
			quantity: 56.5,
		},
	];
	let limit = 5;
	let filters = {};

	try {
		let result = await Emarsys.predict.recommendProductsCartItemsLimitFilters(logic, cartItems, limit, filters);
	} catch (e) {
		console.log(e);
	}
}

9. Track Recommendation Click

The Emarsys SDK doesn't track automatically recommendationClicks, so you have to call manually trackRecommendationClick when an interaction happens with any of the recommended products.

async trackRecommendationClick() {
	let product = {
		productId: "productId",
		title: "title", 
		linkUrl: "http://linkUrl.com/test",
		feature: "feature",
		cohort: "awesome",
		imageUrl: "http://productURL.com/imageUrl", 
		zoomImageUrl: "http://productURL.com/zoomImageUrl",
		categoryPath: "productCategoryPath",
		productDescription: "productDescription",
		album: "productAlbum",
		actor: "productActor",
		artist: "productArtist",
		author: "productAuthor",
		brand: "productBrand",
		customFields: {
			productTestKey1: "productTestValue1",
			productTestKey2: "productTestValue2",
			productTestKey3: "productTestValue3",
		},
		available: true,
		price: 45.67, 
		msrp: 2.45, 
		year: 2019, 
	};

	try {
		let result = await Emarsys.predict.trackRecommendationClick(product);
	} catch (e) {
		console.log(e);
	}
}

DeepLink

In order to track email link clicks that open the application directly with the Emarsys SDK, you need to call trackDeepLink.

1. Track Deep Link

async trackDeepLink(url) {
	try {
		let result = await Emarsys.trackDeepLink(url);
	} catch (e) {
		console.log(e);
	}
}

ApplicationCode and merchantId change

1. Change ApplicationCode

Emarsys SDK now provides a solution for applicationCode and merchantId change in a convenient way, without restarting the SDK.

async changeApplicationCode() {
	let applicationCode = "applicationCode";

	try {
		let result = await Emarsys.changeApplicationCode(applicationCode);
	} catch (e) {
		console.log(e);
	}
}

2. Change MerchantId

async changeMerchantId() {
	let merchantId = "merchantId";

	try {
		let result = await Emarsys.changeMerchantId(merchantId);
	} catch (e) {
		console.log(e);
	}
}

3. Get ApplicationCode

Provides what is the actual applicationCode set in the SDK.

async getApplicationCode() {
	try {
		let applicationCode = await Emarsys.getApplicationCode();
	} catch (e) {
		console.log(e);
	}
}

4. Get MerchantId

Provides what is the actual merchantId set in the SDK.

async getMerchantId() {
	try {
		let merchantId = await Emarsys.getMerchantId();
	} catch (e) {
		console.log(e);
	}
}

5. Get ContactFieldId

Provides what is the actual contactFieldId set in the SDK.

async getContactFieldId() {
	try {
		let contactFieldId = await Emarsys.getContactFieldId();
	} catch (e) {
		console.log(e);
	}
}

6. Get HardwareId

Provides what is the actual hardwareId set in the SDK.

async getHardwareId() {
	try {
		let hardwareId = await Emarsys.getHardwareId();
	} catch (e) {
		console.log(e);
	}
}

7. Get LanguageCode

Provides what is the actual languageCode set in the SDK.

async getLanguageCode() {
	try {
		let languageCode = await Emarsys.getLanguageCode();
	} catch (e) {
		console.log(e);
	}
}

8. Get SdkVersion

Provides what is the actual sdkVersion in the SDK.

async getSdkVersion() {
	try {
		let sdkVersion = await Emarsys.getSdkVersion();
	} catch (e) {
		console.log(e);
	}
}

Inbox

1. fetchMessages

In order to receive the messageInbox content, you can use the fetchMessages method.

async  fetchMessages() {
	try {
		let  inboxData = await  Emarsys.inbox.fetchMessages()
	} catch (e) {
		console.log(e);
	}
}

2. addTag

To label a message with a tag, you can use addTag method. (for example: "OPENED", "SEEN" etc)

async  addTag() {
	let  tag = "seen"
	let  messageId = "12345"
	try {
		let  result = await  Emarsys.inbox.addTag(tag, messageId)
	} catch (e) {
		console.log(e)
	}
}

3. removeTag

To remove a label from a message, you can use removeTag method.

async  removeTag() {
	let  tag = "seen"
	let  messageId = "12345"
	try {
		let  result = await  Emarsys.inbox.removeTag(tag, messageId)
	} catch (e) {
		console.log(e)
	}
}
Clone this wiki locally