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 VB.NET Downloads
Dim success As Boolean = 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.
Dim rawBody As New Chilkat.BinData
success = rawBody.LoadFile("request-body.bin")
If (success <> True) Then
Debug.WriteLine("Cannot read request body.")
Exit Sub
End If
Dim timestamp As String = "TIMESTAMP_HEADER"
Dim signature As String = "SIGNATURE_HEADER"
Dim verifyKey As New Chilkat.PublicKey
success = verifyKey.LoadBase64("CONFIGURED_EVENT_WEBHOOK_VERIFICATION_KEY")
If (success <> True) Then
Debug.WriteLine("Check the configured SendGrid verification key.")
Exit Sub
End If
Dim signedBytes As New Chilkat.BinData
signedBytes.AppendString(timestamp,"utf-8")
signedBytes.AppendBd(rawBody)
Dim ecc As New Chilkat.Ecc
If (ecc.VerifyBd(signedBytes,"sha256",signature,"base64",verifyKey) <> 1) Then
Debug.WriteLine("Invalid signature: reject this request.")
Exit Sub
End If
Dim events As New Chilkat.JsonArray
success = events.Load(rawBody.GetString("utf-8"))
If (success <> True) Then
Debug.WriteLine("Invalid event array.")
Exit Sub
End If
' 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.
Dim files As New Chilkat.FileAccess
Dim storeDir As String = "private-events"
success = files.DirEnsureExists(storeDir)
If (success <> True) Then
Debug.WriteLine("Event store unavailable.")
Exit Sub
End If
Dim random As New Chilkat.Prng
Dim item As New Chilkat.JsonObject
Dim eventId As New Chilkat.StringBuilder
Dim target As New Chilkat.StringBuilder
Dim temp As New Chilkat.StringBuilder
Dim i As Integer = 0
While (i < events.Size)
success = events.ObjectAt2(i,item)
If (success <> True) Then
Debug.WriteLine("Invalid event object.")
Exit Sub
End If
eventId.SetString(item.StringOf("sg_event_id"))
If (eventId.Length = 0) Then
Debug.WriteLine("Missing sg_event_id.")
Exit Sub
End If
' 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) Then
Dim record As New 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") = True) Then
record.UpdateString("notification_ref",item.StringOf("notification_ref"))
End If
If (item.HasMember("reason") = True) Then
record.UpdateString("reason",item.StringOf("reason"))
End If
' 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) Then
Debug.WriteLine("Could not store event. Do not acknowledge the batch.")
Exit Sub
End If
success = files.FileRename(temp.GetAsString(),target.GetAsString())
If (success <> True) Then
files.FileDelete(temp.GetAsString())
If (files.FileExists(target.GetAsString()) <> True) Then
Debug.WriteLine("Could not commit event. Do not acknowledge the batch.")
Exit Sub
End If
End If
End If
i = i + 1
End While
Debug.WriteLine("Verified and recorded: the HTTP handler can now return 204.")