Recevoir des notifications et créer des interactions
Les notifications reçues de Dynamics 365 Marketing ont une charge utile supplémentaire contenant des liens et un ID de suivi pour la création d’événements d’interaction.
Wichtig
Pour suivre les liens que les destinataires ouvrent dans les notifications, vous devez recueillir le consentement de suivi des clients. Dynamics 365 Marketing n’a aucun moyen de recueillir ce consentement pour vous.
Si vous n’avez pas recueilli le consentement au suivi, vous devez utiliser le champ d’URL originalLink décrit dans l’extrait de code ci-dessous. Si vous avez obtenu le consentement, vous pouvez utiliser la valeur du champ lien, qui sera traçable.
PushLinkClicked sera généré automatiquement. L’URL est un lien de redirection qui créera l’interaction si le lien du champ lien est utilisé.
Recevoir des notifications dans iOS
Exemple d’extrait de code pour analyser les notifications entrantes dans iOS :
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
// Print full message
NSString *urlString = [[userInfo valueForKey:@"data"] valueForKey:@"link"];
NSString *originalUrlString = [[userInfo valueForKey:@"data"] valueForKey:@"originalLink"];
NSString *trackingIdString = [[userInfo valueForKey:@"data"] valueForKey:@"trackingId"];
if(![urlString isEqual:[NSNull null]])
{
if([urlString length] != 0)
{
[self createInteraction:[NSNumber numberWithInt:0] stringTracking:trackingIdString];
NSURL *url = [NSURL URLWithString:urlString];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
// iOS 10 and above
[[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:nil];
}
else
{
[[UIApplication sharedApplication] openURL:url]; // iOS <10
}
}
}
else
{
[self createInteraction:[NSNumber numberWithInt:1] stringTracking:trackingIdString];
}
}
Envoyer des événements dans iOS
Pour envoyer des événements, utilisez l’exemple d’extrait de code suivant :
- (void) createInteraction: (NSNumber *) typeInteraction stringTracking:(NSString *)trackingId
{
if([trackingId isEqual:@"00000000-0000-0000-0000-000000000000"]){
return;
}
NSString* orgId = [[NSUserDefaults standardUserDefaults] objectForKey:@"organizationId2"]
NSString* endP = [[NSUserDefaults standardUserDefaults] objectForKey:@"endpoint2"];
if(orgId == NULL || endP == NULL){
return;
}
// Create open interaction
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat: @"https://%@/api/v1.0/orgs/%@/pushchannel/event/trackings/%@", endP, orgId, trackingId]]];
// Create the Method "GET" or "POST"
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// Convert the String to Data
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
NSDictionary *jsonBodyDict = @{@"PushNotificationStatus":typeInteraction, @"DeviceToken":deviceToken};
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
// Apply the data to the body
[urlRequest setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSLog(@"Login SUCCESS");
}
else
{
NSLog(@"Error %ld", (long)[httpResponse statusCode]);
}
}];
[dataTask resume];
}
Recevoir des notifications dans Android
Les événements sont utilisés pour suivre les notifications comme suit :
- Ouvert : L’utilisateur a appuyé sur la notification.
- Cliqué : L’utilisateur a cliqué sur le lien dans la notification.
EventTrackingContrat
Corps JSON :
{
"PushNotificationStatus": "Opened",
"DeviceToken": {deviceToken}
}
URL du point de terminaison :
https://%s/api/v1.0/orgs/<orgId>/event/trackings/<trackingId>
- OrgId : Il s’agit de l’identifiant de votre organisation, généré lors de votre inscription sur Dynamics CRM.
- TrackingId : Chaque notification a un identifiant de suivi dans ses données. Cet identifiant doit être envoyé pour le suivi des événements.
Exemple d’extrait de code pour analyser les notifications entrantes dans Android
Partie 1 : Obtention de l’ID de suivi à partir du message de notification
Remplacer la méthode OnMessageReceived de FirebaseMessagingService et extrayez les données requises de la charge utile comme indiqué :
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.d(TAG, "From: " + remoteMessage.getFrom());
String message = null;
String title = null;
String deepLink = null;
String name = null;
String trackingId = null;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
message = remoteMessage.getNotification().getBody();
title = remoteMessage.getNotification().getTitle();
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
if (remoteMessage.getData().get("title") != null) {
title = remoteMessage.getData().get("title");
}
if (remoteMessage.getData().get("body") != null) {
message = remoteMessage.getData().get("body");
}
// If tracking consent has been taken, use link otherwise use 'originalLink'
if (remoteMessage.getData().get("link") != null) {
deepLink = remoteMessage.getData().get("link");
}
if (remoteMessage.getData().containsKey("trackingId")) {
trackingId = remoteMessage.getData().get("trackingId");
}
}
if (message != null || title != null) {
sendNotification(message, title, deepLink, name, trackingId);
} else {
Log.d(TAG, "Empty Notification Received");
}
}
Partie 2 : Créer une notification
Créez le contenu de la notification et ajoutez l’ID de suivi dans les données pour générer l’événement à l’ouverture de la notification.
private void sendNotification(String message, String title, String deeplink, String name, String trackingId) {
NotificationManager notificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
this,
NOTIFICATION_CHANNEL_ID)
.setContentText(message)
.setContentTitle(title)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSmallIcon(android.R.drawable.ic_popup_reminder)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(createContentIntent(this, deeplink, name, trackingId))
.setDeleteIntent(createOnDismissedIntent(this, trackingId))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message));
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
private PendingIntent createOnDismissedIntent(Context context, String trackingId) {
Intent intent = new Intent(context, NotificationDismissalReceiver.class);
intent.putExtra("TrackingId", trackingId);
return PendingIntent.getBroadcast(context.getApplicationContext(),0, intent, 0);
}
private PendingIntent createContentIntent(Context context, String deeplink, String name, String trackingId) {
Intent intent;
if (deeplink != null) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(deeplink));
} else {
intent = new Intent(this, MainActivity.class);
}
Bundle pushData = new Bundle();
pushData.putString("name", name);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtras(pushData);
intent.putExtra("Source", "Notification");
intent.putExtra("TrackingId", trackingId);
return PendingIntent.getActivity(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_ONE_SHOT);
}
Partie 3 : Générer un événement d’ouverture de notification
Gérer l’application ouverte via la notification dans MainActivity pour obtenir l’ID de suivi.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String source = getIntent().getStringExtra("Source");
if (source != null && !source.isEmpty())
{
String trackingId = getIntent().getStringExtra("TrackingId");
EventTrackerClient.sendEventToServer(this.getApplicationContext(), trackingId, EventType.Opened);
}
checkPlayServices();
FirebaseService.createChannelAndHandleNotifications(getApplicationContext());
Envoyer des événements dans Android
Pour envoyer des événements, utilisez les exemples d’extraits de code suivants :
Partie 1 : Générer la charge utile
EventTrackingContract:
public class EventTrackingContract {
private static final String LOG_TAG = "DeviceRegistrationContract";
private EventType mEvent;
private String mDeviceToken;
public EventTrackingContract(EventType eventName, String deviceToken) {
this.setEventName(eventName);
this.setDeviceToken(deviceToken);
}
public EventType getEventName() {
return mEvent;
}
public void setEventName(EventType eventName) {
this.mEvent = eventName;
}
public String getDeviceToken() {
return mDeviceToken;
}
public void setDeviceToken(String deviceToken) {
this.mDeviceToken = deviceToken;
}
public String toJsonString() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("PushNotificationStatus", mEvent.toString());
jsonObject.put("DeviceToken", mDeviceToken);
} catch (JSONException e) {
Log.d(LOG_TAG, "Json exception while creating event tracking contract: " + e.getMessage());
}
return jsonObject.toString();
}
}
EventTypeEnum:
public enum EventType {
Clicked(0),
Opened(1);
private int value;
private EventType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Partie 2 : HttpClient pour envoyer l’événement au serveur
AsyncTask.execute(new Runnable() {
@Override
public void run() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String hostname = sharedPreferences.getString(HOST_NAME, "");
String organizationId = sharedPreferences.getString(ORGANIZATION_ID, "");
final HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
final EventTrackingContract eventTrackingContract = new EventTrackingContract(event);
Log.d(TAG, eventTrackingContract.toJsonString());
String response = HttpClientWrapper.request(String.format(NotificationSettings.CxpTrackEventUrl, hostname, organizationId, trackingId),
"POST", headers, eventTrackingContract.toJsonString());
Log.d(TAG, response);
}
});
Commentaires
Envoyer et afficher des commentaires pour