Skip to content

Instantly share code, notes, and snippets.

@jamesward
Created September 8, 2020 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesward/c1ead2fd62b2ae82397f3a88e99ce581 to your computer and use it in GitHub Desktop.
Save jamesward/c1ead2fd62b2ae82397f3a88e99ce581 to your computer and use it in GitHub Desktop.
Opportunity Webhook
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);
}
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