Skip to content
Eduardo Zatoni edited this page Oct 19, 2020 · 46 revisions

Contents

Usage

import EmarsysWrapper 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

It should be done in didFinishLaunchingWithOptions in AppDelegate.

EMSConfig *config = [EMSConfig makeWithBuilder:^(EMSConfigBuilder * builder) {
  [builder setMobileEngageApplicationCode:@"EMSXX-XXXXX"]; // your application code
  [builder setContactFieldId:@0000000000]; // contact identifier field ID
  [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:2.5.4"
}

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.EmarsysMessagingService">
  <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)
	.mobileEngageApplicationCode("EMSAA-00000") // your application code
	.contactFieldId(0000000000) // contact identifier field ID
	.predictMerchantId("XXXXXXXXXXXXX") // predict merchant ID
	.build();
  Emarsys.setup(config);
  createNotificationChannels();
}

2. Set Contact

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

async setContact() {
	let contactFieldValue = "[email protected]";
	try {
		let result = await EmarsysWrapper.setContact(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 EmarsysWrapper.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 EmarsysWrapper.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];
  
  RNEmarsysEventHandler *rnEMSEventHandler = [RNEmarsysEventHandler allocWithZone: nil];
  Emarsys.inApp.eventHandler = rnEMSEventHandler;
  Emarsys.notificationCenterDelegate.eventHandler = rnEMSEventHandler;
  UNUserNotificationCenter.currentNotificationCenter.delegate = Emarsys.notificationCenterDelegate;

  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
  RNEmarsysEventHandler eventHandler = RNEmarsysEventHandler.getInstance();
  Emarsys.getInApp().setEventHandler(eventHandler);
  Emarsys.getPush().setNotificationEventHandler(eventHandler);
}

setEventHandler

Add setEventHandler to your App.js constructor.

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

5. 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

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.

async setPushToken() {
	let pushToken = "custom-push-token";
	try {
		let result = await EmarsysWrapper.setPushToken( pushToken );
	} catch (e) {
		console.log(e);
	}
}

2. Clear Push Token

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

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

3. Track Message Open

The Emarsys SDK automatically handles whether the push messages have been opened, however, if you want to track it manually the trackMessageOpen method should be used, where the messageId parameter is required.

async trackMessageOpen() {
	let messageId = "push-message-ID";

	try {
		let result = await EmarsysWrapper.trackMessageOpen( messageId );
	} 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 EmarsysWrapper.pause();
	} catch (e) {
		console.log(e);
	}
}

2. Resume

In order to show inApp messages after being paused, use the resume method.

async resume() {
	try {
		let result = await EmarsysWrapper.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 EmarsysWrapper.trackCart(cartItems);
	} catch (e) {
		console.log(e);
	}
}

When you want to track empty basket.

async trackEmptyCart() {
	let emptyCartItems = [];

	try {
		let result = await EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.recommendProducts(logic);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsQuery() {
	let logic = "POPULAR";
	let query = "Shoes>Pump";

	try {
		let result = await EmarsysWrapper.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 EmarsysWrapper.recommendProductsCartItems(logic, cartItems);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsLimit() {
	let logic = "RELATED";
	let limit = 1;

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

	try {
		let result = await EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.recommendProductsCartItemsFilters(logic, cartItems, filters);
	} catch (e) {
		console.log(e);
	}
}
async recommendProductsLimitFilters() {
	let logic = "POPULAR";
	let limit = 5;
	let filters = {};

	try {
		let result = await EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.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 applicationCodeChange = "applicationCode";

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

2. Change MerchantId

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

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

3. Get ApplicationCode

Provides what is the actual applicationCode set in the SDK.

async getApplicationCode() {
	try {
		let applicationCode = await EmarsysWrapper.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 EmarsysWrapper.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 EmarsysWrapper.getContactFieldId();
	} catch (e) {
		console.log(e);
	}
}
Clone this wiki locally