Skip to content

Instantly share code, notes, and snippets.

@codefriar
Last active January 30, 2024 06:21
Show Gist options
  • Save codefriar/b9da78ecd4c9ba2cb0e085ac8167909e to your computer and use it in GitHub Desktop.
Save codefriar/b9da78ecd4c9ba2cb0e085ac8167909e to your computer and use it in GitHub Desktop.
MCMessagingUtils is an Apex class used to trigger journey builder actions and push messages from Salesforce service and sales cloud.
public with sharing class Invocable_TriggerMCEvent {
@InvocableMethod(label='Send Message with new Comment to Reporter' description='Send Message with new Comment to Reporter')
public static void TriggerMCEvent(List<String> contactKey) {
MCMessagingUtils.triggerMCInteractionEvent(contactKey[0]);
}
}
public with sharing class MCMessagingUtils {
//inner classes
public class MCMessagingUtilsException extends Exception{}
public class accessTokenResult{
public String accessToken;
public integer expiresIn;
}
public class TriggerInteractionEventObj {
String ContactKey {get;set;}
String EventDefinitionKey {get;set;}
public TriggerInteractionEventObj(String incomingContactKey){
this.ContactKey = incomingContactKey;
this.EventDefinitionKey = credentials.eventDefinitionKey__c;
}
}
// Appropriate HTTP methods for various calls
private static final String kAuthMethod = 'POST';
private static final String kFireInteractionMethod = 'POST';
private static final String kFirePushMessageMethod = 'POST';
// Custom Setting Name to use:
private static final String kCredsName = 'df16';
// Push Message to reuse:
private static final String kMessageId = 'MjoxMTQ6MA';
// URI's
private static final String kAPIAuthBaseURI = 'https://auth.exacttargetapis.com';
private static final String kAPIBaseURI = 'https://www.exacttargetapis.com';
private static final String kAuthURI = kAPIAuthBaseURI + '/v1/requestToken';
private static final String kFireInteractionEventURI = kAPIBaseURI + '/interaction/v1/events';
private static final String kFirePushMessageURI = '/messageContact/'+ kMessageId +'/send';
private static final String kActivityTriggerMCInteractionEvent = 'kActivityTriggerMCInteractionEvent';
private static final String kActivityTriggerMCPushEvent = 'kActivityTriggerMCPushEvent';
private static McCreds__c credentials = McCreds__c.getInstance(kCredsName);
private static String preservedActivity;
private static String preservedContactKey;
private static String preservedCommentBody;
public static void triggerMCInteractionEvent(String contactKey){
MCMessagingUtils.accessToken();
TriggerInteractionEventObj payloadObj= new TriggerInteractionEventObj(contactKey);
String payloadString = JSON.serialize(payloadObj);
system.debug('*** - method: ' + kFireInteractionMethod);
system.debug('*** - payload: ' + payloadString);
system.debug('*** - uri: ' + kFireInteractionEventURI);
system.debug('*** - token: ' + MCMessagingUtils.accessToken() );
sendHTTPRequest(kFireInteractionMethod,
payloadString,
kFireInteractionEventURI);
}
public static void sendMCPushMessage(String commentBody, String contactKey){
MCMessagingUtils.accessToken();
sendHTTPRequest(kFirePushMessageMethod,
generateMessageSendBody(commentBody, contactKey),
kFirePushMessageURI);
}
//Note, I have to use a string building method, rather than serializing an object
// because override is a reserved word in apex.
private Static String generateMessageSendBody(String CommentBody, String SubscriberKey){
return '{' +
'"MessageText": "'+CommentBody+'",' +
'"Override": true,'+
'"sound": "default",'+
'"SendTime": "2012-10-31 09:00",'+
'"content-available": 1'+
'"subscriberKeys": ["' + SubscriberKey + '"]' +
'}';
}
private static string accessToken(){
if(credentials.accessToken__c == null || DateTime.now() > credentials.expiresIn__c){
return makeAuthenticationCall();
} else {
return credentials.accessToken__c;
}
}
private static string makeAuthenticationCall(){
if(credentials != null && String.isNotEmpty(credentials.clientId__c) && String.isNotEmpty(credentials.clientSecret__c)){
String authJson = '{"clientId":"' + credentials.clientId__c + '","clientSecret":"' + credentials.clientSecret__c + '"}';
HttpResponse response = sendAuthRequest(authJson);
accessTokenResult atr = (accessTokenResult) System.JSON.deserialize(response.getBody(), accessTokenResult.class);
credentials.accessToken__c = atr.accessToken;
credentials.expiresIn__c = Datetime.now().addSeconds(atr.expiresIn);
update credentials;
}
return credentials.accessToken__c;
}
private static HttpResponse sendAuthRequest(String body){
Http h = new Http();
HttpRequest req = generateRequest(kAuthMethod, body, kAuthURI);
HttpResponse res = h.send(req);
return res;
}
private static HttpRequest generateRequest(String method, String body, String url){
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'application/json');
req.setEndpoint(url);
req.setBody(body);
req.setMethod(method);
system.debug('%%% - ' + body);
return req;
}
@future(Callout=true)
Public Static void sendHTTPRequest(String Method, String Body, String URL) {
Http h = new Http();
HttpRequest req = generateRequest(method, body, url);
req.setHeader('Authorization', 'Bearer ' + MCMessagingUtils.accessToken());
HttpResponse res = h.send(req);
system.debug('#### - ' + res.getBody());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment