Created
September 8, 2020 18:34
-
-
Save jamesward/c1ead2fd62b2ae82397f3a88e99ce581 to your computer and use it in GitHub Desktop.
Opportunity Webhook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trigger OpportunityCreatedWebhookTrigger on Opportunity (after insert) { | |
String url = 'https://echo-webhook.herokuapp.com/test1234'; | |
String content = Webhook.jsonContent(Trigger.new, Trigger.old); | |
Webhook.callout(url, content); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Webhook implements HttpCalloutMock { | |
public static HttpRequest request; | |
public static HttpResponse response; | |
public HTTPResponse respond(HTTPRequest req) { | |
request = req; | |
response = new HttpResponse(); | |
response.setStatusCode(200); | |
return response; | |
} | |
public static String jsonContent(List<Object> triggerNew, List<Object> triggerOld) { | |
String newObjects = '[]'; | |
if (triggerNew != null) { | |
newObjects = JSON.serialize(triggerNew); | |
} | |
String oldObjects = '[]'; | |
if (triggerOld != null) { | |
oldObjects = JSON.serialize(triggerOld); | |
} | |
String userId = JSON.serialize(UserInfo.getUserId()); | |
String content = '{"new": ' + newObjects + ', "old": ' + oldObjects + ', "userId": ' + userId + '}'; | |
return content; | |
} | |
@future(callout=true) | |
public static void callout(String url, String content) { | |
if (Test.isRunningTest()) { | |
Test.setMock(HttpCalloutMock.class, new Webhook()); | |
} | |
Http h = new Http(); | |
HttpRequest req = new HttpRequest(); | |
req.setEndpoint(url); | |
req.setMethod('POST'); | |
req.setHeader('Content-Type', 'application/json'); | |
req.setBody(content); | |
h.send(req); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment