Receiving webhooks
A webhook tells you that something changed for a user. It is thin: it carries the type, the object’s ID and a version, and you fetch the data from the API.
| Type | When it arrives | What to do |
|---|---|---|
reward.available |
a reward became available | get the terms with GET /v1/rewards/{reward_id} and create a coupon, one per reward_id |
reward.expired |
the reward’s term ended | disable the coupon |
reward.cancelled |
the reward was cancelled by a rollback (refund, chargeback) or by an operator | disable the coupon |
badge.earned |
a badge or a new level was earned | update the profile, congratulate the user |
badge.revoked |
a badge was revoked | remove the badge from the profile |
scenario.completed |
a scenario was completed | optional: analytics, a notification |
An example body:
{ "type": "reward.available", "timestamp": "2026-11-19T10:15:00Z", "data": { "reward_id": "rw_7730", "user_ref": "s_81c3", "version": 2 }}timestamp in the body is the moment of the change and is the same in every retry. The moment of sending is in the webhook-timestamp header.
How to receive
Section titled “How to receive”- Verify the signature and the timestamp (no older than 5 minutes) with the webhook secret (
whsec_…): with a ready-made Standard Webhooks library, or by hand as in the Java example. Verify the raw request body before parsing JSON: after parsing and serializing again the bytes change, and the signature will not match. - Drop duplicates by the
webhook-idheader. Delivery is at least once: a retry carries the samewebhook-idand the same body. - Answer 2xx fast, within 10 seconds. Do heavy work, such as creating a coupon, after answering, in your own queue.
- Drop stale messages by
data.version: delivery order is not guaranteed, and a message with a newer version may have arrived first.
// app/api/aapp/webhooks/route.ts (npm install standardwebhooks)import { Webhook } from 'standardwebhooks';
const wh = new Webhook(process.env.AAPP_WEBHOOK_SECRET!); // whsec_…
export async function POST(req: Request) { const payload = await req.text(); // raw body: verify before parsing JSON const headers = Object.fromEntries(req.headers); let msg: { type: string; timestamp: string; data: { reward_id?: string; user_ref: string; version: number } }; try { msg = wh.verify(payload, headers) as typeof msg; } catch { return new Response(null, { status: 400 }); }
const id = headers['webhook-id']; if (await alreadyHandled(id)) return new Response(null, { status: 200 });
await queue.push({ id, msg }); // create the coupon later, idempotently by reward_id return new Response(null, { status: 204 });}// Spring Boot. Verification by hand, so no extra dependency is needed.@RestControllerclass AappWebhookController {
private static final Duration TOLERANCE = Duration.ofMinutes(5); private final byte[] key = Base64.getDecoder() .decode(System.getenv("AAPP_WEBHOOK_SECRET").substring("whsec_".length()));
@PostMapping("/aapp/webhooks") ResponseEntity<Void> receive(@RequestBody byte[] body, @RequestHeader("webhook-id") String id, @RequestHeader("webhook-timestamp") String timestamp, @RequestHeader("webhook-signature") String signatures) throws Exception { if (!verify(id, timestamp, body, signatures)) { return ResponseEntity.badRequest().build(); } if (alreadyHandled(id)) { return ResponseEntity.ok().build(); } queue.push(id, body); // create the coupon later, idempotently by reward_id return ResponseEntity.noContent().build(); }
boolean verify(String id, String timestamp, byte[] body, String signatures) throws Exception { long sentAt = Long.parseLong(timestamp); if (Math.abs(Instant.now().getEpochSecond() - sentAt) > TOLERANCE.toSeconds()) { return false; } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8)); byte[] expected = mac.doFinal(body); // While a secret is being rotated there are several signatures, separated by spaces. for (String signature : signatures.split(" ")) { if (signature.startsWith("v1,") && MessageDigest.isEqual(expected, decode(signature.substring(3)))) { return true; } } return false; }
private static byte[] decode(String base64) { try { return Base64.getDecoder().decode(base64); } catch (IllegalArgumentException e) { return new byte[0]; } }}// go get github.com/standard-webhooks/standard-webhooks/librariesimport ( "io" "net/http" "os"
standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go")
func aappWebhook() http.HandlerFunc { wh, err := standardwebhooks.NewWebhook(os.Getenv("AAPP_WEBHOOK_SECRET")) // whsec_… if err != nil { panic(err) } return func(w http.ResponseWriter, r *http.Request) { payload, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { w.WriteHeader(http.StatusBadRequest) return } if err := wh.Verify(payload, r.Header); err != nil { w.WriteHeader(http.StatusBadRequest) return } id := r.Header.Get("webhook-id") if alreadyHandled(id) { w.WriteHeader(http.StatusOK) return } queue.Push(id, payload) // create the coupon later, idempotently by reward_id w.WriteHeader(http.StatusNoContent) }}A coupon exactly once
Section titled “A coupon exactly once”Create the coupon idempotently by reward_id. The same reward can send reward.available twice with different webhook-ids: for example, a refund moved the scenario’s completion, the reward went back to pending and then became available again. By then the coupon already exists, and a second one is not needed.
Before applying the coupon at checkout, reserve the reward with POST /v1/rewards/{reward_id}/reserve. A 409 reward_not_available response means the discount cannot be applied right now.
Retries and undelivered messages
Section titled “Retries and undelivered messages”If you did not answer 2xx within 15 seconds, answered otherwise or with a redirect, we retry: after 5 seconds, 1, 5 and 30 minutes, 1, 2, 4 and 8 hours, and a last time 24 hours after the first attempt. Each attempt is signed anew, so a retry hours later still passes the timestamp check.
If the last attempt fails too, the message is undelivered. Once your receiver is fixed, ask us to send it again: it arrives with the same webhook-id and the same body. All reward changes, delivered or not, are also in the GET /v1/rewards/feed feed, so you can reconcile against it.
URL requirements
Section titled “URL requirements”- Only
https://with a valid certificate and a public host; any port. - We do not follow redirects: a 3xx response counts as a failure.
- If your receiver needs a token, put it in the URL path or query, not in the userinfo.
testandlivehave separate URLs.