# Roerdink B2B API - Integration guide

For wholesale customers of Roerdink and the agencies or developers that build their integration
(including integrations written with the help of ChatGPT, Copilot or other AI assistants).

- Base URL: `https://api.roerdink.nl` - all endpoints are under `/api/v1`
- OpenAPI 3 specification: <https://api.roerdink.nl/openapi.json>
- Interactive reference (read-only): <https://api.roerdink.nl/swagger/>
- Short rules for AI tools: <https://api.roerdink.nl/llms.txt>

This guide describes how the API behaves **today**, including a few known quirks. Where the
behaviour is unusual (errors as HTTP 500, a rewritten order reference, a webhook signature
caveat) it is called out explicitly so you can code around it.

---

## 1. What the API offers

| Task | Endpoint(s) |
|------|-------------|
| Product master data (brand, model, size, colour, RRP, images, categories) | `GET /api/v1/catalogue` |
| Stock of the models released to you (recommended stock sync) | `GET /api/v1/connectedstock` |
| Stock of the whole assortment (only with permission) | `GET /api/v1/allstock` |
| Look up one product (find `idproduct`, your price) | `GET /api/v1/products/lookup`, `GET /api/v1/products` |
| Place an order | `POST /api/v1/orders` |
| Order status, backorders, fulfilment per product | `GET /api/v1/orders/{orderId}` and sub-resources |
| Shipments with track & trace | `GET /api/v1/picklists/{pickListId}/shipments` |
| Push notifications for product and stock changes | `POST /api/v1/hooks` |

Not available through the API: invoices, returns/complaints, price lists. Use the
website or contact Roerdink for those.

There is **no sandbox**. Every order created through the API is a real order. Agree test
orders with your Roerdink contact beforehand.

---

## 2. Getting access

1. Ask your Roerdink contact for API access. You receive an **API id** and an **API password**.
   Both are GUIDs, for example `0f8c2d4e-1a2b-4c3d-9e8f-7a6b5c4d3e2f`.
2. Roerdink links the API account to your customer account. Orders you create are placed on
   that account, and you only ever see your own orders.
3. **Release the models you want to sell.** `/connectedstock` only returns models that are
   released ("connected") to your account. You do this yourself in the catalogue on
   www.roerdink.nl (the connect/"koppelen" option on a model, or the bulk action on a
   filtered selection), or Roerdink does it for you. An empty `/connectedstock` response
   almost always means nothing has been released yet.
4. Optional: ask for **full stock access** if you need `/allstock` (stock of the entire
   assortment).

Keep the credentials on your server (environment variables or a secret store). Never put them
in browser JavaScript, a mobile app or a public repository.

---

## 3. Authentication

HTTP Basic authentication on every request: username = API id, password = API password.

```
Authorization: Basic base64("<api id>:<api password>")
```

**Send the header pre-emptively.** The server does not answer with a `WWW-Authenticate`
challenge, so HTTP clients that only send credentials after a challenge never authenticate.
In .NET, set `HttpClient.DefaultRequestHeaders.Authorization` yourself instead of using
`HttpClientHandler.Credentials`. `curl -u`, PHP cURL (`CURLOPT_USERPWD`), Guzzle `auth`,
Python `requests` `auth=` and Postman all send it pre-emptively.

| Situation | Result |
|-----------|--------|
| No `Authorization` header | `401`, empty body |
| Unknown, wrong or deactivated credentials | `401`, empty body |
| Malformed header (not base64, no `:`, not two GUIDs) | `401`, empty body |

---

## 4. Conventions

- JSON in and out. Send `Accept: application/json`; without it some clients (browsers, some
  libraries) receive XML. Send `Content-Type: application/json` on POST/PUT.
- Field names are lower case exactly as documented (`idorder`, `deliveryzipcode`,
  `free_stock`). Request field names are matched case-insensitively, but stick to the
  documented spelling.
- Properties with a null value are **omitted** from responses. Treat a missing property as
  "no value"; never assume a property is always present.
- Dates are ISO 8601. Times are Dutch local time (Europe/Amsterdam).
- Amounts are in EUR.
- Responses can contain more properties than documented (they come from the warehouse
  system). Ignore what you do not need; do not fail on unknown properties.
