A Webhook Receiver That Saves the Payload First

When an outside system sends webhooks into Salesforce, it's tempting to process each event right there in the REST method. I prefer a listener that only does two things. It checks the request is genuine, and it saves the raw payload to a log record. Then it answers. A separate job does the actual processing, which I'll cover in the next post.

That split pays off in a few ways. The sender gets a fast response, so it doesn't time out and resend. If the processing logic has a bug, the payload is still sitting there to reprocess once the fix is in. And when someone asks what the other system actually sent, there's a record of it.

Here's a cut-down version. Webhook_Log__c is a plain custom object with a direction, a status and a long text area for the payload.

//exposed publicly through a Salesforce Site -> {Site URL}/services/apexrest/webhooks/vendor/v1/
@RestResource(urlMapping='/webhooks/vendor/v1/*')
global without sharing class vendorWebhookListener {

    @HttpPost
    global static void handlePost() {
        RestRequest request = RestContext.request; //the inbound request
        RestResponse response = RestContext.response; //the response we send back
        response.addHeader('Content-Type', 'application/json');
        Map<String, Object> responseMap = new Map<String, Object>(); //same response shape for success and failure
        try {
            if (!webhookSignature.isValid(request.requestBody, request.headers.get('X-Signature'))) { //reject anything we can't verify
                response.statusCode = 401;
                responseMap.put('success', false);
                responseMap.put('error', new Map<String, String>{'type' => 'invalid_signature'});
            } else {
                Webhook_Log__c log = new Webhook_Log__c(
                    Direction__c = 'Inbound',
                    Status__c = 'New', //the processing job looks for this
                    Request__c = request.requestBody.toString().left(131072) //long text area limit
                );
                insert log;
                response.statusCode = 200;
                responseMap.put('success', true);
                responseMap.put('id', log.Id); //handy for the sender's own logs
            }
        } catch (Exception e) {
            response.statusCode = 500;
            responseMap.put('success', false);
            responseMap.put('error', new Map<String, String>{'type' => e.getTypeName(), 'message' => e.getMessage()});
        }
        response.responseBody = Blob.valueOf(JSON.serialize(responseMap)); //serialize and send the response
    }
}

Now the signature check. Most vendors sign the body with HMAC-SHA256 and a shared secret, but check their docs for exactly what they sign and which header they use. Some include a timestamp, and some send two signatures so they can rotate keys.

public class webhookSignature {

    //true when the signature header matches an HMAC-SHA256 of the body, using our shared secret
    public static Boolean isValid(Blob body, String signatureHeader) {
        if (body == null || String.isBlank(signatureHeader)) { //nothing to check
            return false;
        }
        String secret = Webhook_Settings__c.getOrgDefaults().Signing_Secret__c; //protected custom setting, so it stays out of source control
        Blob mac = Crypto.generateMac('hmacSHA256', body, Blob.valueOf(secret)); //sign the body the same way the sender did
        return EncodingUtil.base64Encode(mac) == signatureHeader;
    }
}

A few practical notes:

  • Guest User access. The Site's guest User needs access to the Apex class and create access on the log object, and nothing more.
  • Keep the response shape the same. Senders log what you return. When success, id and error always appear in the same places, it's much easier to troubleshoot from their side.
  • Don't look anything up you don't need. Every query in the listener is one more thing that can fail before the payload is safe.

The payoff comes later. When the processing logic has a bug (and it will at some point), the payloads are still sitting there waiting to be reprocessed.

Automated Exchange Rates in Salesforce.com

Reduce Repetitive Tasks, Eliminate Errors & Free Up Your Administrators.

Birthday Reminders for Salesforce.com

It might lead to a sale. Or it might make you feel good.