Reading a Webhook Payload and JSON
A webhook payload is usually JSON, a plain-text format that holds labeled data. Once you know four pieces of punctuation, you can read most of them.
Stripe packs each event into a JSON payload with the event details inside1. GitHub tells you to pick JSON when a content type is offered2.
What JSON is
It's text, laid out by the same rules JavaScript uses for objects3. You don't need to know JavaScript to read it. MDN notes that it can be used independently from JavaScript, and that many programming environments can read (parse) and generate it3.
The pieces
- Curly braces { } wrap an object, a group of labeled values.
- A key and a value sit on either side of a colon. The key is the label. The value is the data. "status": "paid" has the key status and the value paid.
- Square brackets [ ] wrap an array, which is a list. JSON can also contain arrays3.
- Commas separate items.
Objects can sit inside other objects. That's how a payload holds an order, and inside the order a customer, and inside the customer an email address.
A made-up example
This sample is invented for illustration. It isn't from any real app, and real payloads carry many more fields.
{
"type": "invoice.paid",
"id": "evt_example",
"data": {
"invoice": {
"customer": "Example Co",
"paid": true,
"items": ["Setup", "Support"]
}
}
}
Read it from the outside in.
- The outer braces hold the whole message.
- type says what happened: an invoice was paid.
- id names this one event, so you can tell it apart from others.
- data holds the details. Inside it, invoice holds the record.
- items is an array with two entries.
The rules that trip people up
JSON is strict. MDN's guide gives a short list of rules:
- Text values go in double quotes. Single quotes aren't allowed3.
- No comma after the last item in an object or array3.
- No comments3.
One stray comma or colon is enough to make the whole file invalid3. If you edit a payload by hand in a text editor, check for that first.
Finding what you need
- Find the event type. Many payloads carry a field that names the event. Some apps put it in a header instead, as the page on request anatomy explains.
- Find the ID. Stripe warns that the same event may now and then arrive twice1. An ID lets you notice a repeat.
- Find the record. This is the order, invoice, ticket or contact that changed.
- Pick the fields you need. You rarely need all of them. A sheet that logs paid invoices may need only a customer name and an amount.
Field names and nesting depth vary by app. The maker's documentation lists them, so keep it open beside the payload.
If a payload doesn't hold what you need, the app's API may. The page on polling and webhooks describes how the two can work together.
Sources used
- Receive Stripe events in your webhook endpoint, Stripe Documentation
- Handling webhook deliveries, GitHub Docs
- Working with JSON, MDN Web Docs