Webhooks
Webhooks tell your system when something happens to a code, so you do not have to poll.
| Event | Sent when |
|---|---|
code.redeemed | A member redeemed a code in the shop. Holds the selection with prices, and the delivery address the member entered. A line with fulfilledByPartner: true is delivered by you, not shipped by us. |
code.shipped | The order for a redeemed code shipped. Holds carrier and tracking. A new package with a new tracking number sends a new event. |
code.deactivated | A code was deactivated. Sent once, not again when the deactivation is repeated. |
Tracking does not exist when a code is redeemed, which is why redemption and shipment are two events.
Everything in an event is also available from GET /v1/codes/{code}.
Register an endpoint
POST /v1/webhook-endpoints - scope webhooks:manage. The endpoint belongs to the environment of
the host you call; a sandbox endpoint only receives sandbox events.
{
"url": "https://partner.example.com/webhooks/b2b",
"events": ["code.redeemed", "code.shipped", "code.deactivated"],
"description": "Member system"
}
{
"id": 42,
"url": "https://partner.example.com/webhooks/b2b",
"events": ["code.redeemed", "code.shipped", "code.deactivated"],
"description": "Member system",
"secret": "<signing secret>",
"createdAt": "2026-10-01T08:00:00Z"
}
The signing secret is shown once, in this response. Store it where your receiver can read it.
Rules for url: it must use https, it must not point to a private or local address or to a B2B
Group host, and it can be at most 500 characters. events must contain known event types. A broken
rule answers 400 validation_error with a message that says which.
curl
curl -s https://api-sandbox.b2bgroup.dk/v1/webhook-endpoints \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{ "url": "https://partner.example.com/webhooks/b2b", "events": ["code.redeemed", "code.shipped", "code.deactivated"] }'
C#
var response = await http.PostAsJsonAsync("/v1/webhook-endpoints", new
{
url = "https://partner.example.com/webhooks/b2b",
events = new[] { "code.redeemed", "code.shipped", "code.deactivated" },
});
response.EnsureSuccessStatusCode();
var endpoint = await response.Content.ReadFromJsonAsync<JsonElement>();
var signingSecret = endpoint.GetProperty("secret").GetString(); // Store it now - it is not shown again.
Node
const response = await fetch(`${baseUrl}/v1/webhook-endpoints`, {
method: 'POST',
headers,
body: JSON.stringify({
url: 'https://partner.example.com/webhooks/b2b',
events: ['code.redeemed', 'code.shipped', 'code.deactivated'],
}),
});
const { id, secret } = await response.json(); // Store the secret now - it is not shown again.
Python
response = session.post(f"{BASE_URL}/v1/webhook-endpoints", json={
"url": "https://partner.example.com/webhooks/b2b",
"events": ["code.redeemed", "code.shipped", "code.deactivated"],
})
response.raise_for_status()
signing_secret = response.json()["secret"] # Store it now - it is not shown again.
Other endpoint routes
All require webhooks:manage.
| Route | Does |
|---|---|
GET /v1/webhook-endpoints | Lists your endpoints in this environment as { items }, newest first. Secrets are never included. |
DELETE /v1/webhook-endpoints/{id} | Removes the endpoint. Answers { id }. |
POST /v1/webhook-endpoints/{id}/rotate-secret | Creates a new secret, shown once, and answers { secret, previousExpiresAt }. |
POST /v1/webhook-endpoints/{id}/test | Sends a code.redeemed test event with "test": true. |
GET /v1/webhook-endpoints/{id}/deliveries?cursor=&pageSize= | Delivery attempts, newest first, as { items, nextCursor }. pageSize is 1 to 200; any other value answers 400 validation_error. |
POST /v1/webhook-endpoints/{id}/deliveries/{deliveryId}/retry | Queues a new attempt for a failed or abandoned delivery. Any other status answers 409 delivery_not_retryable. |
An endpoint id that does not exist, or belongs to the other environment, answers 404 not_found.
What we send
We send POST <your url> with a JSON body and these headers:
| Header | Value |
|---|---|
X-B2B-Event-Id | The event id, identical to id in the body. |
X-B2B-Event-Type | The event type, identical to type in the body. |
X-B2B-Signature | t=<unix timestamp>,v1=<signature> - see below. |
X-B2B-Version | The contract version the body follows, for example 2026-10-01. |
The body always has the same frame:
{
"id": "evt_01J9Q6X0Z8N4C5R7T2V9W3Y1B0",
"type": "code.redeemed",
"createdAt": "2026-11-03T14:22:10Z",
"environment": "production",
"test": false,
"data": {
"code": "ABC-7K3Q-M8ZP",
"externalMemberRef": "M-482913",
"campaign": "welcome-2027",
"redeemedAt": "2026-11-03T14:22:10Z",
"orderId": 5511,
"selection": [ { "sku": "BBP-1234", "name": "Softshell jacket", "variant": "M", "quantity": 1, "fulfilledByPartner": false, "unitPriceDkk": 2400.00, "lineTotalDkk": 2400.00 } ],
"totalDkk": 2400.00,
"delivery": { "name": "...", "address": "...", "zip": "6760", "city": "Ribe", "country": "DK", "email": "...", "phone": "..." },
"version": 2,
"tier": 5
}
}
Every line in selection has fulfilledByPartner. It is true when you, the partner, deliver the
item yourself, for example a stay in a holiday home: nothing is shipped from our warehouse for that
line, so a code.shipped event only follows if the order also holds lines we ship. When a
redemption contains such a line, we also send an email to the addresses set up for you with us, so
the people who handle the delivery hear about it even if your webhook receiver is down. Ask your
contact at B2B Group to set or change those addresses.
Every line also carries the price of the gift: unitPriceDkk is the price of one unit in DKK
including VAT, as set up in your shop when the code was redeemed, and lineTotalDkk is that price
multiplied by quantity. data.totalDkk is the sum over the order. The prices are frozen at
redemption, so they match redemption on the code object for as long as the code exists. A gift
without a price in your shop has no unitPriceDkk and lineTotalDkk, and an order where no gift
has a price has no totalDkk.
data.tier is the code's tier, the same value as tier on the code object. It is the tier you set
when you issued or imported the code, or 1 if you did not set one. See "Tiers" in Codes.
data for the other events:
code.shipped:{ code, externalMemberRef, orderId, shipment: { carrier, trackingNumber, trackingUrl, shippedAt }, version, tier }code.deactivated:{ code, externalMemberRef, reason, deactivatedAt, version, tier }
The full schemas are in the OpenAPI document under webhooks.
Answering, retries and duplicates
- Answer with any 2xx status within 10 seconds. Do the real work afterwards, for example from a queue.
- Anything else counts as a failure: another status, a timeout, a failed connection, or a redirect (3xx) - redirects are not followed.
- After a failure we retry after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 12 hours, and
then every 12 hours. After 3 days the delivery is
abandoned. You can retry it yourself with the retry route above. - The same event can arrive more than once, and events can arrive out of order. Store the event
id and ignore an id you have already processed. To handle the order, use
data.version: it is the code's version after the change and increases by one every time the code changes. Ignore an event whose version is not higher than the one you have stored, and store the new version when you apply one.createdAtis still in every event and tells you when it happened, but two changes can share the same timestamp, so do not use it to decide which is newer. - Delivery statuses are
pending,sending,delivered,failedandabandoned.
Verify the signature
Always verify the signature before you trust the body.
- Read the raw request body as bytes, before any JSON parsing.
- Split
X-B2B-Signatureon,. Thetvalue is a unix timestamp; eachv1value is a signature. - Reject the request if
tis more than 5 minutes from your clock. - Compute HMAC-SHA256 of
t + "." + raw body, keyed with your signing secret used as UTF-8 text, and hex-encode it in lowercase. - Accept the request if it equals any of the
v1values. Compare in constant time.
After you rotate the secret, the previous secret stays valid for 24 hours (previousExpiresAt). In
that window every delivery carries two v1 values, the newest first:
t=1793715730,v1=<signed with new secret>,v1=<signed with old secret>. Checking against your
current secret and accepting any match makes rotation seamless.
C#
using System.Security.Cryptography;
using System.Text;
static bool IsValidSignature(string header, byte[] rawBody, string secret, TimeSpan tolerance)
{
string? timestamp = null;
var signatures = new List<string>();
foreach (var part in header.Split(','))
{
var pair = part.Split('=', 2);
if (pair.Length != 2) continue;
if (pair[0] == "t") timestamp = pair[1];
else if (pair[0] == "v1") signatures.Add(pair[1]);
}
if (!long.TryParse(timestamp, out var unix)
|| Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - unix) > tolerance.TotalSeconds)
{
return false;
}
var signedPayload = Encoding.UTF8.GetBytes(timestamp + ".").Concat(rawBody).ToArray();
var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signedPayload);
return signatures.Any(signature =>
{
try { return CryptographicOperations.FixedTimeEquals(expected, Convert.FromHexString(signature)); }
catch (FormatException) { return false; }
});
}
// ASP.NET Core minimal API receiver.
app.MapPost("/webhooks/b2b", async (HttpRequest request) =>
{
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer);
var rawBody = buffer.ToArray();
if (!IsValidSignature(request.Headers["X-B2B-Signature"].ToString(), rawBody, signingSecret, TimeSpan.FromMinutes(5)))
{
return Results.Unauthorized();
}
var eventId = request.Headers["X-B2B-Event-Id"].ToString();
// Skip eventId if you have processed it before; otherwise queue the event and answer quickly.
return Results.Ok();
});
Node
import crypto from 'node:crypto';
import express from 'express';
function isValidSignature(header, rawBody, secret, toleranceSeconds = 300) {
const parts = header.split(',').map((part) => part.split('='));
const timestamp = parts.find(([key]) => key === 't')?.[1];
const signatures = parts.filter(([key]) => key === 'v1').map(([, value]) => value);
if (!timestamp || Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;
const expected = crypto.createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest();
return signatures.some((signature) => {
const given = Buffer.from(signature, 'hex');
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
}
const app = express();
// express.raw keeps the body as bytes, exactly as we signed it.
app.post('/webhooks/b2b', express.raw({ type: 'application/json' }), (req, res) => {
if (!isValidSignature(req.get('X-B2B-Signature') ?? '', req.body, process.env.SIGNING_SECRET)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString('utf8'));
// Skip event.id if you have processed it before; otherwise queue the event and answer quickly.
res.sendStatus(200);
});
Python
import hashlib
import hmac
import time
from flask import Flask, request
def is_valid_signature(header: str, raw_body: bytes, secret: str, tolerance: int = 300) -> bool:
parts = [part.split("=", 1) for part in header.split(",") if "=" in part]
timestamp = next((value for key, value in parts if key == "t"), None)
signatures = [value for key, value in parts if key == "v1"]
if timestamp is None or not timestamp.isdigit() or abs(time.time() - int(timestamp)) > tolerance:
return False
expected = hmac.new(secret.encode("utf-8"), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, signature) for signature in signatures)
app = Flask(__name__)
@app.post("/webhooks/b2b")
def receive():
if not is_valid_signature(request.headers.get("X-B2B-Signature", ""), request.get_data(), SIGNING_SECRET):
return "", 401
event = request.get_json()
# Skip event["id"] if you have processed it before; otherwise queue the event and answer quickly.
return "", 200
curl: send a test event
curl -s -X POST https://api-sandbox.b2bgroup.dk/v1/webhook-endpoints/42/test \
-H "Authorization: Bearer $TOKEN"
The answer is { eventId, type, test }. Then check GET /v1/webhook-endpoints/{id}/deliveries (here
with id 42) to see the status your receiver answered.