Sample code for 30+ languages & platforms
CkJava 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 CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean 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 = new CkBinData();
    success = rawBody.LoadFile("request-body.bin");
    if (success != true) {
        System.out.println("Cannot read request body.");
        return;
        }

    String timestamp = "TIMESTAMP_HEADER";
    String signature = "SIGNATURE_HEADER";
    CkPublicKey verifyKey = new CkPublicKey();
    success = verifyKey.LoadBase64("CONFIGURED_EVENT_WEBHOOK_VERIFICATION_KEY");
    if (success != true) {
        System.out.println("Check the configured SendGrid verification key.");
        return;
        }

    CkBinData signedBytes = new CkBinData();
    signedBytes.AppendString(timestamp,"utf-8");
    signedBytes.AppendBd(rawBody);
    CkEcc ecc = new CkEcc();
    if (ecc.VerifyBd(signedBytes,"sha256",signature,"base64",verifyKey) != 1) {
        System.out.println("Invalid signature: reject this request.");
        return;
        }

    CkJsonArray events = new CkJsonArray();
    success = events.Load(rawBody.getString("utf-8"));
    if (success != true) {
        System.out.println("Invalid event array.");
        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 = new CkFileAccess();
    String storeDir = "private-events";
    success = files.DirEnsureExists(storeDir);
    if (success != true) {
        System.out.println("Event store unavailable.");
        return;
        }

    CkPrng random = new CkPrng();
    CkJsonObject item = new CkJsonObject();
    CkStringBuilder eventId = new CkStringBuilder();
    CkStringBuilder target = new CkStringBuilder();
    CkStringBuilder temp = new CkStringBuilder();
    int i = 0;
    while ((i < events.get_Size())) {
        success = events.ObjectAt2(i,item);
        if (success != true) {
            System.out.println("Invalid event object.");
            return;
            }

        eventId.SetString(item.stringOf("sg_event_id"));
        if (eventId.get_Length() == 0) {
            System.out.println("Missing sg_event_id.");
            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 = new CkJsonObject();
            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) {
                System.out.println("Could not store event. Do not acknowledge the batch.");
                return;
                }

            success = files.FileRename(temp.getAsString(),target.getAsString());
            if (success != true) {
                files.FileDelete(temp.getAsString());
                if (files.FileExists(target.getAsString()) != true) {
                    System.out.println("Could not commit event. Do not acknowledge the batch.");
                    return;
                    }

                }

            }

        i = i+1;
        }

    System.out.println("Verified and recorded: the HTTP handler can now return 204.");
  }
}