Webhooks
Receive signed notifications (Standard Webhooks) when something changes in Billora: event catalog, payload format, signature verification, retries, testing and the management API.
Webhooks tell your system the moment something happens in your organization: an invoice is issued or paid, a customer is created, an expense is confirmed… Billora sends a JSON POST to the URL you configure, signed according to the open Standard Webhooks specification.
Setup
Create an endpoint in the app (Settings → Webhooks) or through the API (POST /webhooks/endpoints/, see the management API). Each endpoint has:
| Field | Description |
|---|---|
url | Your server's URL. It must be HTTPS and publicly reachable (private, loopback and reserved IPs are rejected). |
events | List of event types you want to receive, or ["*"] for all (except clinic events, which must be listed explicitly). |
description | Text to identify it. |
enabled | Whether it is active. |
When you create it, Billora generates a signing secret shaped whsec_… and returns it in the response (you can also send your own in secret: whsec_ + base64 of 24 to 64 bytes). Store it on your server (for example in BILLORA_WEBHOOK_SECRET): you need it to verify signatures. Owners and admins can reveal it again or rotate it.
The number of endpoints depends on the plan: beyond it, creation answers 402 quota_exceeded.
curl https://api.billora.app/api/v1/webhooks/endpoints/ \
-H "Authorization: Bearer $BILLORA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://erp.ejemplo.es/webhooks/billora",
"events": ["invoice.issued", "invoice.paid", "customer.created", "customer.updated"],
"description": "ERP production"
}'Event catalog
| Event | Sent when… |
|---|---|
invoice.created | An invoice is created (usually a draft; also corrective invoices and those generated by recurring invoices). |
invoice.updated | A relevant field changes (amounts, dates, notes, status, balance, number…). Includes previous_attributes. |
invoice.issued | The invoice goes from draft to issued (final number and VeriFactu record if applicable). Once per invoice. |
invoice.sent | An invoice is emailed (may repeat if resent). |
invoice.paid | An invoice becomes paid (balance 0). |
invoice.partially_paid | An invoice becomes partially paid (first partial payment; later ones emit payment.created and invoice.updated). |
invoice.overdue | An issued invoice passes its due date unpaid. |
invoice.cancelled | An invoice is cancelled. |
invoice.rectified | A corrective invoice is issued against this invoice. data.object is the corrected invoice and data.rectifying_invoice the corrective one. |
invoice.deleted | A draft invoice is deleted. |
invoice.verifactu.accepted | The tax agency accepts the invoice's VeriFactu record (also “accepted with errors”). |
invoice.verifactu.rejected | The tax agency rejects the invoice's VeriFactu record. |
quote.created / quote.updated / quote.deleted | Quote lifecycle. |
quote.accepted / quote.rejected | A quote is marked as accepted or rejected. |
proforma.created / proforma.updated / proforma.deleted | Proforma lifecycle. |
credit_note.created / credit_note.updated / credit_note.deleted | Credit notes (previous system). |
external_invoice.created / .updated / .deleted | Third-party and self-billed invoices (they don't emit invoice.* events). |
customer.created / customer.updated / customer.deleted | Customers. |
supplier.created / supplier.updated / supplier.deleted | Suppliers. |
product.created / product.updated / product.deleted | Products and services. |
payment.created / payment.deleted | An invoice payment is recorded or deleted (manual, “mark as paid”, Stripe…). |
expense.created / expense.updated / expense.deleted | Expenses. |
expense.confirmed | An expense is confirmed (booked). |
expense.paid | An expense becomes paid. |
recurring_invoice.generated | A recurring invoice generates and issues an invoice. data.object is the generated invoice and data.recurring_invoice the template. |
case.created / case.updated | Cases. |
case.closed | A case is closed. |
case_file.created | A file is uploaded to a case. |
signature.sent / signature.viewed | A signature request is sent to the signer / the signer opens the document. |
signature.completed / signature.declined | A signer signs or declines a document. |
signature.expired / signature.cancelled | The request expires unsigned or is cancelled. |
purchase_order.created / .updated / .deleted | Purchase orders. |
purchase_order.sent / .received / .cancelled | The order is marked as sent, received or cancelled. |
vendor_bill.created / .updated / .deleted | Vendor bills. |
vendor_bill.approved / .paid / .cancelled | The vendor bill is approved (numbered), fully paid or cancelled. |
lead.created / .updated / .deleted | CRM leads. |
lead.converted | A lead is converted (into a customer and, optionally, a deal). |
deal.created / .updated / .deleted | CRM deals. |
deal.won / deal.lost | A deal is won or lost. |
booking.created / .updated / .cancelled / .deleted | Agenda bookings. data.object excludes confirmation_token, answers and patient_name. |
employee.created / .updated / .terminated / .deleted | HR employees. data.object excludes iban, ss_number, dni_nie and photo (also from previous_attributes). |
leave_request.created / .approved / .rejected / .cancelled | Leave requests. |
import.completed / import.failed | An import finishes (completed or completed_with_errors) or fails. No preview_data. |
patient.created / patient.deleted | Clinic (explicit subscription, see below): a patient is created or deleted. |
episode.created / episode.completed | Clinic (explicit subscription): an episode is created or completed. |
webhook.test | Only from the “Send test” action (delivered even if the endpoint isn't subscribed or enabled). |
The full, current list is also available at GET /webhooks/event-types/. We may add new events at any time (not a breaking change): if you subscribe to * (which includes future ones), ignore types you don't know.
Clinic events
Events carrying health data (patient.created, patient.deleted, episode.created and episode.completed) have explicit_subscription: true in the catalog: the * wildcard does not include them; list them one by one (["*", "patient.created"] is valid). Their data.object only carries identifiers, never clinical data:
patient:id,reference,is_active,created_at,updated_at.episode:id,reference,patient,practitioner,status,is_signed,signed_at,date,created_at,updated_at.
There is no patient.updated (it would expose previous values). If you need the details, read them through the API with a clinica:read key, which is audited.
- One change can emit several events: paying an invoice in full emits
payment.created,invoice.updatedandinvoice.paid. - Within one operation, several
*.updatedof the same object are merged into one, and no*.updatedis emitted right after its*.created. - Events are only recorded if, at that moment, at least one enabled endpoint is subscribed to that type: there is no history of events without subscribers.
Payload format
POST /webhooks/billora HTTP/1.1
Host: erp.ejemplo.es
Content-Type: application/json
User-Agent: Billora-Webhooks/1.0
webhook-id: evt_01JBQ9C7Y5M3K8D2W4R6T0V9XA
webhook-timestamp: 1793527200
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4={
"id": "evt_01JBQ9C7Y5M3K8D2W4R6T0V9XA",
"type": "invoice.paid",
"created_at": "2026-11-01T10:00:00Z",
"api_version": "2026-11-01",
"organization_id": 5,
"data": {
"object": {
"id": 5120,
"number": "F-2026-0042",
"status": "paid",
"customer": { "id": 318, "legal_name": "Talleres Martín S.L.", "vat_id": "B12345674" },
"issue_date": "2026-11-01",
"total": "1028.50",
"balance": "0.00"
}
}
}| Field | Description |
|---|---|
id | Unique event id (evt_…). Same value as the webhook-id header, identical on every retry and on all your endpoints. |
type | Event type. |
created_at | When it happened. |
api_version | Version of the event format. |
organization_id | Organization where it happened. |
data.object | Full representation of the resource after the operation, the same the API returns in its detail (GET /invoices/{id}/…), with amounts as decimal strings. It doesn't include temporary signed URLs (attachment_url, download_url…). |
data.previous_attributes | Only on *.updated events: previous values of the fields that changed (relations as ids). |
On *.deleted events, data.object is the resource's last representation with "deleted": true. Events are created in the same transaction as the change: if the operation is rolled back, nothing is sent.
Verifying the signature
Always verify the signature before processing a webhook: it proves Billora sent it and nobody altered it.
- Read the raw body (the exact bytes received) before parsing JSON.
- Build the signed content:
{webhook-id}.{webhook-timestamp}.{body}. - Compute
HMAC-SHA256with the key = base64 decoding of the part of the secret afterwhsec_, and base64-encode the result. - The
webhook-signatureheader holds one or more space-separated signatures shapedv1,<signature>. The webhook is valid if any of them matches (compare in constant time). - Reject the message if
webhook-timestampis more than 5 minutes away from your current time (protection against replays).
Endpoints created before November 2026 may have a user-chosen secret without the whsec_ prefix (the API flags them with "secret_format": "legacy"): then the HMAC key is the secret's raw UTF-8 bytes. The examples handle both formats; rotating the secret moves it to the whsec_ format.
import crypto from "node:crypto";
import express from "express";
const RAW_SECRET = process.env.BILLORA_WEBHOOK_SECRET; // whsec_…
const SECRET = RAW_SECRET.startsWith("whsec_")
? Buffer.from(RAW_SECRET.slice("whsec_".length), "base64")
: Buffer.from(RAW_SECRET, "utf8"); // legacy secrets
const TOLERANCE_SECONDS = 5 * 60;
export function verifyBilloraWebhook(rawBody, headers) {
const id = headers["webhook-id"];
const timestamp = headers["webhook-timestamp"];
const signatures = headers["webhook-signature"];
if (!id || !timestamp || !signatures) throw new Error("Missing signature headers");
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) throw new Error("Timestamp outside tolerance");
const expected = crypto.createHmac("sha256", SECRET).update(`${id}.${timestamp}.${rawBody}`).digest();
const valid = signatures.split(" ").some((entry) => {
const [version, signature] = entry.split(",");
if (version !== "v1" || !signature) return false;
const received = Buffer.from(signature, "base64");
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
});
if (!valid) throw new Error("Invalid signature");
return JSON.parse(rawBody);
}
const app = express();
// express.raw: we need the exact body, not re-serialized JSON.
app.post("/webhooks/billora", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = verifyBilloraWebhook(req.body.toString("utf8"), req.headers);
} catch (err) {
return res.status(400).send(err.message);
}
await enqueue(event); // store it and process it in the background
res.sendStatus(204); // answer fast (under 15 s)
});import base64, hashlib, hmac, json, os, time
from flask import Flask, abort, request
RAW_SECRET = os.environ["BILLORA_WEBHOOK_SECRET"] # whsec_…
SECRET = (base64.b64decode(RAW_SECRET.removeprefix("whsec_")) if RAW_SECRET.startswith("whsec_")
else RAW_SECRET.encode("utf-8")) # legacy secrets
TOLERANCE_SECONDS = 5 * 60
def verify_billora_webhook(raw_body: bytes, headers) -> dict:
msg_id = headers.get("webhook-id")
timestamp = headers.get("webhook-timestamp")
signatures = headers.get("webhook-signature")
if not (msg_id and timestamp and signatures):
raise ValueError("Missing signature headers")
if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
raise ValueError("Timestamp outside tolerance")
signed = f"{msg_id}.{timestamp}.".encode() + raw_body
expected = base64.b64encode(hmac.new(SECRET, signed, hashlib.sha256).digest()).decode()
for entry in signatures.split(" "):
version, _, signature = entry.partition(",")
if version == "v1" and hmac.compare_digest(signature, expected):
return json.loads(raw_body)
raise ValueError("Invalid signature")
app = Flask(__name__)
@app.post("/webhooks/billora")
def billora_webhook():
try:
event = verify_billora_webhook(request.get_data(), request.headers)
except ValueError as exc:
abort(400, str(exc))
enqueue(event) # store it and process it in the background
return "", 204<?php
function verifyBilloraWebhook(string $rawBody, array $headers, string $secret, int $tolerance = 300): array {
$headers = array_change_key_case($headers, CASE_LOWER);
$id = $headers['webhook-id'] ?? '';
$timestamp = $headers['webhook-timestamp'] ?? '';
$signatures = $headers['webhook-signature'] ?? '';
if ($id === '' || $timestamp === '' || $signatures === '') {
throw new RuntimeException('Missing signature headers');
}
if (abs(time() - (int) $timestamp) > $tolerance) {
throw new RuntimeException('Timestamp outside tolerance');
}
$key = str_starts_with($secret, 'whsec_')
? base64_decode(substr($secret, strlen('whsec_')), true)
: $secret; // legacy secrets
$expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$rawBody}", $key, true));
foreach (explode(' ', $signatures) as $entry) {
[$version, $signature] = array_pad(explode(',', $entry, 2), 2, '');
if ($version === 'v1' && hash_equals($expected, $signature)) {
return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
}
}
throw new RuntimeException('Invalid signature');
}
$rawBody = file_get_contents('php://input');
try {
$event = verifyBilloraWebhook($rawBody, getallheaders(), getenv('BILLORA_WEBHOOK_SECRET'));
} catch (Throwable $e) {
http_response_code(400);
exit($e->getMessage());
}
enqueue($event); // store it and process it in the background
http_response_code(204);Standard Webhooks libraries
Since Billora follows the standard, you can also use the official Standard Webhooks libraries (standardwebhooks on npm and PyPI, standard-webhooks/standard-webhooks on Packagist) or Svix's verifier: new Webhook(secret).verify(rawBody, headers).
To test your implementation, use the standard's test vector: secret whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw, id msg_p5jXN8AQM9LWM0D4loKWxJek, timestamp 1614265330 and body {"test": 2432232314} produce the signature v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE= (disable the timestamp check in that test).
The most common mistake
Verifying against JSON that was parsed and serialized again. Any whitespace or key-order change breaks the signature: always use the raw body.
Secret rotation
You can rotate the secret at any time (POST /webhooks/endpoints/{id}/rotate-secret/). For the next 24 hours Billora signs with the new secret and the previous one, so the header carries two signatures (v1,… v1,…). The verification code above already accepts either: update BILLORA_WEBHOOK_SECRET calmly within that window.
Responding and retries
- A delivery is successful if your endpoint answers with any
2xxstatus within 15 seconds (5 s to connect). Answer2xxto events you ignore, too. - Redirects are not followed: a
3xxcounts as a failure. Configure the final URL. - Answer right away and process later (queue, background job). Don't make slow calls before answering.
- If the response isn't
2xx, times out or the connection fails, Billora retries with these delays after the previous attempt:
| Attempt | Delay |
|---|---|
| 1 | Immediately |
| 2 | 5 seconds |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 5 hours |
| 7 | 10 hours |
| 8 | 10 hours |
That is 8 attempts over about 27 hours; after that the delivery is failed. Delays are minimums: a job checks pending deliveries every minute, so a retry may leave up to a minute late. Each attempt has a new webhook-timestamp and signature, but the same webhook-id.
Delivery statuses: pending, retrying, succeeded, failed and cancelled.
If your server is overloaded, answer 429 or 503 with a Retry-After header (in seconds): Billora waits at least that long before the next attempt (up to 10 hours).
Automatic disabling
- If your endpoint answers
410 Gone, Billora disables it immediately (use it to unsubscribe). - If an endpoint keeps failing for 5 days without a single successful delivery, it is disabled (any successful delivery resets the count).
- In both cases owners and admins are emailed, the endpoint gets a
disabled_reason(goneorfailing) and its pending deliveries are cancelled. Re-enable it once fixed (POST /webhooks/endpoints/{id}/enable/) and recover what was missed withrecover.
Idempotency and ordering
- Billora may deliver the same event more than once (for example if your server processed it but the response got lost). Store processed
webhook-ids and discard repeats. - Ordering is not guaranteed: an
invoice.paidcan arrive before theinvoice.issuedof the same invoice if the latter had to be retried.data.objectreflects the state after the operation that produced the event; if you need the latest state, read the resource again through the API.
-- Example: deduplication table
CREATE TABLE billora_webhook_events (
event_id text PRIMARY KEY, -- webhook-id
type text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now()
);
-- INSERT … ON CONFLICT (event_id) DO NOTHING → no row inserted means already processed.Testing and redelivery
| Action | Endpoint |
|---|---|
Send a test event (webhook.test) and see the result immediately (status, duration, response body). Not retried and doesn't affect the endpoint's health | POST /webhooks/endpoints/{id}/test/ |
See the events of the last 30 days (filters type, object_type, object_id, created_after, created_before) and the exact body sent | GET /webhooks/events/ · GET /webhooks/events/{id}/ |
| See deliveries and their attempts (status, response time, error) | GET /webhooks/deliveries/?endpoint=&event=&status=&type= · GET /webhooks/deliveries/{id}/ |
Redeliver one delivery now (same webhook-id, new signature) | POST /webhooks/deliveries/{id}/redeliver/ |
Redeliver every failed delivery since a date ({"since": "2026-10-30T00:00:00Z"}, optionally until; at most 30 days back) | POST /webhooks/endpoints/{id}/recover/ |
To develop locally, expose your server through an HTTPS tunnel (for example ngrok or Cloudflare Tunnel), create a test endpoint in your test organization and use “Send test”. Events, deliveries and attempts are kept for 30 days.
Security
- Use HTTPS with a valid certificate;
http://URLs are not accepted. - Verify the signature and timestamp on every request; don't trust the source IP. Billora doesn't publish a fixed range of outgoing IPs: the signature is the authentication mechanism.
- URLs with user and password,
localhost, internal domains (.local,.internal…) or resolving to private, loopback, link-local (including169.254.169.254), CGNAT or reserved addresses are rejected when configured and on every delivery. The connection is opened to the validated IP, so a DNS change can't reach internal networks. - Don't put secrets in the endpoint URL (it shows up in delivery logs).
- Treat the event content as data: if you need a resource's definitive state (for example before fulfilling an order), read it again through the API.
Management API
Requires webhooks:read to read and webhooks:write for everything else (including revealing the secret). In the app, any member can read endpoints and deliveries; creating, editing, testing, rotating, revealing the secret and redelivering is reserved to owners and admins.
| Method | Path | Description |
|---|---|---|
| GET | /webhooks/endpoints/ | List endpoints. |
| POST | /webhooks/endpoints/ | Create an endpoint (returns the secret). |
| GET | /webhooks/endpoints/{id}/ | Read an endpoint. |
| PATCH | /webhooks/endpoints/{id}/ | Change URL, events, description or status. |
| DELETE | /webhooks/endpoints/{id}/ | Delete an endpoint. |
| POST | /webhooks/endpoints/{id}/test/ | Synchronous test delivery. |
| GET | /webhooks/endpoints/{id}/secret/ | Reveal the secret. |
| POST | /webhooks/endpoints/{id}/rotate-secret/ | Rotate the secret (the old one keeps signing for 24 h). |
| POST | /webhooks/endpoints/{id}/enable/ · /disable/ | Enable or disable. |
| POST | /webhooks/endpoints/{id}/recover/ | Requeue failed or cancelled deliveries in a range (since, until). 202 with {"recovered": n}; 409 if the endpoint is disabled. |
| GET | /webhooks/event-types/ | Event catalog. |
| GET | /webhooks/events/ · /webhooks/events/{id}/ | Sent events. |
| GET | /webhooks/deliveries/ · /webhooks/deliveries/{id}/ | Deliveries and their attempts. |
| POST | /webhooks/deliveries/{id}/redeliver/ | Redeliver a delivery. |
Full schemas are in the API reference.
