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

PHP ActiveX
<?php

$success = 0;

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

//  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.
$rawBody = new COM("Chilkat.BinData");
$success = $rawBody->LoadFile('request-body.bin');
if ($success != 1) {
    print 'Cannot read request body.' . "\n";
    exit;
}

$timestamp = 'TIMESTAMP_HEADER';
$signature = 'SIGNATURE_HEADER';
$verifyKey = new COM("Chilkat.PublicKey");
$success = $verifyKey->LoadBase64('CONFIGURED_EVENT_WEBHOOK_VERIFICATION_KEY');
if ($success != 1) {
    print 'Check the configured SendGrid verification key.' . "\n";
    exit;
}

$signedBytes = new COM("Chilkat.BinData");
$signedBytes->AppendString($timestamp,'utf-8');
$signedBytes->AppendBd($rawBody);
$ecc = new COM("Chilkat.Ecc");
if ($ecc->VerifyBd($signedBytes,'sha256',$signature,'base64',$verifyKey) != 1) {
    print 'Invalid signature: reject this request.' . "\n";
    exit;
}

$events = new COM("Chilkat.JsonArray");
$success = $events->Load($rawBody->getString('utf-8'));
if ($success != 1) {
    print 'Invalid event array.' . "\n";
    exit;
}

//  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.
$files = new COM("Chilkat.FileAccess");
$storeDir = 'private-events';
$success = $files->DirEnsureExists($storeDir);
if ($success != 1) {
    print 'Event store unavailable.' . "\n";
    exit;
}

$random = new COM("Chilkat.Prng");
$item = new COM("Chilkat.JsonObject");
$eventId = new COM("Chilkat.StringBuilder");
$target = new COM("Chilkat.StringBuilder");
$temp = new COM("Chilkat.StringBuilder");
$i = 0;
while (($i < $events->Size)) {
    $success = $events->ObjectAt2($i,$item);
    if ($success != 1) {
        print 'Invalid event object.' . "\n";
        exit;
    }

    $eventId->SetString($item->stringOf('sg_event_id'));
    if ($eventId->Length == 0) {
        print 'Missing sg_event_id.' . "\n";
        exit;
    }

    //  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()) != 1) {
        $record = new COM("Chilkat.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') == 1) {
            $record->UpdateString('notification_ref',$item->stringOf('notification_ref'));
        }

        if ($item->HasMember('reason') == 1) {
            $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 != 1) {
            print 'Could not store event. Do not acknowledge the batch.' . "\n";
            exit;
        }

        $success = $files->FileRename($temp->getAsString(),$target->getAsString());
        if ($success != 1) {
            $files->FileDelete($temp->getAsString());
            if ($files->FileExists($target->getAsString()) != 1) {
                print 'Could not commit event. Do not acknowledge the batch.' . "\n";
                exit;
            }

        }

    }

    $i = $i + 1;
}

print 'Verified and recorded: the HTTP handler can now return 204.' . "\n";

?>