Sample code for 30+ languages & platforms
C++ Requires Chilkat v11.0.0+

SendGrid: Verify and record delivery events (web server required)

See more SendGrid Examples

Requires a web server with a public HTTPS POST endpoint. Enable the signed Event Webhook, subscribe to delivery events, and configure its verification public key on your server. This is the portable handler logic, not a standalone HTTP listener. Pass the unmodified request body and the X-Twilio-Email-Event-Webhook-Timestamp and X-Twilio-Email-Event-Webhook-Signature headers from your web framework. Do not take the verification key from the request.

Return 403 for an invalid signature, 400 for malformed input, and 5xx for storage failures. Return 204 only after the whole batch is recorded. A deferred event is temporary; bounce records a delivery failure. The receipt example sets notification_ref, which appears directly on the event. Keep event IDs across retries. On multiple hosts, use a shared database with a unique constraint on sg_event_id.

Signature verification ยท Event fields

Chilkat C++ Downloads

C++
#include <CkBinData.h>
#include <CkPublicKey.h>
#include <CkEcc.h>
#include <CkJsonArray.h>
#include <CkFileAccess.h>
#include <CkPrng.h>
#include <CkJsonObject.h>
#include <CkStringBuilder.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;

    //  Adapter inputs: the original request body and these two incoming HTTP headers.
    //  For a captured request use a private, request-specific file. A live handler can
    //  put the raw bytes directly in rawBody instead. Never parse and reserialize them.
    CkBinData rawBody;
    success = rawBody.LoadFile("request-body.bin");
    if (success != true) {
        std::cout << "Cannot read request body." << "\r\n";
        return;
    }

    const char *timestamp = "TIMESTAMP_HEADER";
    const char *signature = "SIGNATURE_HEADER";
    CkPublicKey verifyKey;
    success = verifyKey.LoadBase64("CONFIGURED_EVENT_WEBHOOK_VERIFICATION_KEY");
    if (success != true) {
        std::cout << "Check the configured SendGrid verification key." << "\r\n";
        return;
    }

    CkBinData signedBytes;
    signedBytes.AppendString(timestamp,"utf-8");
    signedBytes.AppendBd(rawBody);
    CkEcc ecc;
    if (ecc.VerifyBd(signedBytes,"sha256",signature,"base64",verifyKey) != 1) {
        std::cout << "Invalid signature: reject this request." << "\r\n";
        return;
    }

    CkJsonArray events;
    success = events.Load(rawBody.getString("utf-8"));
    if (success != true) {
        std::cout << "Invalid event array." << "\r\n";
        return;
    }

    //  Use a persistent directory outside the web root, writable only by the handler.
    //  Store one record per event, not one per message: a deferred message may later be delivered.
    CkFileAccess files;
    const char *storeDir = "private-events";
    success = files.DirEnsureExists(storeDir);
    if (success != true) {
        std::cout << "Event store unavailable." << "\r\n";
        return;
    }

    CkPrng random;
    CkJsonObject item;
    CkStringBuilder eventId;
    CkStringBuilder target;
    CkStringBuilder temp;
    int i = 0;
    while ((i < events.get_Size())) {
        success = events.ObjectAt2(i,item);
        if (success != true) {
            std::cout << "Invalid event object." << "\r\n";
            return;
        }

        eventId.SetString(item.stringOf("sg_event_id"));
        if (eventId.get_Length() == 0) {
            std::cout << "Missing sg_event_id." << "\r\n";
            return;
        }

        //  Hash the ID for a filesystem-safe key. A retry maps to the same final record.
        target.SetString(storeDir);
        target.Append("/");
        target.Append(eventId.getHash("sha256","hex","utf-8"));
        target.Append(".json");
        if (files.FileExists(target.getAsString()) != true) {
            CkJsonObject record;
            record.UpdateString("sg_event_id",eventId.getAsString());
            record.UpdateString("event",item.stringOf("event"));
            record.UpdateInt("timestamp",item.IntOf("timestamp"));
            if (item.HasMember("notification_ref") == true) {
                record.UpdateString("notification_ref",item.stringOf("notification_ref"));
            }

            if (item.HasMember("reason") == true) {
                record.UpdateString("reason",item.stringOf("reason"));
            }

            //  Publish a complete file by renaming in the same directory.
            temp.SetString(target.getAsString());
            temp.Append(random.genRandom(16,"hex"));
            success = record.WriteFile(temp.getAsString());
            if (success != true) {
                std::cout << "Could not store event. Do not acknowledge the batch." << "\r\n";
                return;
            }

            success = files.FileRename(temp.getAsString(),target.getAsString());
            if (success != true) {
                files.FileDelete(temp.getAsString());
                if (files.FileExists(target.getAsString()) != true) {
                    std::cout << "Could not commit event. Do not acknowledge the batch." << "\r\n";
                    return;
                }

            }

        }

        i = i + 1;
    }

    std::cout << "Verified and recorded: the HTTP handler can now return 204." << "\r\n";
    }