Codes
A code is a gift code a member redeems in the shop. Every code belongs to your partner account and
to one environment; a code from another partner or from the other environment answers 404
code_not_found, exactly like a code that does not exist.
The examples below assume you already have a token. In C#, Node and Python they reuse the http,
headers and session objects from Authentication.
The code object
GET /v1/codes/{code}, the list, deactivation and the sandbox routes all answer with the same shape:
{
"code": "ABC-7K3Q-M8ZP",
"status": "used",
"valid": false,
"campaign": "welcome-2027",
"externalMemberRef": "M-482913",
"issuedAt": "2026-10-01T08:00:00Z",
"expiresAt": "2029-10-01T00:00:00Z",
"usedAt": "2026-11-03T14:22:10Z",
"deactivatedAt": null,
"redemption": {
"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": null, "phone": null },
"shipment": { "carrier": "GLS", "trackingNumber": "...", "trackingUrl": "...", "shippedAt": "2026-11-05T09:12:44Z" }
},
"version": 3,
"failedAttempts": 1,
"lastFailedAttemptAt": "2026-11-20T18:05:31Z",
"tier": 5
}
statusisactive,used,expiredordeactivated. When more than one applies, the first in this order wins:deactivated,used,expired,active.validistrueonly when the code can be redeemed now.redemptionisnulluntil the code is redeemed.deliveryis what the member typed when ordering: name, address, email and phone.shipmentisnulluntil the order has shipped, and holds the latest shipment after that.versionincreases by one every time the code changes. A new or imported code starts at 1, and each later change adds one: reactivation, deactivation, redemption and shipment. Ignore an event or response whoseversionis not higher than the one you have stored. That way an older answer or a webhook that arrives late never overwrites newer data.fulfilledByPartneron a line inselectionistruewhen you, the partner, deliver the item yourself, for example a stay in a holiday home. Nothing is shipped from our warehouse for that line, and the addresses set up for you with us also receive an email about it.falsefor items we ship.unitPriceDkkon a line inselectionis the price of one unit of the gift in DKK including VAT, as set up in your shop when the code was redeemed, andlineTotalDkkis that price multiplied byquantity.redemption.totalDkkis the sum oflineTotalDkkover the order. The prices are frozen at redemption: a later price change in the shop does not change them. A gift without a price in your shop has nounitPriceDkkandlineTotalDkk, and an order where no gift has a price has nototalDkk. The member never pays in the shop; the price is for your own records.failedAttemptscounts the redemption attempts on this code that were refused because the code was already used, expired or deactivated, andlastFailedAttemptAtis when the latest one happened (nullwhen there has been none). The counter is per code: an attempt with a code we do not know cannot be tied to a code and is not counted anywhere. A high count on a used code can mean a member is trying to redeem it again, or that the code has been shared. In the sandbox the automatic cleanup at 03:00 Danish time also resets these numbers.tieris the code's tier, which decides which gifts the code can be used for. See "Tiers" below.- All times are UTC in ISO 8601.
Tiers
Every gift in your shop has a tier, for example 1, 3 or 5. A code has a tier too, which you set when you issue or import the code. If you do not send a tier, the code gets tier 1.
A member can use several codes together for one gift, and then the tiers of those codes are added up. The sum must be at least the tier of the gift. A gift with tier 5 can therefore be chosen with one code with tier 5, or for example with five codes with tier 1.
If the codes do not cover the tier of the gift, the redemption is refused with insufficient_tier.
Your contact at B2B Group tells you which tier each gift has.
tieris a whole number from 1 to 100. You can send it onPOST /v1/codes/issue, as a top-level field onPOST /v1/codes/issue-batch, and on each entry inPOST /v1/codes/import.- A tier outside 1 to 100 answers 400
validation_errorwith the message'tier' must be an integer between 1 and 100., and nothing is issued or imported. tieris part of the code object and of thecode.redeemed,code.shippedandcode.deactivatedwebhooks.
Issue a code
POST /v1/codes/issue - scope codes:issue. All fields are optional.
{ "campaign": "welcome-2027", "externalMemberRef": "M-482913" }
Send expiresAt (ISO 8601, UTC) when you calculate the expiry yourself, for example from the
member's own agreement:
{ "campaign": "welcome-2027", "externalMemberRef": "M-482913", "expiresAt": "2027-12-31T23:59:59Z" }
Send tier when the code should cover gifts with a higher tier than 1 (see "Tiers" above):
{ "campaign": "welcome-2027", "externalMemberRef": "M-482913", "tier": 5 }
The answer is { code, expiresAt, valid, status, campaign, externalMemberRef, issuedAt, version, failedAttempts, tier }.
If you send expiresAt, that is the expiry; otherwise we set it from the validity agreed for the
campaign or your account. An expiresAt that is not in the future answers 400 validation_error.
A freshly issued code has no redemption and no failed attempts yet (failedAttempts is 0); those
appear on GET /v1/codes/{code} as the code is used. Without tier the code gets tier 1, and a
tier outside 1 to 100 answers 400 validation_error.
externalMemberRef is your own reference to the member. Use an id from your system, never a name or
an email address.
curl
curl -s https://api-sandbox.b2bgroup.dk/v1/codes/issue \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{ "campaign": "welcome-2027", "externalMemberRef": "M-482913" }'
C#
var response = await http.PostAsJsonAsync("/v1/codes/issue",
new { campaign = "welcome-2027", externalMemberRef = "M-482913" });
response.EnsureSuccessStatusCode();
var issued = await response.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine(issued.GetProperty("code").GetString());
Node
const response = await fetch(`${baseUrl}/v1/codes/issue`, {
method: 'POST',
headers,
body: JSON.stringify({ campaign: 'welcome-2027', externalMemberRef: 'M-482913' }),
});
const issued = await response.json();
console.log(issued.code);
Python
response = session.post(f"{BASE_URL}/v1/codes/issue",
json={"campaign": "welcome-2027", "externalMemberRef": "M-482913"})
response.raise_for_status()
print(response.json()["code"])
Issue codes in a batch
POST /v1/codes/issue-batch - scope codes:issue. Up to 500 codes per call. Send count for
anonymous codes, externalMemberRefs for one code per reference, or both. The optional top-level
expiresAt (ISO 8601, UTC) applies to every code in the call; without it we set the expiry from the
validity agreed for the campaign or your account. The optional top-level tier also applies to
every code in the call; without it the codes get tier 1.
{ "campaign": "welcome-2027", "externalMemberRefs": ["M-482913", "M-507264"] }
{ "campaign": "welcome-2027", "count": 25, "expiresAt": "2027-12-31T23:59:59Z", "tier": 5 }
{
"issued": [
{ "externalMemberRef": "M-482913", "code": "ABC-7K3Q-M8ZP", "expiresAt": "2029-10-01T00:00:00Z", "campaign": "welcome-2027", "issuedAt": "2026-10-01T08:00:00Z", "version": 1, "failedAttempts": 0, "tier": 1 },
{ "externalMemberRef": "M-507264", "code": "ABC-A7B3-9X2Y", "expiresAt": "2029-10-01T00:00:00Z", "campaign": "welcome-2027", "issuedAt": "2026-10-01T08:00:00Z", "version": 1, "failedAttempts": 0, "tier": 1 }
]
}
A call with neither count nor externalMemberRefs, with more than 500 codes, with an
expiresAt that is not in the future, or with a tier outside 1 to 100, answers 400
validation_error.
Get a code
GET /v1/codes/{code} - scope codes:read. The full picture described above. For a quick check of
status and validity only, use GET /v1/codes/{code}/status, which answers
{ code, status, valid, expiresAt, usedAt }.
curl
curl -s https://api-sandbox.b2bgroup.dk/v1/codes/ABC-7K3Q-M8ZP -H "Authorization: Bearer $TOKEN"
C#
var response = await http.GetAsync($"/v1/codes/{Uri.EscapeDataString(code)}");
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// error: code_not_found
}
var detail = await response.Content.ReadFromJsonAsync<JsonElement>();
Node
const response = await fetch(`${baseUrl}/v1/codes/${encodeURIComponent(code)}`, { headers });
if (response.status === 404) { /* error: code_not_found */ }
const detail = await response.json();
Python
response = session.get(f"{BASE_URL}/v1/codes/{code}")
if response.status_code == 404:
pass # error: code_not_found
detail = response.json()
List codes (daily pull)
GET /v1/codes?status=&campaign=&externalMemberRef=&updatedSince=&cursor=&pageSize= - scope codes:read. Returns
{ items, nextCursor } where every item has the shape of the code object.
| Parameter | Meaning |
|---|---|
status | active, used, expired or deactivated. |
campaign | Only codes in this campaign. |
externalMemberRef | Only codes registered on this reference, exact match, at most 100 characters. See "Look up a member's codes" below. |
updatedSince | Only codes whose latest change (issued, used, shipped or deactivated) is at or after this UTC time, ISO 8601. |
pageSize | 1 to 500. |
cursor | The nextCursor from the previous page. Treat it as an opaque string. |
The list is ordered by the latest change. Following nextCursor until it is null never skips a code
and never returns the same code twice within one pull. An invalid status, cursor, pageSize or
updatedSince, or an externalMemberRef longer than 100 characters, answers 400 validation_error.
To pull changes once a day: remember when the previous run started, pass that time as
updatedSince, and follow the cursor to the end.
curl
curl -s "https://api-sandbox.b2bgroup.dk/v1/codes?updatedSince=2026-11-02T00:00:00Z&pageSize=500" \
-H "Authorization: Bearer $TOKEN"
C#
string? cursor = null;
do
{
var url = $"/v1/codes?updatedSince={Uri.EscapeDataString(since.ToString("O"))}&pageSize=500"
+ (cursor is null ? "" : $"&cursor={Uri.EscapeDataString(cursor)}");
var page = await http.GetFromJsonAsync<JsonElement>(url);
foreach (var item in page.GetProperty("items").EnumerateArray())
{
// Update your member record from item.
}
var next = page.GetProperty("nextCursor");
cursor = next.ValueKind == JsonValueKind.Null ? null : next.GetString();
} while (cursor is not null);
Node
let cursor = null;
do {
const params = new URLSearchParams({ updatedSince: since.toISOString(), pageSize: '500' });
if (cursor) params.set('cursor', cursor);
const page = await (await fetch(`${baseUrl}/v1/codes?${params}`, { headers })).json();
for (const item of page.items) {
// Update your member record from item.
}
cursor = page.nextCursor;
} while (cursor);
Python
cursor = None
while True:
params = {"updatedSince": since.isoformat(), "pageSize": 500}
if cursor:
params["cursor"] = cursor
page = session.get(f"{BASE_URL}/v1/codes", params=params).json()
for item in page["items"]:
pass # Update your member record from item.
cursor = page["nextCursor"]
if not cursor:
break
Look up a member's codes
GET /v1/codes?externalMemberRef=M-482913 - scope codes:read. Returns every code registered on
that reference, in the same { items, nextCursor } shape as the list, for example when a member logs
in to your own portal and you want to show the status of their codes.
externalMemberRefis your own opaque reference to the member, the same value you sent when the code was issued or imported. Use an id from your system, never a name or an email address. We do not know who the member is.- The match is exact:
M-482913does not findm-482913orM-4829. At most 100 characters; a longer value answers 400validation_error. - It combines with the other parameters, for example
status=activefor the codes the member can still redeem, orupdatedSince,pageSizeandcursoras in the list. - A reference with no codes answers 200 with an empty
items.
curl
curl -s "https://api-sandbox.b2bgroup.dk/v1/codes?externalMemberRef=M-482913" \
-H "Authorization: Bearer $TOKEN"
C#
var url = $"/v1/codes?externalMemberRef={Uri.EscapeDataString(memberRef)}";
var page = await http.GetFromJsonAsync<JsonElement>(url);
foreach (var item in page.GetProperty("items").EnumerateArray())
{
Console.WriteLine($"{item.GetProperty("code").GetString()}: {item.GetProperty("status").GetString()}");
}
Node
const params = new URLSearchParams({ externalMemberRef: memberRef });
const page = await (await fetch(`${baseUrl}/v1/codes?${params}`, { headers })).json();
for (const item of page.items) {
console.log(`${item.code}: ${item.status}`);
}
Python
page = session.get(f"{BASE_URL}/v1/codes", params={"externalMemberRef": member_ref}).json()
for item in page["items"]:
print(f"{item['code']}: {item['status']}")
Import existing codes
POST /v1/codes/import - scope codes:manage. Registers codes you have already given to members,
unchanged, with their reference, campaign and dates. At most 1000 codes per call.
{
"codes": [
{ "code": "ABC-H3WQ-7NZK", "externalMemberRef": "M-482913", "campaign": "legacy", "issuedAt": "2024-03-01T00:00:00Z", "expiresAt": "2027-03-01T00:00:00Z", "tier": 1 },
{ "code": "ABC-M4PX-2RTV", "externalMemberRef": "M-507264", "campaign": "legacy", "issuedAt": "2024-03-01T00:00:00Z", "expiresAt": "2027-03-01T00:00:00Z", "tier": 5 }
]
}
{ "imported": 2, "skipped": [] }
codeandexpiresAtare required.issuedAtis optional; send it to keep the original issue date.tieris optional and set per entry, a whole number from 1 to 100. Without it the code gets tier 1. See "Tiers" above.- Codes are trimmed and upper-cased. By default a code is 4 to 50 characters of
A-Z,0-9and-; if your account has an agreed code format, that format applies instead. - A code that is not imported is listed in
skippedwith itsreason, and the rest of the batch is still imported. The reasons are exactly:
| Reason | Meaning |
|---|---|
already_exists | The code is already registered, or appears earlier in the same batch. Never an error, so you can safely repeat an import that was interrupted. |
invalid_format | The code does not match the code format, or campaign is longer than 50 characters, or externalMemberRef is longer than 100 characters. |
missing_expiry | expiresAt is missing. |
- More than 1000 codes, an entry that is
null, or an entry with atieroutside 1 to 100, answers 400validation_errorand nothing is imported. For a tier,messagenames the entry, for example'codes[3].tier' must be an integer between 1 and 100.
curl
curl -s https://api-sandbox.b2bgroup.dk/v1/codes/import \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{ "codes": [ { "code": "ABC-H3WQ-7NZK", "externalMemberRef": "M-482913", "expiresAt": "2027-03-01T00:00:00Z" } ] }'
C#
foreach (var chunk in existingCodes.Chunk(1000))
{
var response = await http.PostAsJsonAsync("/v1/codes/import", new { codes = chunk });
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine($"Imported {result.GetProperty("imported").GetInt32()}");
}
Node
for (let i = 0; i < existingCodes.length; i += 1000) {
const response = await fetch(`${baseUrl}/v1/codes/import`, {
method: 'POST',
headers,
body: JSON.stringify({ codes: existingCodes.slice(i, i + 1000) }),
});
const result = await response.json();
console.log(`Imported ${result.imported}, skipped ${result.skipped.length}`);
}
Python
for i in range(0, len(existing_codes), 1000):
response = session.post(f"{BASE_URL}/v1/codes/import", json={"codes": existing_codes[i:i + 1000]})
response.raise_for_status()
result = response.json()
print(f"Imported {result['imported']}, skipped {len(result['skipped'])}")
Deactivate a code
POST /v1/codes/{code}/deactivate - scope codes:manage. Stops an unused code from being redeemed,
for example when a member leaves. The body is optional:
{ "reason": "member_left" }
- The answer is the code object with
statusdeactivated. reasonis free text; it is cut at 200 characters.- The call is idempotent: repeating it answers 200 with the original reason.
- A used code cannot be deactivated: 409
code_already_used. - The first deactivation sends the
code.deactivatedwebhook. Repeating the call does not send it again.
curl
curl -s -X POST https://api-sandbox.b2bgroup.dk/v1/codes/ABC-7K3Q-M8ZP/deactivate \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{ "reason": "member_left" }'
C#
var response = await http.PostAsJsonAsync($"/v1/codes/{Uri.EscapeDataString(code)}/deactivate",
new { reason = "member_left" });
if (response.StatusCode == System.Net.HttpStatusCode.Conflict)
{
// error: code_already_used - the member has already redeemed the code.
}
Node
const response = await fetch(`${baseUrl}/v1/codes/${encodeURIComponent(code)}/deactivate`, {
method: 'POST',
headers,
body: JSON.stringify({ reason: 'member_left' }),
});
if (response.status === 409) { /* error: code_already_used */ }
Python
response = session.post(f"{BASE_URL}/v1/codes/{code}/deactivate", json={"reason": "member_left"})
if response.status_code == 409:
pass # error: code_already_used
Errors on the code routes
| Status | error | When |
|---|---|---|
| 400 | validation_error | A field or query parameter is invalid; message says which. |
| 400 | validation_error | expiresAt on POST /v1/codes/issue or POST /v1/codes/issue-batch is not in the future. |
| 400 | validation_error | tier on issue, batch or import is not a whole number from 1 to 100. |
| 404 | code_not_found | The code does not exist for your account in this environment. |
| 409 | code_already_used | The code is already used (deactivation). |
See Errors for the full list.