- Names of colours and categories are Dutch (`Zwart`, `Dames`).

---

## 5. Rate limit

At most **50 requests per 60-second window per API account**. Every server or process that
uses the same account shares this budget. The window starts at your first request and the
counter resets when it ends.

When you exceed it you get `429 Too Many Requests` with a plain-text body such as
`Too many requests (quota will be replenished in 37 seconds)` and no `Retry-After` header.
Wait for the indicated number of seconds (or 60 seconds) before continuing.

Design for it:

- Page through stock and catalogue with large pages (`limit=1000`) instead of many small calls.
- Do not poll every order every minute; see the polling advice in section 9.
- Serialize calls (one at a time) in batch jobs; do not fire requests in parallel.

---

## 6. Errors

Today most problems come back as **HTTP 500**, including validation errors, unknown ids,
orders that are not yours and missing permissions. The body is JSON; the reason is in
`ExceptionMessage`:

```json
{
  "Message": "An error has occurred.",
  "ExceptionMessage": "Product is discontinued; amount requested not available"
}
```

Use `ExceptionMessage` (and fall back to `Message`). Common messages:

| `ExceptionMessage` (starts with) | Meaning | Retry? |
|---|---|---|
| `No orderlines given.` | `products` array missing or empty | No - fix request |
| `Each order line must specify a product via ...` | A line has no `productcode`, `ean`/`barcode` or `idproduct` | No |
| `Product not found. Tried ...` | An identifier on a line matched nothing (exact match). The message lists what was tried | No - check codes |
| `Product is discontinued; amount requested not available` | Discontinued product, amount above free stock | No - lower amount |
| `Order given is not yours.` / `Picklist given is not yours.` | Id belongs to another customer | No |
| `Geen toegang tot alle voorraad.` | `/allstock` without full stock access ("no access to all stock") | No |
| `Specify 'ean' or 'productcode' ...` / `No product found for ...` | `/products/lookup` without parameter / without match | No |
| `Already subscribed to this hook` | Webhook for this event already exists | No |
| `Name is mandatory` / `Event is mandatory` / `Address is mandatory` | Webhook field missing | No |
| `Error: ...` or `Error (WebException): ...` | The warehouse system rejected or did not answer the request | GET: yes, with back-off. POST: see below |
| `Too many requests to the warehouse system; retry later.` | The warehouse system is temporarily busy | GET: yes, after a minute. POST: see below |
| `Internal error (reference ...)` | Unexpected error on our side; the details are logged under that reference | GET: once, later. If it persists, contact Roerdink with the reference |

Other status codes:

- `401` - see section 3.
- `404` with a JSON `Message` - the URL does not exist (typo in the path).
- `429` - see section 5.

Retry rules:

- Retry `429` after waiting. Retry network errors and `Error (WebException)` on **GET**
  requests at most 3 times with increasing delays (e.g. 5 s, 30 s, 2 min).
- **Never blindly retry `POST /api/v1/orders`.** There is no idempotency key. If the call
  timed out or failed with an unclear error, first check whether the order exists: list your
  recent orders (`GET /api/v1/orders?status=concept`, then `status=processing`) and look for
  your reference in `reference` or in `customer_remarks` (see section 8.4).

---

## 7. Identifying products

Roerdink sells models (a shoe design) in colours and sizes. One **variant** (one colour in
one size) is one product. Identifiers:

| Field | Where you get it | Use it for |
|-------|------------------|-----------|
| `productcode` | `/catalogue`, `/connectedstock`, `/allstock` | **Primary key.** Unique per variant. Preferred on order lines. |
| `barcode` (EAN) | `/catalogue`, `/connectedstock`, `/allstock` | Alternative key. Send it as `ean` (or `barcode`) on order lines. |
| `idproduct` | `/products`, `/products/lookup`, order lines | Warehouse id. Needed for the order-line endpoints. |
| `model_id` | `/catalogue`, `/connectedstock` | Groups variants of one model. **Never** an `idproduct`. |

Matching on order lines is **exact** (no fuzzy matching). Resolution order: `idproduct`, then
`ean`/`barcode`, then `productcode`; the first match wins. If you give an identifier that
matches nothing, the whole order is rejected and the error lists what was tried.

