.. _braze_integration: Braze ===== Braze (formerly Appboy) is a marketing automation platform that allows customers to engage with end users via contextual messaging sent at all points throughout the user journey. Braze can be used in conjunction with Apptimize to streamline product releases, A/B tests, messaging and user lifecycle management, and to provide retargeting and re-engagement. Use Cases ^^^^^^^^^ With Braze and Apptimize together, you can leverage both platforms in conjunction to create powerful end-to-end experiences: * Synchronize the in-app and CRM marketing experiences for a custom promotion. * Test a new onboarding experience in Apptimize, and use Braze to nurture users throughout the new flow. * Concurrently test product feature configurations alongside their appropriate user messaging. * Tailor in-app experiences and their appropriate messaging for different segments of end users. How It Works ^^^^^^^^^^^^ Braze and Apptimize can be integrated together to pass data from SDK to SDK. You can sync active Apptimize A/B test groups back to Braze, allowing you to retarget the users in a particular Apptimize test within Braze via push, email, or In-App Messaging. We have sample integration code which demonstrates how the Braze and Apptimize SDKs can pass data to power custom targeting and segmentation in Braze based on Apptimize experiment data. This sample integration will set custom attributes on your users’ Braze User Profiles for the following Apptimize data: * The full list of active experiments that the user is currently enrolled in. * The full list of experiments the user has ever been enrolled in, including completed experiments. * The variant(s) the user has seen as part of an experiment participation. *Note: Feature Flags are considered experiments where the only variant is when the Feature Flag is on. If the Feature Flag is off, no data will be reported.* In addition, this integration will log an Braze Custom Event for the first participation event of an experiment. This can be done in one of two ways: * A custom event is generated with property data denoting the experiment name, the experiment ID, the variant name and the variant ID. * An attribute array is generated with entries for every participation that has occurred. Each participation is formatted as :code:`experiment_id_EXPERIMENT_ID:variant_id_VARIANT_ID:experiment_name_EXPERIMENT_NAME:variant_name_VARIANT_NAME` You can then use Braze’s Action-Based Delivery Campaigns or Canvases to send follow-on messages to users in real-time when these events are triggered. Integration Specifics ^^^^^^^^^^^^^^^^^^^^^ The integration sample code is available for both iOS and Android below. iOS --- In order to integrate with your app, import the Appboy-Apptimize.m and Appboy-Apptimize.h files into your Xcode project, import the Appboy-Apptimize.h header into your AppDelegate implementation and add the following to didFinishLaunchingWithOptions after initializing both Braze and Apptimize: .. code-block:: objective-c [ApptimizeAppboy setupExperimentTracking]; **Appboy-Apptimize.h** .. code-block:: objective-c // Apptimize-Appboy.h #ifndef Apptimize_Appboy_h #define Apptimize_Appboy_h @interface ApptimizeAppboy : NSObject + (void)setupExperimentTracking; @end #endif /* Apptimize_Appboy_h */ **Appboy-Apptimize.m** .. code-block:: objective-c // Apptimize-Appboy.m #import #import "Apptimize-Appboy.h" #import #import #import "Appboy.h" #import "ABKUser.h" // Key to store previous enrollment dictionary to check against to see if enrollment has changed NSString *const ApptimizeAppboyTestEnrollmentStorageKey = @"ApptimizeAppboyTestEnrollmentStorageKey"; @implementation ApptimizeAppboy + (void)setupExperimentTracking { // Track for enrollment changes [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(apptimizeTestsProcessed:) name:ApptimizeTestsProcessedNotification object:nil]; // Track for participation events [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(experimentDidGetViewed:) name:ApptimizeTestRunNotification object:nil]; } + (void)apptimizeTestsProcessed:(NSNotification*)notification { NSLog(@"Appboy-Apptimize integration processing new Apptimize tests"); [self updateForNewTests]; } + (void)updateForNewTests { NSDictionary *savedEnrollmentDictionary = [[NSUserDefaults standardUserDefaults] objectForKey:ApptimizeAppboyTestEnrollmentStorageKey]; NSDictionary *currentEnrollmentDictionary = [self getEnrollmentDictionaryFromTestInfo]; BOOL enrollmentChanged = NO; for (id key in currentEnrollmentDictionary) { if (![savedEnrollmentDictionary[key] isEqualToString:currentEnrollmentDictionary[key]]) { enrollmentChanged = YES; NSString *testAttributeKey = [@"apptimize_test_" stringByAppendingString:key]; [[Appboy sharedInstance].user addToCustomAttributeArrayWithKey:testAttributeKeyvalue :currentEnrollmentDictionary[key]]; } } if (currentEnrollmentDictionary.count != savedEnrollmentDictionary.count) { enrollmentChanged = YES; } if (enrollmentChanged) { [[Appboy sharedInstance].user setCustomAttributeArrayWithKey:@"active_apptimize_tests" array:currentEnrollmentDictionary.allKeys]; for (id key in currentEnrollmentDictionary.allKeys) { [[Appboy sharedInstance].user addToCustomAttributeArrayWithKey:@"all_apptimize_tests" value:key]; } [[NSUserDefaults standardUserDefaults] setObject:currentEnrollmentDictionary forKey:ApptimizeAppboyTestEnrollmentStorageKey]; [[NSUserDefaults standardUserDefaults] synchronize]; } } // Dictionary with variant IDs keyed by test ID, both as NSStrings + (NSMutableDictionary *)getEnrollmentDictionaryFromTestInfo { NSMutableDictionary *enrollmentDictionary = [NSMutableDictionary dictionary]; for(id key in [Apptimize testInfo]) { NSLog(@"key=%@ value=%@", key, [[Apptimize testInfo] objectForKey:key]); NSDictionary *testInfo = [[Apptimize testInfo] objectForKey:key]; enrollmentDictionary[[testInfo.testID stringValue]] = [testInfo.enrolledVariantID stringValue]; } return enrollmentDictionary; } + (void)experimentDidGetViewed:(NSNotification*)notification { if (![notification.userInfo[ApptimizeTestFirstRunUserInfoKey] boolValue]) { return; } // Apptimize doesn't notify with IDs, so we iterate over all experiments to find the matching one. NSString *name = notification.userInfo[ApptimizeTestNameUserInfoKey]; NSString *variant = notification.userInfo[ApptimizeVariantNameUserInfoKey]; [[Apptimize testInfo] enumerateKeysAndObjectsUsingBlock:^(id key, id experiment, BOOL *stop) { BOOL match = [experiment.testName isEqualToString:name] && [experiment.enrolledVariantName isEqualToString:variant]; if (!match) { return; } // If you want to log a custom event for each participation [[Appboy sharedInstance] logCustomEvent:@"apptimize_experiment_viewed" withProperties: @{@"apptimize_experiment_name" : [experiment testName], @"apptimize_variant_name" : [experiment enrolledVariantName], @"apptimize_experiment_id" : [experiment testID], @"apptimize_variant_id" : [experiment enrolledVariantID]}]; // If you want a custom attribute array set for each participation [[Appboy sharedInstance].user addToCustomAttributeArrayWithKey:@"apptimize_experiments" value:[NSString stringWithFormat:@"experiment_id_%@:variant_id_%@:experiment_name_%@:variant_name_%@", [experiment testID], [experiment enrolledVariantID], [experiment testName], [experiment enrolledVariantName] ]]; *stop = YES; }]; } @end Android ------- Import the ApptimizeBraze.java class into your app and in your main Activity implementation, create a private member brazeApptimizeIntegration: .. code-block:: java private ApptimizeBraze brazeApptimizeIntegration; Then in your onCreate method, after initializing Braze and Apptimize: .. code-block:: java brazeApptimizeIntegration = new ApptimizeBraze(); brazeApptimizeIntegration.configureExperimentTracking(this); **ApptimizeBraze.java** .. code-block:: java import android.content.Context; import android.util.Log; import com.apptimize.Apptimize; import com.apptimize.ApptimizeTestInfo; import com.braze.Braze; import com.braze.BrazeUser; import com.braze.models.outgoing.BrazeProperties; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; public class ApptimizeBraze implements Apptimize.OnExperimentRunListener, Apptimize.OnExperimentsProcessedListener { public void configureExperimentTracking(Context context) { brazeInstance = Braze.getInstance(context); enrollmentStorage = new File(context.getDir("apptimize-appboy", Context.MODE_PRIVATE), ApptimizeBrazeTestEnrollmentStorage); Apptimize.setOnExperimentRunListener(this); Apptimize.addOnExperimentsProcessedListener(this); } @Override public void onExperimentRun(String experimentName, String variantName, boolean firstRun) { if (!firstRun) { return; } Map testInfoMap = Apptimize.getTestInfo(); if (testInfoMap == null) { return; } String experimentId = ""; String variantId = ""; Log.d("Apptimize-Braze", "In onExperimentRun"); for (ApptimizeTestInfo testInfo : testInfoMap.values()) { if (testInfo.getTestName().equals(experimentName) && testInfo.getEnrolledVariantName().equals(variantName)) { experimentId = String.valueOf(testInfo.getTestId()); variantId = String.valueOf(testInfo.getEnrolledVariantId()); } } Log.d("Apptimize-Braze", "Logging participation for " + experimentName + ":" + experimentId + " and variant " + variantName + ":" + variantId); // If you want to log a custom event for each participation logParticipationEventAsEvent(experimentName, variantName, experimentId, variantId); // If you want a custom attribute array set for each participation logParticipationEventAsAttributes(experimentName, variantName, experimentId, variantId); } private void logParticipationEventAsEvent(String experimentName, String variantName, String experimentId, String variantId) { BrazeProperties eventProperties = new BrazeProperties(); eventProperties.addProperty("apptimize_experiment_name", experimentName); eventProperties.addProperty("apptimize_variant_name", variantName); eventProperties.addProperty("apptimize_experiment_id", experimentId); eventProperties.addProperty("apptimize_variant_id", variantId); brazeInstance.logCustomEvent("apptimize_experiment_viewed", eventProperties); } private void logParticipationEventAsAttributes(String experimentName, String variantName, String experimentId, String variantId) { brazeInstance.getCurrentUser().addToCustomAttributeArray("apptimize_experiments", "experiment_id_" + experimentId + ":variant_id_" + variantId + ":experiment_name_" + experimentName + ":variant_name_" + variantName); } @Override public void onExperimentsProcessed() { Map currentEnrollmentDictionary = getEnrollmentDictionary(); Map savedEnrollmentDictionary = getPreviousEnrollmentDictionary(); BrazeUser brazeUser = brazeInstance.getCurrentUser(); boolean enrollmentChanged = false; Log.d("Apptimize-Braze", "Processing experiments"); for (String key : currentEnrollmentDictionary.keySet()) { if (savedEnrollmentDictionary == null || !currentEnrollmentDictionary.get(key).equals(savedEnrollmentDictionary.get(key))) { Log.d("Apptimize-Braze", "Found change in enrollment" + currentEnrollmentDictionary.get(key)); enrollmentChanged = true; String testAttributeKey = "apptimize_test_" + key; brazeUser.addToCustomAttributeArray(testAttributeKey, currentEnrollmentDictionary.get(key)); } } if (currentEnrollmentDictionary.size() == 0 && savedEnrollmentDictionary.size() != 0) { enrollmentChanged = true; } if (enrollmentChanged) { Log.d("Apptimize-Braze", "Enrollment changed"); brazeUser.setCustomAttributeArray("active_apptimize_tests", currentEnrollmentDictionary.keySet().toArray(new String[0])); for (String key : currentEnrollmentDictionary.keySet()) { brazeUser.addToCustomAttributeArray("all_apptimize_tests", key); } storePreviousEnrollmentDictionary(currentEnrollmentDictionary); } } private Map getEnrollmentDictionary() { Map enrollment = new HashMap(); Map testInfoMap = Apptimize.getTestInfo(); for (ApptimizeTestInfo testInfo : testInfoMap.values()) { Log.d("Apptimize-Braze", "TestID: " + String.valueOf(testInfo.getTestId()) + " VariantID: " + String.valueOf(testInfo.getEnrolledVariantId())); enrollment.put(String.valueOf(testInfo.getTestId()), String.valueOf(testInfo.getEnrolledVariantId())); } return enrollment; } private Map getPreviousEnrollmentDictionary() { ObjectInputStream enrollmentStream; try { enrollmentStream = new ObjectInputStream(new FileInputStream(enrollmentStorage)); } catch(Exception e) { Log.d("Apptimize-Braze", "Unable to open file"); return null; } Map previousEnrollment; try { previousEnrollment = (Map)enrollmentStream.readObject(); } catch (Exception e) { Log.d("Apptimize-Braze", "Unable to get previous enrollment"); return null; } return previousEnrollment; } private void storePreviousEnrollmentDictionary(Map enrollmentDictionary) { try { ObjectOutputStream enrollmentStream = new ObjectOutputStream(new FileOutputStream(enrollmentStorage)); enrollmentStream.writeObject(enrollmentDictionary); enrollmentStream.flush(); enrollmentStream.close(); } catch (Exception e) { Log.d("Apptimize-Braze", "Unable to save enrollment information"); } } private Braze brazeInstance; private File enrollmentStorage; private static String ApptimizeBrazeTestEnrollmentStorage = "ApptimizeAppboyTestEnrollmentStorage"; }