Primirea notificărilor și crearea de interacțiuni
Notificările primite de la Dynamics 365 Marketing au o sarcină utilă suplimentară care conține linkuri și a trackingId pentru crearea de evenimente de interacțiune.
Wichtig
Pentru a urmări linkurile pe care destinatarii le deschid în notificări, trebuie să colectați consimțământul de urmărire a clienților. Dynamics 365 Marketing nu are nicio modalitate de a colecta acest consimțământ pentru dvs.
Dacă nu ați colectat consimțământul de urmărire, trebuie să utilizați originalLink Câmpul URL descris în fragment de cod de mai jos. Dacă ați obținut consimțământul, puteți utiliza legătură valoarea câmpului, care va fi urmăribilă.
PushLinkClicked va fi generat automat. URL-ul este un link de redirecționare care va crea interacțiunea dacă linkul de la legătură câmpul este utilizat.
Primiți notificări în iOS
Exemplu fragment de cod pentru a analiza notificările primite în 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];
}
}
Trimite evenimente în iOS
Pentru a trimite evenimente, utilizați următorul exemplu fragment de cod:
- (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];
}
Primiți notificări în Android
Evenimentele sunt folosite pentru urmărirea notificărilor după cum urmează:
- Deschis: Utilizatorul a atins notificarea.
- S-a făcut clic pe: Utilizatorul a făcut clic pe linkul din notificare.
Contract de urmărire a evenimentelor
Corp JSON:
{
"PushNotificationStatus": "Opened",
"DeviceToken": {deviceToken}
}
Adresa URL a punctului final:
https://%s/api/v1.0/orgs/<orgId>/event/trackings/<trackingId>
- OrgId: Acesta este ID-ul organizației dvs., generat atunci când v-ați înregistrat Dynamics CRM.
- TrackingId: Fiecare notificare are un ID de urmărire în datele sale. Acest ID trebuie trimis pentru urmărirea evenimentului.
Exemplu fragment de cod pentru a analiza notificările primite Android
Partea 1: Obținerea ID-ului de urmărire din mesajul de notificare
Ignorați OnMessageReceived Metodă de FirebaseMessagingService și extrageți datele necesare din sarcina utilă, așa cum se arată:
@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");
}
}
Partea 2: Creați o notificare
Creați conținutul notificării și adăugați ID-ul de urmărire în date pentru a genera evenimentul la notificarea deschisă.
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);
}
Partea 3: Generați un eveniment deschis de notificare
Gestionați aplicația deschisă prin notificarea în Activitate principala pentru a obține ID-ul de urmărire.
@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());
Trimite evenimente în Android
Pentru a trimite evenimente, utilizați următoarele fragmente de cod exemplu:
Partea 1: Generați sarcina utilă
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;
}
}
Partea 2: HttpClient pentru trimiterea evenimentului către server
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);
}
});
Feedback
Trimiteți și vizualizați feedback pentru