To check an identifier before ordering:

```
GET /api/v1/products/lookup?productcode=10.123.045.42
GET /api/v1/products/lookup?ean=8712345678906
```

The response includes `idproduct`, `purchase_in_quantities_of` (pack size; order in multiples
of it, `0` = no restriction), `discontinued`, and your net price in `price_order` when a
customer-specific discount applies (`price` is the gross wholesale price).

---

## 8. Placing orders

### 8.1 Request

`POST /api/v1/orders`

```json
{
  "reference": "WEB-100245",
  "customer_remarks": "Please deliver before noon",
  "deliveryname": "J. Jansen",
  "deliveryaddress": "Dorpsstraat 12",
  "deliveryaddress2": "",
  "deliveryzipcode": "1234 AB",
  "deliverycity": "Voorbeelddorp",
  "deliverycountry": "NL",
  "emailaddress": "j.jansen@example.com",
  "telephone": "+31612345678",
  "dropshipment": true,
  "products": [
    { "productcode": "10.123.045.42", "amount": 1 },
    { "ean": "8712345678906", "amount": 2 }
  ]
}
```

| Field | Notes |
|-------|-------|
| `products` | Required, at least one line. Each line: one identifier (section 7) + `amount` (integer >= 1). Optional `remarks`. |
| `reference` | Your order number. Will be moved to `customer_remarks` later (8.4). |
| `customer_remarks` | Optional free text. |
| `delivery*` | Always send the full delivery address. `deliverycountry` is an ISO code (`NL`, `BE`, `DE`). Put street + house number in `deliveryaddress`, additions (apartment, unit) in `deliveryaddress2`. |
| `emailaddress`, `telephone` | Of the recipient; used by the carrier. |
| `preferred_delivery_date` | Optional, `YYYY-MM-DD`. |
| `dropshipment` | `true` when the order ships straight to your consumer. |

Do **not** send: `price` (ignored - Roerdink sets prices), `idcustomer` (overwritten with your
account), discounts, templates or shipping profiles.

### 8.2 Response - store `idorder`

The response is the created order with status `concept`:

```json
{
  "idorder": 48211934,
  "orderid": "O2026-104233",
  "status": "concept",
  "reference": "WEB-100245",
  "products": [
    { "idorder_product": 301245501, "idproduct": 9876543, "productcode": "10.123.045.42", "price": 59.95, "amount": 1 }
  ],
  "dropshipment": true
}
```

**Store `idorder` together with your own order.** It is the only stable key; all follow-up
calls use it (`/api/v1/orders/{idorder}`). `orderid` is the human-readable number you can show
to people. Prices in this response are provisional (gross); see 8.3.

### 8.3 What happens next (automatically)

Shortly after creation Roerdink picks the order up and:

1. sets your **net prices** on the order lines;
2. rounds amounts **up to the pack size** (`purchase_in_quantities_of`) where needed, and then
   sends a notification e-mail to the order's `emailaddress` - for a dropshipment that is your
   consumer. Order in multiples of the pack size to avoid both;
3. **rewrites `reference`** (see 8.4);
4. moves the order from `concept` to `processing`, after which the warehouse picks it.

Do **not** call `/process` or `/allocate` yourself, and do not change the order afterwards
(`PUT`, adding/removing lines): such changes are not reflected in Roerdink's own order
administration (pricing, invoicing). If an order must change or be cancelled after it was
accepted, contact Roerdink.

### 8.4 Gotcha: `reference` is overwritten

After Roerdink has processed the order:

- `reference` becomes Roerdink's internal reference, e.g. `Roerdink order (NC): 734512`. Do
  not parse it; the format can vary.
- your own reference moves to `customer_remarks`, as
  `Referentie klant: WEB-100245`, followed by ` | Opmerkingen klant: <your remarks>` if you
  sent remarks. ("Referentie klant" is Dutch for "customer reference".)

So: never look up your orders by `reference`. Use the stored `idorder`. If you must find an
order without it, search `customer_remarks` for `Referentie klant: <your number>`.

### 8.5 Dropshipment

An order is treated as a dropshipment (shipped to your end customer, handled under your
dropship agreement with Roerdink) when **any** of these is true:

