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

Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Ecc;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.JsonArray;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Prng;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        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.
        BinData rawBody = new BinData();
        try {
            rawBody.loadFile("request-body.bin");
        } catch (ChilkatException e) {
            System.out.println("Cannot read request body.");
            return;
        }

        String timestamp = "TIMESTAMP_HEADER";
        String signature = "SIGNATURE_HEADER";
        PublicKey verifyKey = new PublicKey();
        try {
            verifyKey.loadBase64("CONFIGURED_EVENT_WEBHOOK_VERIFICATION_KEY");
        } catch (ChilkatException e) {
            System.out.println("Check the configured SendGrid verification key.");
            return;
        }

        BinData signedBytes = new BinData();
        signedBytes.appendString(timestamp, "utf-8");
        signedBytes.appendBd(rawBody);
        Ecc ecc = new Ecc();
        if (ecc.verifyBd(signedBytes, "sha256", signature, "base64", verifyKey) != 1) {
            System.out.println("Invalid signature: reject this request.");
            return;
        }

        JsonArray events = new JsonArray();
        try {
            events.load(rawBody.getString("utf-8"));
        } catch (ChilkatException e) {
            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.
        FileAccess files = new FileAccess();
        String storeDir = "private-events";
        try {
            files.dirEnsureExists(storeDir);
        } catch (ChilkatException e) {
            System.out.println("Event store unavailable.");
            return;
        }

        Prng random = new Prng();
        JsonObject item = new JsonObject();
        StringBuilder eventId = new StringBuilder();
        StringBuilder target = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        int i = 0;
        while (i < events.getSize()) {
            try {
                events.objectAt2(i, item);
            } catch (ChilkatException e) {
                System.out.println("Invalid event object.");
                return;
            }

            eventId.setString(item.stringOf("sg_event_id"));
            if (eventId.getLength() == 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())) {
                JsonObject record_ = new JsonObject();
                record_.updateString("sg_event_id", eventId.getAsString());
                record_.updateString("event", item.stringOf("event"));
                record_.updateInt("timestamp", item.intOf("timestamp"));
                if (item.hasMember("notification_ref")) {
                    record_.updateString("notification_ref", item.stringOf("notification_ref"));
                }

                if (item.hasMember("reason")) {
                    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"));
                try {
                    record_.writeFile(temp.getAsString());
                } catch (ChilkatException e) {
                    System.out.println("Could not store event. Do not acknowledge the batch.");
                    return;
                }

                try {
                    files.fileRename(temp.getAsString(), target.getAsString());
                } catch (ChilkatException e) {
                    files.fileDelete(temp.getAsString());
                    if (!files.fileExists(target.getAsString())) {
                        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.");
    }
}