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

Rust

// Assumes Chilkat is unlocked. See Global Unlock Sample.
let _ = 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.
let raw_body = chilkat::BinData::new();
if raw_body.load_file("request-body.bin").is_err() {
    println!("Cannot read request body.");
    return;
}

let timestamp = "TIMESTAMP_HEADER".to_string();
let signature = "SIGNATURE_HEADER".to_string();
let verify_key = chilkat::PublicKey::new();
if verify_key.load_base64("CONFIGURED_EVENT_WEBHOOK_VERIFICATION_KEY").is_err() {
    println!("Check the configured SendGrid verification key.");
    return;
}

let signed_bytes = chilkat::BinData::new();
let _ = signed_bytes.append_string(&timestamp, "utf-8");
let _ = signed_bytes.append_bd(&raw_body);
let ecc = chilkat::Ecc::new();
if ecc.verify_bd(&signed_bytes, "sha256", &signature, "base64", &verify_key) != 1 {
    println!("Invalid signature: reject this request.");
    return;
}

let events = chilkat::JsonArray::new();
if events.load(&raw_body.get_string("utf-8").unwrap_or_default()).is_err() {
    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.
let files = chilkat::FileAccess::new();
let store_dir = "private-events".to_string();
if files.dir_ensure_exists(&store_dir).is_err() {
    println!("Event store unavailable.");
    return;
}

let random = chilkat::Prng::new();
let item = chilkat::JsonObject::new();
let event_id = chilkat::StringBuilder::new();
let target = chilkat::StringBuilder::new();
let temp = chilkat::StringBuilder::new();
let mut i = 0;
while i < events.size() {
    if events.object_at2(i, &item).is_err() {
        println!("Invalid event object.");
        return;
    }

    let _ = event_id.set_string(&item.string_of("sg_event_id").unwrap_or_default());
    if event_id.length() == 0 {
        println!("Missing sg_event_id.");
        return;
    }

    // Hash the ID for a filesystem-safe key. A retry maps to the same final record.
    let _ = target.set_string(&store_dir);
    let _ = target.append("/");
    let _ = target.append(&event_id.get_hash("sha256", "hex", "utf-8").unwrap_or_default());
    let _ = target.append(".json");
    if !files.file_exists(&target.get_as_string().unwrap_or_default()) {
        let record = chilkat::JsonObject::new();
        let _ = record.update_string("sg_event_id", &event_id.get_as_string().unwrap_or_default());
        let _ = record.update_string("event", &item.string_of("event").unwrap_or_default());
        let _ = record.update_int("timestamp", item.int_of("timestamp"));
        if item.has_member("notification_ref") {
            let _ = record.update_string("notification_ref", &item.string_of("notification_ref").unwrap_or_default());
        }

        if item.has_member("reason") {
            let _ = record.update_string("reason", &item.string_of("reason").unwrap_or_default());
        }

        // Publish a complete file by renaming in the same directory.
        let _ = temp.set_string(&target.get_as_string().unwrap_or_default());
        let _ = temp.append(&random.gen_random(16, "hex").unwrap_or_default());
        if record.write_file(&temp.get_as_string().unwrap_or_default()).is_err() {
            println!("Could not store event. Do not acknowledge the batch.");
            return;
        }

        if files.file_rename(&temp.get_as_string().unwrap_or_default(), &target.get_as_string().unwrap_or_default()).is_err() {
            let _ = files.file_delete(&temp.get_as_string().unwrap_or_default());
            if !files.file_exists(&target.get_as_string().unwrap_or_default()) {
                println!("Could not commit event. Do not acknowledge the batch.");
                return;
            }

        }

    }

    i = i + 1;
}

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