- you send `"dropshipment": true`;
- your account is configured to treat all API orders as dropshipments;
- the delivery address is **not one of the addresses Roerdink has on file for your account**.
  The comparison uses the postcode (ignoring spaces and punctuation) plus the house number
  (the last group of digits in `deliveryaddress`). A missing or incomplete postcode, or a
  foreign address that is not on file, also counts as dropshipment.

The server never switches dropshipment off. If you order for your own shop, send your shop
address exactly as registered with Roerdink, with the house number in `deliveryaddress`
(`Dorpsstraat 12`, not `Dorpsstraat 12 unit 3` - put `unit 3` in `deliveryaddress2`). The
create response contains `"dropshipment": true` when the order is handled as a dropshipment.

### 8.6 Discontinued products

For a discontinued product (`discontinued: true` on `/products/lookup`,
`out_of_assortment: true` on `/connectedstock`) you cannot order more than the current free
stock; the order is rejected with `Product is discontinued; amount requested not available`.
Check stock first and lower the amount.

---

## 9. Following orders up to shipment

There are **no order or shipment webhooks**. Poll.

1. `GET /api/v1/orders/{idorder}` - `status`:
   - `concept` - received, not yet processed by Roerdink
   - `processing` - accepted, being fulfilled
   - `paused` - on hold at Roerdink
   - `completed` - everything shipped
   - `cancelled` - cancelled
   The order also contains `picklists[]`. A picklist is the warehouse job for (part of) the
   order; a partly delivered order can have several.
2. For each `picklists[].idpicklist`:
   `GET /api/v1/picklists/{idpicklist}/shipments` returns the parcels with `trackingcode`,
   `tracktraceurl`, `providername`. It is empty until the parcel has been labelled. Ignore
   shipments with `"cancelled": true`.
3. `GET /api/v1/picklists/{idpicklist}` returns which products are in that picklist (a
   shipment itself carries no product lines).
4. Optional: `GET /api/v1/orders/{idorder}/productstatus` (per product: allocated, on picklist,
   backorder, delivered) and `GET /api/v1/orders/{idorder}/backorders` (quantities still
   waiting for stock).

Polling advice (fits the rate limit):

- Only poll orders that are not `completed` or `cancelled`.
- Poll each open order every 30-60 minutes, and fetch shipments only for picklists you have
  not yet seen with a tracking code.
- Stop polling an order once it is `completed` and every picklist has a shipment.

---

## 10. Catalogue and stock synchronisation

### 10.1 Catalogue (product data)

`GET /api/v1/catalogue?offset=0` returns **1000 rows per page** (fixed; `limit` is ignored).
Continue with `offset=1000`, `2000`, ... until a page has fewer than 1000 rows. One row per
variant with `productcode`, `barcode`, `model_id`, `model_name`, `size_code`, `color_code`,
`brand_id`, `brand_name`, `price`, `description`, `images` (up to 6 URLs) and `categories`.

- `price` in the catalogue is the **recommended retail price** (consumer price), **not** your
  purchase price. Your purchase price: `price_order` (or `price` when absent) on
  `/products/lookup`.
- The catalogue covers the whole active assortment, not only your released models, and
  contains no stock figures.
- Refreshing once a day is enough.

### 10.2 Stock

`GET /api/v1/connectedstock?limit=1000&offset=0`, then `offset=1000`, ... until a page has
fewer than 1000 rows. Without `limit` you get everything in one (large) response and `offset`
is ignored.

```json
[
  {
    "productcode": "10.123.045.43",
    "barcode": "8712345678913",
    "model_id": 6789,
    "model_name": "NW-2041",
    "size_code": "43",
    "color_code": "Zwart",
    "stock": [ { "freestock": 0, "expected_in_days": 12 } ]
  }
]
```

- `stock[0].freestock` is the sellable stock, **capped at 30**: `30` means "30 or more".
  Treat `0` or lower as out of stock.
- `stock[0].expected_in_days` appears only when the variant is out of stock and not
  discontinued: the estimated number of days until it is available again.
- `stock[0].out_of_assortment: true` marks a discontinued variant (sold while stock lasts).
- `minstock` / `maxstock` are informational and can be ignored.
- Only active variants of models released to your account are included. A variant that
  disappears from the result is no longer available to you: set it to 0 in your shop.
