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 Go Downloads
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.
rawBody := chilkat.NewBinData()
success = rawBody.LoadFile("request-body.bin")
if success != true {
fmt.Println("Cannot read request body.")
rawBody.DisposeBinData()
return
}
timestamp := "TIMESTAMP_HEADER"
signature := "SIGNATURE_HEADER"
verifyKey := chilkat.NewPublicKey()
success = verifyKey.LoadBase64("CONFIGURED_EVENT_WEBHOOK_VERIFICATION_KEY")
if success != true {
fmt.Println("Check the configured SendGrid verification key.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
return
}
signedBytes := chilkat.NewBinData()
signedBytes.AppendString(timestamp,"utf-8")
signedBytes.AppendBd(rawBody)
ecc := chilkat.NewEcc()
if ecc.VerifyBd(signedBytes,"sha256",signature,"base64",verifyKey) != 1 {
fmt.Println("Invalid signature: reject this request.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
return
}
events := chilkat.NewJsonArray()
success = events.Load(*rawBody.GetString("utf-8"))
if success != true {
fmt.Println("Invalid event array.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
events.DisposeJsonArray()
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.
files := chilkat.NewFileAccess()
storeDir := "private-events"
success = files.DirEnsureExists(storeDir)
if success != true {
fmt.Println("Event store unavailable.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
events.DisposeJsonArray()
files.DisposeFileAccess()
return
}
random := chilkat.NewPrng()
item := chilkat.NewJsonObject()
eventId := chilkat.NewStringBuilder()
target := chilkat.NewStringBuilder()
temp := chilkat.NewStringBuilder()
i := 0
for (i < events.Size()) {
success = events.ObjectAt2(i,item)
if success != true {
fmt.Println("Invalid event object.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
events.DisposeJsonArray()
files.DisposeFileAccess()
random.DisposePrng()
item.DisposeJsonObject()
eventId.DisposeStringBuilder()
target.DisposeStringBuilder()
temp.DisposeStringBuilder()
return
}
eventId.SetString(*item.StringOf("sg_event_id"))
if eventId.Length() == 0 {
fmt.Println("Missing sg_event_id.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
events.DisposeJsonArray()
files.DisposeFileAccess()
random.DisposePrng()
item.DisposeJsonObject()
eventId.DisposeStringBuilder()
target.DisposeStringBuilder()
temp.DisposeStringBuilder()
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 {
record := chilkat.NewJsonObject()
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 {
fmt.Println("Could not store event. Do not acknowledge the batch.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
events.DisposeJsonArray()
files.DisposeFileAccess()
random.DisposePrng()
item.DisposeJsonObject()
eventId.DisposeStringBuilder()
target.DisposeStringBuilder()
temp.DisposeStringBuilder()
record.DisposeJsonObject()
return
}
success = files.FileRename(*temp.GetAsString(),*target.GetAsString())
if success != true {
files.FileDelete(*temp.GetAsString())
if files.FileExists(*target.GetAsString()) != true {
fmt.Println("Could not commit event. Do not acknowledge the batch.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
events.DisposeJsonArray()
files.DisposeFileAccess()
random.DisposePrng()
item.DisposeJsonObject()
eventId.DisposeStringBuilder()
target.DisposeStringBuilder()
temp.DisposeStringBuilder()
record.DisposeJsonObject()
return
}
}
}
i = i + 1
}
fmt.Println("Verified and recorded: the HTTP handler can now return 204.")
rawBody.DisposeBinData()
verifyKey.DisposePublicKey()
signedBytes.DisposeBinData()
ecc.DisposeEcc()
events.DisposeJsonArray()
files.DisposeFileAccess()
random.DisposePrng()
item.DisposeJsonObject()
eventId.DisposeStringBuilder()
target.DisposeStringBuilder()
temp.DisposeStringBuilder()
record.DisposeJsonObject()