# Receiving webhooks > Receive events on your server and verify that Abuna sent them. Source: https://abuna.app/docs/guides/webhooks Webhooks let your server react when something happens in your app, such as a paid invoice or a canceled subscription. Abuna sends an HTTPS `POST` to your webhook URL, signed with your signing secret, so you can check that it came from Abuna. ## Add your webhook URL In the dashboard, open **Webhooks** and set the **Webhook URL**. Only a team owner can change it, and only from the dashboard. A secret key can't point your webhooks somewhere else. Test mode and Live mode each have their own webhook URL and signing secret. A new Test app doesn't copy the Live URL, so Test events never reach a server meant for real customers. The webhook URL must: - Use `https`. - Have a host, and no username or password in it. - Not point at `localhost`, or at a private, loopback, link-local or carrier-grade NAT address. This holds for every request and every redirect, not only for the URL you save. To receive events on your own machine, expose it through a public HTTPS tunnel and use that URL. The [Quickstart](https://abuna.app/docs/quickstart.md#set-your-webhook-endpoint) has a command for one. ## Choose your events Your webhook URL receives only the event types you choose. When you add it in the dashboard, **Recommended** is already selected. To change the choice later, a team owner opens **Webhooks**, edits **Events**, and keeps **Recommended** or picks events one by one. Recommended holds the events a standard integration handles: - `session.completed`, `session.expired` - `subscription.created`, `subscription.trial_ending`, `subscription.paid`, `subscription.renewed`, `subscription.past_due`, `subscription.recovered`, `subscription.canceled`, `subscription.updated` - `invoice.created`, `invoice.paid`, `invoice.payment_failed` - `customer.updated`, `customer.deleted` What you can rely on: - Every event is kept in your app's event list, whether or not your URL receives it. See [Catch up on missed events](https://abuna.app/docs/api/events.md#catch-up). - The [test event](https://abuna.app/docs/guides/webhooks.md#send-a-test-event) always reaches your URL, whatever you chose. - A new choice applies to events from then on. Events that happened before it aren't sent. - When Abuna adds an event type, your URL doesn't receive it until you choose it. - A webhook URL added before 10 October 2026 receives every event type that existed on that date, until you change its events. `webhook_events` on the [app object](https://abuna.app/docs/api/apps.md#object) lists the event types your URL receives. `GET /v1/event-types` lists every event type you can choose, with `recommended` set on the ones in Recommended. It needs no key. **GET /v1/event-types** cURL: ```bash curl https://api.abuna.app/v1/event-types ``` Node.js: ```javascript const response = await fetch("https://api.abuna.app/v1/event-types"); const { items } = await response.json(); const recommended = items.filter((e) => e.recommended).map((e) => e.type); ``` **Response** ```json { "items": [ { "type": "session.completed", "recommended": true }, { "type": "session.expired", "recommended": true }, { "type": "subscription.created", "recommended": true }, { "type": "subscription.trial_ending", "recommended": true }, { "type": "subscription.paid", "recommended": true }, { "type": "subscription.renewed", "recommended": true }, { "type": "subscription.past_due", "recommended": true }, { "type": "subscription.recovered", "recommended": true }, { "type": "subscription.canceled", "recommended": true }, { "type": "subscription.updated", "recommended": true }, { "type": "invoice.created", "recommended": true }, { "type": "invoice.paid", "recommended": true }, { "type": "invoice.payment_failed", "recommended": true }, { "type": "customer.updated", "recommended": true }, { "type": "customer.deleted", "recommended": true }, { "type": "customer.updates_changed", "recommended": false }, { "type": "plan_offer.created", "recommended": false }, { "type": "plan_offer.confirmed", "recommended": false }, { "type": "plan_offer.canceled", "recommended": false }, { "type": "plan_offer.expired", "recommended": false }, { "type": "price_change.scheduled", "recommended": false }, { "type": "price_change.canceled", "recommended": false }, { "type": "price_change.applied", "recommended": false } ], "next_cursor": null } ``` ## Get your signing secret Abuna shows each signing secret once: when you create the app, and when you rotate the secret. A Test secret looks like `whsec_test_...` and a Live one like `whsec_live_...`. Store it on your server, next to your secret key. ## What Abuna sends Each delivery is a JSON body with these headers: - `X-Abuna-Event`: the event type, like `invoice.paid`. - `X-Abuna-Delivery`: the ID of this delivery. It stays the same when a failed delivery is sent again. A redelivery gets a new one. - `X-Abuna-Environment`: `test` or `live`. - `X-Abuna-Signature`: when Abuna signed the request, and the signature. See [Verify the signature](https://abuna.app/docs/guides/webhooks.md#verify-the-signature). The body always has the same five fields. `id` is the event's ID. `data` depends on the type. The mode is in the body as well as the header, because only the body is signed. **Body** ```json { "created_at": 1794780106, "data": { "amount": 5000, "coupon_id": null, "credit": 0, "currency": "XAF", "discount": 0, "invoice_id": "OG3ZsOC7", "invoice_number": "ACME-000001", "kind": "period", "metadata": { "user_id": "42" }, "paid_at": 1794780106, "payment": { "amount": 5000, "app_id": "qhf83tDc", "created_at": 1794780106, "currency": "XAF", "driver": "sandbox", "exchange_margin_bps": null, "exchange_rate": null, "exchange_rate_at": null, "fee": 100, "id": "tGfwt5dd", "marked_by_api_key_id": null, "marked_by_user_id": null, "message": null, "method_label": "Successful payment (test)", "net": null, "note": null, "original_amount": 5000, "original_currency": "XAF", "period_id": "0kYPFwxJ", "provider": "test", "provider_reference": "test_ff6aaf0182bd3f1148bd", "session_id": null, "status": "succeeded" }, "period_end": 1797372106, "period_id": "0kYPFwxJ", "period_start": 1794780106, "promotion_code_id": null, "subscription": { "activated_at": 1794780106, "app_id": "qhf83tDc", "cancel_at": null, "cancel_at_period_end": false, "canceled_at": null, "created_at": 1794780106, "current_period_end": 1797372106, "current_period_start": 1794780106, "customer_id": "GzeUZeSV", "discount": null, "ended_reason": null, "id": "wTiODxvH", "manage_token": "ac78d36db5c13e5f1bcbb67ece2ee29137a0", "metadata": { "user_id": "42" }, "price_id": "IaFQHLTL", "starts_at": 1794780106, "status": "active", "trial_ends_at": null }, "subscription_id": "wTiODxvH" }, "environment": "test", "id": "01M7GKP458FZEMMQQ7VM7J4QK4", "type": "invoice.paid" } ``` ## Verify the signature `X-Abuna-Signature` holds comma-separated pairs. `t` is when Abuna signed the request, in Unix seconds. Each `v1` is a hex HMAC-SHA256, keyed by your signing secret, of `t`, a dot, and the raw body: `"."`. **Signature header** ```bash X-Abuna-Signature: t=1727600000,v1=5f2b8c1e9a4d7f3b6e0c8a2d5f9b1e4c7a3d6f0b8e2c5a9d1f4b7e3c6a0d8f2b ``` For every request: 1. Read the raw body, as bytes, before you parse it. 2. Split the header on commas, and each pair on the first `=`. Keep `t` and every `v1`. 3. If `t` is more than 300 seconds before or after your server's clock, answer `400`. This stops someone from replaying an old request. 4. Compute the HMAC-SHA256 of `t`, a `.`, and the raw body with your signing secret, and hex-encode it. 5. Compare the result with each `v1`, using a constant-time comparison. Accept the request if any one matches. 6. If none matches, answer `400` and ignore the event. The header usually has one `v1`. While a [secret rotation](https://abuna.app/docs/guides/webhooks.md#rotate-the-secret) overlaps, it has two: one made with the new secret and one with the old. Accepting any match keeps your server working whichever secret your server holds. Ignore pairs you don't know, so a new signature scheme added later doesn't break you. **Verify a webhook** Node.js: ```javascript import crypto from "node:crypto"; import http from "node:http"; // header is "t=1727600000,v1=", with a second v1 while a secret rotation overlaps. function verifyAbunaSignature(rawBody, header, secret) { const pairs = (header ?? "").split(",").map((part) => part.split("=")); const timestamp = pairs.find(([key]) => key === "t")?.[1] ?? ""; if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; const expected = crypto.createHmac("sha256", secret).update(timestamp + ".").update(rawBody).digest(); return pairs.some(([key, value]) => { const received = Buffer.from(key === "v1" ? value ?? "" : "", "hex"); return received.length === expected.length && crypto.timingSafeEqual(received, expected); }); } http .createServer((req, res) => { const chunks = []; req.on("data", (chunk) => chunks.push(chunk)); req.on("end", async () => { const rawBody = Buffer.concat(chunks); if (!verifyAbunaSignature(rawBody, req.headers["x-abuna-signature"], process.env.ABUNA_WEBHOOK_SECRET)) { res.writeHead(400).end(); return; } const event = JSON.parse(rawBody); // Save the event before you answer, then handle it in the background. try { await saveEvent(event); } catch { res.writeHead(500).end(); return; } res.writeHead(200).end(); }); }) .listen(3000); ``` Python: ```python import hashlib import hmac import time # header is "t=1727600000,v1=", with a second v1 while a secret rotation overlaps. def verify_abuna_signature(raw_body: bytes, header: str, secret: str) -> bool: pairs = [part.split("=", 1) for part in header.split(",") if "=" in part] timestamp = next((value for key, value in pairs if key == "t"), "") if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300: return False signed = timestamp.encode() + b"." + raw_body expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() return any(key == "v1" and hmac.compare_digest(value, expected) for key, value in pairs) # In Flask: # verify_abuna_signature(request.get_data(), request.headers.get("X-Abuna-Signature", ""), secret) ``` PHP: ```php ", with a second v1 while a secret rotation overlaps. function verify_abuna_signature(string $rawBody, string $header, string $secret): bool { $timestamp = ''; $signatures = []; foreach (explode(',', $header) as $part) { [$key, $value] = array_pad(explode('=', $part, 2), 2, ''); if ($key === 't') { $timestamp = $value; } elseif ($key === 'v1') { $signatures[] = $value; } } if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300) { return false; } $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret); foreach ($signatures as $signature) { if (hash_equals($expected, $signature)) { return true; } } return false; } $rawBody = file_get_contents('php://input'); if (!verify_abuna_signature($rawBody, $_SERVER['HTTP_X_ABUNA_SIGNATURE'] ?? '', getenv('ABUNA_WEBHOOK_SECRET'))) { http_response_code(400); exit; } $event = json_decode($rawBody, true); // Save the event before you answer, then handle it in the background. try { save_event($event); } catch (Throwable) { http_response_code(500); exit; } http_response_code(200); ``` Go: ```go // header is "t=1727600000,v1=", with a second v1 while a secret rotation overlaps. func verifyAbunaSignature(body []byte, header, secret string) bool { var timestamp string var signatures []string for _, part := range strings.Split(header, ",") { key, value, _ := strings.Cut(part, "=") switch key { case "t": timestamp = value case "v1": signatures = append(signatures, value) } } t, err := strconv.ParseInt(timestamp, 10, 64) if err != nil { return false } if age := time.Now().Unix() - t; age > 300 || age < -300 { return false } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(timestamp + ".")) mac.Write(body) expected := hex.EncodeToString(mac.Sum(nil)) for _, signature := range signatures { if hmac.Equal([]byte(signature), []byte(expected)) { return true } } return false } func handleAbunaWebhook(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil || !verifyAbunaSignature(body, r.Header.Get("X-Abuna-Signature"), os.Getenv("ABUNA_WEBHOOK_SECRET")) { http.Error(w, "bad signature", http.StatusBadRequest) return } var event map[string]any if err := json.Unmarshal(body, &event); err != nil { http.Error(w, "bad body", http.StatusBadRequest) return } // Save the event before you answer, then handle it in the background. if err := saveEvent(r.Context(), event); err != nil { http.Error(w, "try again", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } ``` > **Warning:** Sign the exact bytes Abuna sent. If your framework parses JSON first and you serialize it again, the signature won't match. ### Get the raw body in your framework In Express, `express.json()` replaces the body with parsed JSON. Use `express.raw({ type: "application/json" })` on the webhook route, so `req.body` is the bytes Abuna sent. **Express** ```javascript import express from "express"; const app = express(); // express.raw keeps the bytes. Mount it on the webhook route, before any express.json(). app.post("/webhooks/abuna", express.raw({ type: "application/json" }), async (req, res) => { if (!verifyAbunaSignature(req.body, req.get("X-Abuna-Signature"), process.env.ABUNA_WEBHOOK_SECRET)) { return res.sendStatus(400); } const event = JSON.parse(req.body); // Save the event before you answer, then handle it in the background. try { await saveEvent(event); } catch { return res.sendStatus(500); } res.sendStatus(200); }); app.listen(3000); ``` In Laravel, `$request->getContent()` returns the raw body. Pass it to the PHP function above. **Laravel** ```php getContent(); if (!verify_abuna_signature($rawBody, $request->header('X-Abuna-Signature', ''), config('services.abuna.webhook_secret'))) { abort(400); } $event = json_decode($rawBody, true); // Save the event before you answer, then handle it in the background. save_event($event); return response()->noContent(); }); ``` ## Respond with a 2xx A delivery succeeds when your server answers with a `2xx` status within 10 seconds. Up to 4 `307` or `308` redirects are followed, and each must meet the URL rules above. Any other answer fails, including a `301`, `302` or `303` redirect, a timeout or a connection error. A failed delivery is sent again for about a day, up to 10 attempts in all. If your server is down for less than that, you miss nothing. After that, the delivery is marked `failed`, and you can [redeliver it](https://abuna.app/docs/guides/webhooks.md#redeliver). To handle events safely: - Save the event first, for example in your database, then answer `2xx`. After a `2xx`, Abuna doesn't send that delivery again. If the save fails, answer `500`, and the delivery comes again later. Do slow work in the background after you answer, so you stay inside the 10 seconds. - Record each event's `id` and skip one you've already handled. The same event can arrive more than once. - Don't rely on order. An older event can arrive after a newer one. See [Handle events out of order](https://abuna.app/docs/guides/webhooks.md#out-of-order). ## Handle events out of order Event IDs sort in the order the events happened, so compare them as plain strings to tell which came first. Don't use `created_at`: it is in whole seconds, and the events of one change often share it. For example, a payment produces `invoice.paid` and `subscription.recovered` together, in that order. See [Event order](https://abuna.app/docs/api/events.md#order) for each change. Every event about a subscription carries the whole subscription in `data.subscription`, as it stands right after that event. You don't need to replay events in order to know a subscription's state: 1. Store, for each subscription, the ID of the newest event you applied to it. 2. When an event arrives, compare its `id` with the stored one. If it is newer, save `data.subscription` as the subscription's state and store the new ID. 3. If it is older, a newer state is already saved. Keep the stored state, and still do any one-off work the event calls for, like a receipt. Give the customer access while `data.subscription.status` is `trialing`, `active` or `past_due`, and take it away at `canceled`. A renewal still unpaid when the paid period ends is `past_due` until the customer pays it or the days to pay run out. ## Event types - `session.completed`: a customer finished a [session](https://abuna.app/docs/guides/sessions.md). `data.type` says which: for `checkout`, the first payment went through or a free trial started, and `data.subscription_id` is the new subscription. `data.metadata` is what you passed when you created it. - `session.expired`: a session ran out or you expired it, without completing. - `subscription.created`: a subscription started, with `trialing` for a free trial or `pending` while waiting for its first payment. - `subscription.paid`: the first payment went through. After a free trial, that is the first invoice. A trial start sends `subscription.created` only: grant access while `data.subscription.status` is `trialing`. Use `invoice.paid` to track money collected. - `subscription.trial_ending`: the trial ends soon, at your app's normal renewal reminder lead time. See [Free trials](https://abuna.app/docs/guides/trials.md). - `subscription.renewed`: the next billing period and its invoice were issued, 3 days before the paid period ends by default. The new period starts on the renewal date. - `subscription.past_due`: the paid period ended and the renewal is unpaid. A renewal paid before the period ends never sends it. The customer keeps access until the subscription ends. - `subscription.recovered`: the unpaid renewal was paid, and the subscription is `active` again. It also comes when a payment that arrives after a cancel for non-payment brings the subscription back. - `subscription.updated`: a cancel at the end of the paid period was scheduled or undone, the price changed, a downgrade or an upgrade at the next renewal was scheduled or undone, or an upgrade waiting for payment lapsed. `data.cancel_at` is when it ends, or `null`, and `data.cancel_at_period_end` is `true` while a cancel is scheduled. `data.price_id` is the current price, and `data.change` says what changed about the price. `data.updated_by` is `merchant` or `customer`. - `plan_offer.created`, `plan_offer.confirmed`, `plan_offer.canceled`, `plan_offer.expired`: a plan change waiting for the customer was created, accepted, withdrawn or replaced, or ran out. A checkout makes one, and emails the customer its link, when a returning customer picks another price of the product they subscribe to. - `subscription.canceled`: the subscription ended, including at the end of the paid period. `data.reason` is `merchant`, `customer`, `non_payment`, or `checkout_expired`. - `invoice.created`: an invoice was issued for a billing period. `data.kind` is `plan_change` for the first period of an upgrade. - `invoice.paid`: an invoice was paid. `data.payment` is the payment, with what the customer was charged in FCFA and the exchange rate when the invoice was in another currency. - `invoice.payment_failed`: a payment on an invoice didn't go through. `data.payment` is the payment that failed. - `price_change.scheduled`, `price_change.canceled`, `price_change.applied`: a new amount for a price was scheduled, canceled or replaced, or took effect on its day. `data.reason` on `price_change.canceled` is `merchant` or `replaced`. - `customer.updated`: a customer's name, email, phone number, or metadata changed, or their first payment gave them a phone number. `data.updated_by` is `merchant` or `customer`. - `customer.deleted`: you deleted a customer. It follows the `subscription.canceled` event of each subscription that ended. `data.deleted_by` is `merchant`. - `customer.updates_changed`: a customer's Telegram or WhatsApp status changed, for example when they turned it on or stopped it. `data.channel` is `telegram` or `whatsapp`, `data.status` is the status now and `data.previous_status` the one before. Subscription, invoice, and plan offer events carry the subscription's [metadata](https://abuna.app/docs/api/subscriptions.md#metadata). Session events carry the session's own `metadata`, not the subscription's. Pass metadata on every session you create so its events can identify your customer. Without it, session events carry `{}`. Every event is also kept in your app's event list, even when no webhook URL is set or your URL doesn't receive its type. See [Events](https://abuna.app/docs/api/events.md) for each type's `data`. Every event whose `data` has a `subscription_id` also has `data.subscription`, the full [subscription object](https://abuna.app/docs/api/subscriptions.md#object) as it stands right after the event. ## Send a test event To check your webhook URL, click **Send test event** in the dashboard, or call `POST /v1/apps/{appID}/webhooks/test`. Abuna sends one signed `ping` event right away and tells you how your server answered, whatever events you chose. It goes once, and it isn't saved as an event or a delivery. **POST /v1/apps/{appID}/webhooks/test** cURL: ```bash curl -X POST https://api.abuna.app/v1/apps/8ddhXCDW/webhooks/test \ -H "Authorization: Bearer sk_test_..." ``` Node.js: ```javascript const response = await fetch("https://api.abuna.app/v1/apps/8ddhXCDW/webhooks/test", { method: "POST", headers: { Authorization: "Bearer sk_test_..." }, }); const result = await response.json(); ``` **Response** ```json { "delivered": true, "response_status": 200, "error": null } ``` `delivered` is `true` when your server answered `2xx`. If no answer came back, `response_status` is `null` and `error` says why. You can send 10 test events per minute. Without a webhook URL, the call returns `422` with code `webhook_url_missing`. **The ping your server receives** ```json { "id": "01J9ZQ8E1F2G3H4J5K6M7N8P9Q", "type": "ping", "environment": "test", "created_at": 1727600000, "data": { "message": "A test event sent from the Abuna dashboard." } } ``` ## Redeliver failed events Once your server is fixed, list failed deliveries with `GET /v1/apps/{appID}/webhooks?status=failed`, then redeliver each one with `POST /v1/apps/{appID}/webhooks/{id}/redeliver`. A redelivery sends the same body again, as a new delivery, to your current webhook URL. It's signed with your current secret and sent again on failure like any other. **Redeliver failed events** cURL: ```bash curl "https://api.abuna.app/v1/apps/8ddhXCDW/webhooks?status=failed&limit=100" \ -H "Authorization: Bearer sk_test_..." curl -X POST https://api.abuna.app/v1/apps/8ddhXCDW/webhooks/R3vH6sLd/redeliver \ -H "Authorization: Bearer sk_test_..." ``` Node.js: ```javascript const base = "https://api.abuna.app/v1/apps/8ddhXCDW/webhooks"; const headers = { Authorization: "Bearer sk_test_..." }; const failed = await (await fetch(base + "?status=failed&limit=100", { headers })).json(); for (const delivery of failed.items) { await fetch(base + "/" + delivery.id + "/redeliver", { method: "POST", headers }); } ``` See [Webhook deliveries](https://abuna.app/docs/api/webhook-deliveries.md) for the fields on each delivery. To find events your server never handled, whatever their delivery status, page through the event list. See [Catch up on missed events](https://abuna.app/docs/api/events.md#catch-up). ## Rotate the signing secret If your signing secret leaks, a team owner can click **Rotate secret** on the **Webhooks** page. A secret key can't rotate it. Abuna shows the new secret once and signs with it right away. For the next 24 hours, `X-Abuna-Signature` carries a second `v1`, signed with the old secret. Put the new secret on your server within that time. If you rotate again inside the 24 hours, the secret you just replaced becomes the old one, and the one before it stops working.