- Note the field names: `stock[0].freestock` here, but `free_stock` on `/products`.

`/api/v1/allstock` works the same (same paging, same cap) for the whole assortment, with only
`productcode`, `barcode` and `stock[0].freestock` / `expected_in_days`. It requires full stock
access; without it you get HTTP 500 `Geen toegang tot alle voorraad.`

Recommended schedule: a full `/connectedstock` run every 15-60 minutes, optionally combined
with the `products.free_stock_changed` webhook (section 11) for faster updates in between.
Use `/connectedstock` (or `/allstock`) as the source of truth for stock; the stock figures in
other endpoints are informational.

---

## 11. Webhooks (product events)

### 11.1 Subscribing

```
POST /api/v1/hooks
{
  "name": "Stock updates for my shop",
  "event": "products.free_stock_changed",
  "address": "https://shop.example.com/roerdink/webhook",
  "secret": "3f9a1c0e7b5d42e8a6c1f0b9d8e7a6c5"
}
```

- **Only two events are delivered: `products.changed` and `products.free_stock_changed`.**
  Other event names (for example `orders.closed` or `picklists.shipments.created`) are
  accepted but never fire.
- One subscription per event per API account.
- `GET /api/v1/hooks` lists your subscriptions; `GET /api/v1/hooks/{idhook}` returns one (or
  `null`).
- **Known issue:** `DELETE /api/v1/hooks/{idhook}` returns 204 but the subscription stays
  active, and you cannot create a second one for the same event. Choose the `address`
  carefully; to stop deliveries or change the address, contact Roerdink.
- Use an HTTPS address and a secret of ASCII characters only (e.g. 32 random hex characters).

### 11.2 Deliveries

Roerdink sends a `POST` to your address with `Content-Type: text/json` (UTF-8):

```json
{
  "idhook": 42,
  "name": "ProductsFreeStockChanged (auto-added @ 2026-03-02 10:15:00)",
  "event": "products.free_stock_changed",
  "event_triggered_at": "2026-10-28T14:05:12.345+01:00",
  "data": {
    "idproduct": 9876543,
    "productcode": "10.123.045.42",
    "name": "Nordic Walker NW-2041 Zwart 42",
    "barcode": "8712345678906",
    "price": 59.95,
    "active": true,
    "stock": [ { "idwarehouse": 1001, "freestock": 14 } ]
  }
}
```

- Events cover **all** Roerdink products, not only the models released to you. Look up
  `data.productcode` in your own catalogue and ignore products you do not sell.
- `data.stock[].freestock` is per warehouse and capped at 30, like `/connectedstock` (`30`
  means "30 or more"). You can also use the event as a trigger and take the stock from your
  next `/connectedstock` run.
- `name` is informational; `data.price` is the gross wholesale price.

### 11.3 Responding and retries

- Answer with any **2xx** status within a few seconds; do the actual work asynchronously.
- Anything else (non-2xx, timeout, connection error) is retried: up to **15 attempts** in
  total over roughly 24 hours (after 10 s, 30 s, 5 min, 10 min, 30 min, then hourly growing to
  6 hours).
- Retries resend the original body. Deliveries can arrive late, out of order and more than
  once. Make processing idempotent (e.g. always re-read the current state, keyed by
  `productcode`).

### 11.4 Verifying the signature

When the subscription has a secret, each delivery has the header `X-Picqer-Signature`: the
**lowercase hex HMAC-SHA256** of the body, keyed with your secret. There is no timestamp or
replay protection.

**Known issue:** the server computes the signature over an ASCII version of the body in which
every non-ASCII character (e.g. the `o` with umlaut in a brand name) is replaced by `?`. For
bodies with only ASCII characters this equals the raw body. Verify like this:

1. compute the HMAC over the raw body bytes; if it matches, accept;
2. otherwise decode the body as UTF-8, replace every non-ASCII character with `?`, compute the
   HMAC over that text and compare again;
3. reject only if both fail.

Code for PHP and C# is in section 12.

---

## 12. Code examples

Set the credentials as environment variables `ROERDINK_API_ID` and `ROERDINK_API_PASSWORD`.

### 12.1 curl

```bash
# Stock of your released models, first page
curl -s -u "$ROERDINK_API_ID:$ROERDINK_API_PASSWORD" \
  -H "Accept: application/json" \
  "https://api.roerdink.nl/api/v1/connectedstock?limit=1000&offset=0"

# Check a product code and get your price
curl -s -u "$ROERDINK_API_ID:$ROERDINK_API_PASSWORD" \
  -H "Accept: application/json" \
  "https://api.roerdink.nl/api/v1/products/lookup?productcode=10.123.045.42"

# Create an order (order.json contains the body from section 8.1)
curl -s -u "$ROERDINK_API_ID:$ROERDINK_API_PASSWORD" \
  -H "Accept: application/json" -H "Content-Type: application/json" \
  -X POST "https://api.roerdink.nl/api/v1/orders" --data @order.json

# Order status and picklists
curl -s -u "$ROERDINK_API_ID:$ROERDINK_API_PASSWORD" \
  -H "Accept: application/json" \
  "https://api.roerdink.nl/api/v1/orders/48211934"

# Track & trace of a picklist
curl -s -u "$ROERDINK_API_ID:$ROERDINK_API_PASSWORD" \
  -H "Accept: application/json" \
  "https://api.roerdink.nl/api/v1/picklists/55120987/shipments"

# Subscribe to stock changes
curl -s -u "$ROERDINK_API_ID:$ROERDINK_API_PASSWORD" \
  -H "Accept: application/json" -H "Content-Type: application/json" \
  -X POST "https://api.roerdink.nl/api/v1/hooks" \
  --data '{"name":"Stock updates","event":"products.free_stock_changed","address":"https://shop.example.com/roerdink/webhook","secret":"3f9a1c0e7b5d42e8a6c1f0b9d8e7a6c5"}'
```

### 12.2 PHP (cURL extension, PHP 8)

```php
<?php
const ROERDINK_BASE = 'https://api.roerdink.nl';

/** Calls the Roerdink API and returns the decoded JSON (or null for an empty body). */
function roerdink(string $method, string $path, ?array $body = null): mixed
{
    $ch = curl_init(ROERDINK_BASE . $path);
    $headers = ['Accept: application/json'];
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPAUTH       => CURLAUTH_BASIC, // sent pre-emptively
        CURLOPT_USERPWD        => getenv('ROERDINK_API_ID') . ':' . getenv('ROERDINK_API_PASSWORD'),
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_TIMEOUT        => 120,
    ]);
    $raw    = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $error  = curl_error($ch);
    curl_close($ch);

    if ($raw === false) {
        throw new RuntimeException('Network error: ' . $error);
    }
    if ($status === 429) {
        throw new RuntimeException('Rate limited: ' . $raw);   // wait and try again later
    }
    if ($status === 401) {
        throw new RuntimeException('Roerdink API credentials rejected');
    }
    $data = ($raw === '') ? null : json_decode($raw, true);
    if ($status >= 400) {
        $reason = $data['ExceptionMessage'] ?? $data['Message'] ?? $raw;
        throw new RuntimeException("Roerdink API error $status: $reason");
    }
    return $data;
}

// --- Stock sync: all pages of /connectedstock -------------------------------------------
$limit  = 1000;
$offset = 0;
$stock  = [];
do {
    $page = roerdink('GET', "/api/v1/connectedstock?limit=$limit&offset=$offset");
    foreach ($page as $row) {
        $free = max(0, (int)($row['stock'][0]['freestock'] ?? 0)); // 30 means "30 or more"
        $stock[$row['productcode']] = $free;
    }
    $offset += $limit;
} while (count($page) === $limit);
// Update your shop from $stock; set variants that are not in $stock to 0.

// --- Create an order and store idorder --------------------------------------------------
$order = roerdink('POST', '/api/v1/orders', [
    'reference'       => 'WEB-100245',
    'deliveryname'    => 'J. Jansen',
    'deliveryaddress' => 'Dorpsstraat 12',
    'deliveryzipcode' => '1234 AB',
    'deliverycity'    => 'Voorbeelddorp',
    'deliverycountry' => 'NL',
    'emailaddress'    => 'j.jansen@example.com',
    'dropshipment'    => true,
    'products'        => [
        ['productcode' => '10.123.045.42', 'amount' => 1],
    ],
]);
$idorder = $order['idorder']; // save this with your own order WEB-100245

// --- Later: poll status and track & trace -----------------------------------------------
$current = roerdink('GET', "/api/v1/orders/$idorder");
foreach ($current['picklists'] ?? [] as $picklist) {
    $shipments = roerdink('GET', "/api/v1/picklists/{$picklist['idpicklist']}/shipments");
    foreach ($shipments as $shipment) {
        if (!empty($shipment['cancelled'])) {
            continue;
        }
        echo $shipment['trackingcode'] ?? '', ' ', $shipment['tracktraceurl'] ?? '', PHP_EOL;
    }
}
```

Webhook receiver (PHP):

```php
<?php
$body     = file_get_contents('php://input');
$secret   = getenv('ROERDINK_WEBHOOK_SECRET');
$received = strtolower($_SERVER['HTTP_X_PICQER_SIGNATURE'] ?? '');

$valid = hash_equals(hash_hmac('sha256', $body, $secret), $received);
if (!$valid) {
    // Known issue: Roerdink signs the body with every non-ASCII character replaced by '?'.
    $asciiBody = preg_replace('/[^\x00-\x7F]/u', '?', $body);
    $valid = $asciiBody !== null && hash_equals(hash_hmac('sha256', $asciiBody, $secret), $received);
}
if (!$valid) {
    http_response_code(401);
    exit;
}

$event = json_decode($body, true);
// Queue the work (e.g. in a database table) and answer immediately.
// queue_product_update($event['event'], $event['data']['productcode'] ?? null);
http_response_code(200);
```

### 12.3 C# (.NET 6 or later)

```csharp
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

public sealed class RoerdinkClient
{
    private readonly HttpClient _http;

    public RoerdinkClient(string apiId, string apiPassword)
    {
        _http = new HttpClient
        {
            BaseAddress = new Uri("https://api.roerdink.nl/"),
            Timeout = TimeSpan.FromMinutes(2)
        };
        // Pre-emptive Basic auth. Do NOT use HttpClientHandler.Credentials: the server sends no challenge.
        string token = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{apiId}:{apiPassword}"));
        _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
        _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<JsonElement> SendAsync(HttpMethod method, string path, object? body = null)
    {
        using var request = new HttpRequestMessage(method, path);
        if (body != null)
        {
            request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
        }

        using HttpResponseMessage response = await _http.SendAsync(request);
        string text = await response.Content.ReadAsStringAsync();

        if ((int)response.StatusCode == 429)
            throw new InvalidOperationException("Rate limited: " + text); // wait, then retry
        if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            throw new InvalidOperationException("Roerdink API credentials rejected");
        if (!response.IsSuccessStatusCode)
        {
            string reason = text;
            try
            {
                using var error = JsonDocument.Parse(text);
                if (error.RootElement.TryGetProperty("ExceptionMessage", out var message))
                    reason = message.GetString() ?? text;
            }
            catch (JsonException) { }
            throw new InvalidOperationException($"Roerdink API error {(int)response.StatusCode}: {reason}");
        }

        using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(text) ? "null" : text);
        return doc.RootElement.Clone();
    }
}

// Usage
var client = new RoerdinkClient(
    Environment.GetEnvironmentVariable("ROERDINK_API_ID")!,
    Environment.GetEnvironmentVariable("ROERDINK_API_PASSWORD")!);

// Stock sync
var stock = new Dictionary<string, int>();
const int limit = 1000;
for (int offset = 0; ; offset += limit)
{
    JsonElement page = await client.SendAsync(HttpMethod.Get, $"api/v1/connectedstock?limit={limit}&offset={offset}");
    foreach (JsonElement row in page.EnumerateArray())
    {
        int free = row.GetProperty("stock")[0].TryGetProperty("freestock", out var f) ? f.GetInt32() : 0;
        stock[row.GetProperty("productcode").GetString()!] = Math.Max(0, free); // 30 = "30 or more"
    }
    if (page.GetArrayLength() < limit) break;
}

// Create an order; store idorder with your own order
JsonElement order = await client.SendAsync(HttpMethod.Post, "api/v1/orders", new
{
    reference = "WEB-100245",
    deliveryname = "J. Jansen",
    deliveryaddress = "Dorpsstraat 12",
    deliveryzipcode = "1234 AB",
    deliverycity = "Voorbeelddorp",
    deliverycountry = "NL",
    emailaddress = "j.jansen@example.com",
    dropshipment = true,
    products = new[] { new { productcode = "10.123.045.42", amount = 1 } }
});
int idorder = order.GetProperty("idorder").GetInt32();
```

Webhook signature check (C#, e.g. in an ASP.NET Core endpoint):

```csharp
static bool IsValidSignature(byte[] rawBody, string? signatureHeader, string secret)
{
    if (string.IsNullOrEmpty(signatureHeader)) return false;
    byte[] expected = Encoding.ASCII.GetBytes(signatureHeader.ToLowerInvariant());
    byte[] key = Encoding.ASCII.GetBytes(secret);

    bool Matches(byte[] data)
    {
        using var hmac = new HMACSHA256(key);
        string hex = Convert.ToHexString(hmac.ComputeHash(data)).ToLowerInvariant();
        return CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(hex), expected);
    }

    if (Matches(rawBody)) return true;
    // Known issue: Roerdink signs the body with every non-ASCII character replaced by '?'.
    // Encoding.ASCII.GetBytes performs exactly that replacement.
    return Matches(Encoding.ASCII.GetBytes(Encoding.UTF8.GetString(rawBody)));
}

// ASP.NET Core minimal API; 'secret' is your webhook secret (e.g. from configuration).
app.MapPost("/roerdink/webhook", async (HttpRequest request) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);   // read the raw body; Content-Type is text/json
    byte[] body = buffer.ToArray();

    if (!IsValidSignature(body, request.Headers["X-Picqer-Signature"], secret))
        return Results.Unauthorized();

    // Queue the event for background processing and acknowledge immediately.
    return Results.Ok();
});
```

---

## 13. Checklist for a correct integration

Use this list when you (or your AI assistant) review the integration code:

- [ ] Base URL `https://api.roerdink.nl`, paths `/api/v1/...`.
- [ ] Basic auth header sent on every request, pre-emptively; credentials kept server-side.
- [ ] `Accept: application/json` on every request.
- [ ] At most 50 requests per minute per account; `429` handled by waiting.
- [ ] HTTP 500 handled by reading `ExceptionMessage`; no blind retries, never for `POST /orders`.
- [ ] Products matched on `productcode` (or EAN); `model_id` never used as `idproduct`.
- [ ] No prices or `idcustomer` sent on orders; amounts in multiples of the pack size.
- [ ] Full delivery address sent; house number in `deliveryaddress`; `dropshipment: true` for
      consumer deliveries.
- [ ] `idorder` from the create response stored; orders never looked up by `reference`.
- [ ] No `/process`, `/allocate` or order changes after creation.
- [ ] Stock from `/connectedstock` with `limit=1000` paging; 30 treated as "30 or more";
      missing variants set to 0.
- [ ] Catalogue `price` treated as recommended retail price, not purchase price.
- [ ] Shipments obtained by polling picklists of open orders.
- [ ] Webhooks (if used): only the two product events; raw body read; signature checked with
      the ASCII fallback; 2xx returned quickly; idempotent processing.

---

## 14. Known limitations (current behaviour)

| Limitation | Workaround |
|------------|------------|
| Validation and permission errors return HTTP 500 instead of 4xx | Read `ExceptionMessage` (section 6) |
| `reference` is overwritten after processing | Store `idorder`; your reference is in `customer_remarks` |
| No order or shipment webhooks | Poll (section 9) |
| Subscribing to other webhook events succeeds but nothing is delivered | Only use the two product events |
| `DELETE /hooks/{idhook}` does not stop deliveries | Contact Roerdink |
| Webhook signature computed over an ASCII-converted body | Use the fallback check (section 11.4) |
| Webhook events are not filtered to your released models | Ignore unknown product codes |
| No sandbox | Agree test orders with Roerdink |

Questions or problems: contact your Roerdink account manager. Include the request (without
credentials), the HTTP status, the `ExceptionMessage` (with the reference, if any) and the
time of the call.
