Guides for integrators
Integration recipes
On this page
Four short, complete examples for the jobs most integrations do. Each one shows curl, JavaScript, PHP and Python. The addresses are the example store https://yourstore.example.com and the key is read from the environment: use your own. Every snippet is a starting point to adapt, not a finished product; the parts that are specific to your own system (saveOnce, openReturnCase and so on) are yours to write.
Tip
New here? Do the Quick start first. Before you connect a real store, read the Go-live checklist and Security best practices.
- A paid order goes to your accounting or ERP system
- Keep stock in step with your ERP
- Push products from a catalogue tool
- Handle a return event
A paid order goes to your accounting or ERP system#
When a customer pays, the store sends order.paid. Your receiver checks the signature, ignores repeats, saves the event, answers 200, and a worker creates the invoice or sales order in your system. The API is your safety net: after any downtime, read what you missed.
What you need#
- A webhook for Order paid (also Order cancelled and Order refunded if your accounting follows them), made in the store's admin. See the Quick start.
- For the catch-up: a key with
read:orders.
How it works#
- Verify the signature, then ignore a test message (
"test": true) and any event you do not use. - Save the event with its
idin a table where the id is unique. If it is already there, do nothing: this is a repeat. Answer200within 5 seconds. - A worker maps the order to your system: the
number(text) as your reference, theitems(name, size, price, quantity), and the amountssubtotal,discount,shippingandtotal, all in whole units of the store's currency. A gift packaging fee is already inside the total. - Every hour, and after any downtime, run the catch-up: read the paid orders changed since your last successful sync, and skip order numbers you already have.
# Catch up after downtime: every paid order changed since your last successful sync.
# Follow links.next until it is null. Skip an order number you already handled.
curl -s "https://yourstore.example.com/api/v1/orders?payment_status=paid&updated_since=2026-11-21T00:00:00Z&limit=100&expand=full" \
-H "Authorization: Bearer YOUR_API_KEY"// Express receiver for "order.paid". The route needs the RAW body, so it uses express.raw().
import express from 'express';
import crypto from 'node:crypto';
const app = express();
function isGenuine(raw, header) {
const parts = header.split(',').map((p) => p.trim().split('='));
const t = Number((parts.find(([k]) => k === 't') || [])[1]);
if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false; // older (or newer) than 5 minutes
const expected = crypto.createHmac('sha256', process.env.GROKEEPER_WEBHOOK_SECRET).update(`${t}.${raw}`).digest('hex');
return parts.filter(([k]) => k === 'v1').some(([, v]) =>
v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
app.post('/hooks/grokeeper', express.raw({ type: 'application/json' }), async (req, res) => {
const raw = req.body.toString('utf8');
if (!isGenuine(raw, req.get('X-GroKeeper-Signature') || '')) return res.sendStatus(400);
const event = JSON.parse(raw);
if (event.test || event.type !== 'order.paid') return res.sendStatus(200); // a test message, or an event we do not use: still answer 2xx
// Save the event once. The same event id can arrive again (a retry, or Redeliver in the admin).
// saveOnce() is yours: a table with a UNIQUE column for the event id, returning false if the id is already there.
await saveOnce(event.id, event.data);
res.sendStatus(200); // answer first; a worker creates the invoice in your ERP later
});
app.listen(3000);<?php
// Receiver for "order.paid" in plain PHP. The signing secret comes from the environment.
function is_genuine(string $payload, string $header): bool
{
$t = 0;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
if ($k === 't') { $t = (int) $v; }
if ($k === 'v1') { $signatures[] = $v; }
}
if (!$t || abs(time() - $t) > 300) { return false; } // older (or newer) than 5 minutes
$expected = hash_hmac('sha256', $t . '.' . $payload, (string) getenv('GROKEEPER_WEBHOOK_SECRET'));
foreach ($signatures as $s) {
if (hash_equals($expected, $s)) { return true; }
}
return false;
}
$payload = file_get_contents('php://input'); // the RAW body
if (!is_genuine($payload, $_SERVER['HTTP_X_GROKEEPER_SIGNATURE'] ?? '')) {
http_response_code(400);
exit;
}
$event = json_decode($payload, true);
if (!empty($event['test']) || $event['type'] !== 'order.paid') {
http_response_code(200); // a test message, or an event we do not use
exit;
}
// Save the event once. A UNIQUE column for the event id makes a repeat harmless ($pdo is your own connection; this is MySQL).
$pdo->prepare('INSERT IGNORE INTO grokeeper_events (event_id, payload) VALUES (?, ?)')->execute([$event['id'], $payload]);
http_response_code(200); // answer first; a worker creates the invoice in your ERP later# Flask receiver for "order.paid".
import hashlib
import hmac
import os
import time
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["GROKEEPER_WEBHOOK_SECRET"].encode()
def is_genuine(raw: bytes, header: str) -> bool:
parts = [p.strip().split("=", 1) for p in header.split(",") if "=" in p]
t = next((int(v) for k, v in parts if k == "t" and v.isdigit()), 0)
if not t or abs(time.time() - t) > 300: # older (or newer) than 5 minutes
return False
expected = hmac.new(SECRET, str(t).encode() + b"." + raw, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, v) for k, v in parts if k == "v1")
@app.post("/hooks/grokeeper")
def hook():
raw = request.get_data() # the RAW body
if not is_genuine(raw, request.headers.get("X-GroKeeper-Signature", "")):
abort(400)
event = request.get_json(force=True)
if event.get("test") or event["type"] != "order.paid":
return "", 200 # a test message, or an event we do not use
save_once(event["id"], event["data"]) # yours: a table with a UNIQUE event id; a repeat is ignored
return "", 200 # answer first; a worker creates the invoice in your ERP laterThings to handle#
- The same event can arrive more than once (retries, Redeliver). The event
idis how you tell. - Events can arrive out of order. For money decisions you can re-read the order with
GET /orders/{number}and trust itspayment_status. - Webhooks are retried for about 45 hours and then given up on. If your receiver was down longer, the catch-up read fills the gap.
- The customer's details are personal data. Switch off Include customers' personal details on the endpoint if your accounting does not need them.
Keep stock in step with your ERP#
Your ERP knows about deliveries, damage and counts; the store knows about sales. Push the ERP's changes through POST /inventory/adjustments. It is the only way the API changes stock, it needs a reason, and every change is written to the stock history with your key as the author.
What you need#
- A key with
write:inventory(andread:inventoryto read levels). Write scopes are given by a Super Admin. - The ERP's item code on each size as its SKU, so you can name the size by
sku.
How it works#
- For goods received or found, send
mode: addwithreason: receivedorfound. For damaged or expired stock,mode: removewithreason: damagedorexpired. - After a physical count, send
mode: setwith the counted number andreason: correction(orotherwith a note). - Use your ERP's document number as the
Idempotency-Key, so a retry can never add the same delivery twice. - To compare, read
GET /inventorywithupdated_since: it showson_hand,reservedandavailable(what the shop sells from).
# Add a delivery. The ERP document number is the Idempotency-Key, so a retry never adds twice.
curl -s -X POST "https://yourstore.example.com/api/v1/inventory/adjustments" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: erp-4471" \
-d '{"sku": "SAMPLE-001-250", "mode": "add", "quantity": 24, "reason": "received", "note": "ERP receipt 4471"}'
# After a physical count, set the counted number.
curl -s -X POST "https://yourstore.example.com/api/v1/inventory/adjustments" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: erp-count-118" \
-d '{"sku": "SAMPLE-001-250", "mode": "set", "quantity": 96, "reason": "correction", "note": "ERP stock count 118"}'
# Read what changed in the store since your last sync (stock levels).
curl -s "https://yourstore.example.com/api/v1/inventory?updated_since=2026-11-21T00:00:00Z&limit=100" \
-H "Authorization: Bearer YOUR_API_KEY"// Push one stock change from your ERP. The ERP document number is the Idempotency-Key.
const STORE = 'https://yourstore.example.com';
async function adjustStock({ sku, mode, quantity, reason, note, documentId }) {
for (let attempt = 1; attempt <= 5; attempt++) {
const res = await fetch(`${STORE}/api/v1/inventory/adjustments`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.GROKEEPER_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': `erp-${documentId}`, // 1 to 100 letters, digits or . _ : -
},
body: JSON.stringify({ sku, mode, quantity, reason, note }),
});
if (res.status === 429 || res.status >= 500) { // too many requests, or the store is busy:
const wait = Number(res.headers.get('Retry-After')) || attempt * 2;
await new Promise((r) => setTimeout(r, wait * 1000)); // wait, then send the SAME request again
continue;
}
const json = await res.json();
if (!res.ok) throw new Error(`${json.error.code}: ${json.error.message}`); // for example insufficient_stock, validation_failed
return json.data; // { movement_id, before, after, change, inventory: { ... } }
}
throw new Error('The store did not accept the change after 5 tries');
}
await adjustStock({ sku: 'SAMPLE-001-250', mode: 'add', quantity: 24, reason: 'received', note: 'ERP receipt 4471', documentId: '4471' });<?php
// Push one stock change from your ERP. The ERP document number is the Idempotency-Key.
function adjust_stock(array $change, string $documentId): array
{
for ($attempt = 1; $attempt <= 5; $attempt++) {
$ch = curl_init('https://yourstore.example.com/api/v1/inventory/adjustments');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('GROKEEPER_API_KEY'),
'Content-Type: application/json',
'Idempotency-Key: erp-' . $documentId,
],
CURLOPT_POSTFIELDS => json_encode($change),
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
if ($raw === false) { sleep($attempt * 2); continue; } // the network failed: try again with the same key
$headers = substr($raw, 0, $size);
$json = json_decode(substr($raw, $size), true);
if ($status === 429 || $status >= 500) { // too many requests, or the store is busy
preg_match('/^Retry-After:\s*(\d+)/mi', $headers, $m);
sleep((int) ($m[1] ?? $attempt * 2));
continue; // send the SAME request again
}
if ($status >= 400) {
throw new RuntimeException($json['error']['code'] . ': ' . $json['error']['message']);
}
return $json['data'];
}
throw new RuntimeException('The store did not accept the change after 5 tries');
}
adjust_stock(['sku' => 'SAMPLE-001-250', 'mode' => 'add', 'quantity' => 24, 'reason' => 'received', 'note' => 'ERP receipt 4471'], '4471');# Push one stock change from your ERP. The ERP document number is the Idempotency-Key.
import os
import time
import requests
STORE = "https://yourstore.example.com"
def adjust_stock(change: dict, document_id: str) -> dict:
for attempt in range(1, 6):
res = requests.post(
f"{STORE}/api/v1/inventory/adjustments",
headers={
"Authorization": f"Bearer {os.environ['GROKEEPER_API_KEY']}",
"Idempotency-Key": f"erp-{document_id}", # 1 to 100 letters, digits or . _ : -
},
json=change,
timeout=30,
)
if res.status_code == 429 or res.status_code >= 500: # too many requests, or the store is busy
time.sleep(int(res.headers.get("Retry-After", attempt * 2)))
continue # send the SAME request again
data = res.json()
if not res.ok:
raise RuntimeError(f"{data['error']['code']}: {data['error']['message']}")
return data["data"] # movement_id, before, after, change, inventory
raise RuntimeError("The store did not accept the change after 5 tries")
adjust_stock({"sku": "SAMPLE-001-250", "mode": "add", "quantity": 24, "reason": "received", "note": "ERP receipt 4471"}, "4471")Things to handle#
422 insufficient_stock: you tried to remove more than is available. Nothing was changed.409 stock_changed: you sentexpected(the available stock you last saw) and it is no longer that number. Read again and decide. Nothing was changed.409 idempotency_key_reuse: the same key was used for a different request. A document number must belong to exactly one change.- While a customer is buying, the store's stock moves too. Prefer changes (
add,remove) for ERP events, andsetonly for a real count. - Stock is never accepted when you create or update a product or a size. It changes only here.
Push products from a catalogue tool#
Create products from your catalogue or PIM tool as drafts, check them, then publish. A product made through the API starts as a draft and is published only when it is complete and you ask. Nothing is ever deleted: removing a product archives it.
What you need#
- A key with
write:products(andread:productsto look products up). - For each product: a name and at least one size with a label, a selling price and an MRP, all as whole numbers. Add the SKU, HSN code, GST rate and a category if you have them.
How it works#
- Look the product up by SKU with
GET /products(?sku=). If it exists, change it withPATCH /products/{id}orPATCH /products/{id}/variants/{variantId}instead of creating it again. - Create it with
POST /productsand anIdempotency-Keybuilt from your own product code, so a retry never creates a second product. - Read
meta.warningsin the answer: small points that did not stop the product from being created. - Add the first stock with the stock recipe above: new sizes start at 0.
- Publish with
PATCH /products/{id}andactive: true, or sendpublished: truewhen creating a product you know is complete.
# 1. Is the product there already? (a SKU is unique)
curl -s "https://yourstore.example.com/api/v1/products?sku=SAMPLE-001" -H "Authorization: Bearer YOUR_API_KEY"
# 2. Create it as a DRAFT with its sizes. Stock cannot be sent here: new sizes start at 0.
curl -s -X POST "https://yourstore.example.com/api/v1/products" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: catalogue-SAMPLE-001" \
-d '{"name": "Sample Product", "sku": "SAMPLE-001", "short": "A short description of the product.", "variants": [{"label": "250 g", "price": 399, "mrp": 449, "sku": "SAMPLE-001-250", "weight_grams": 250}]}'
# 3. Publish it when it is complete (422 cannot_publish says what is missing, and nothing changes).
curl -s -X PATCH "https://yourstore.example.com/api/v1/products/7" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: publish-7" \
-d '{"active": true}'const STORE = 'https://yourstore.example.com';
async function call(method, path, body, idempotencyKey) {
const res = await fetch(`${STORE}/api/v1${path}`, {
method,
headers: {
Authorization: `Bearer ${process.env.GROKEEPER_API_KEY}`,
'Content-Type': 'application/json',
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const json = await res.json();
if (!res.ok) throw new Error(`${res.status} ${json.error.code}: ${json.error.message} ${JSON.stringify(json.error.fields || {})}`);
return json;
}
// p comes from your catalogue tool.
async function pushProduct(p) {
const found = await call('GET', `/products?sku=${encodeURIComponent(p.sku)}`);
if (found.data.length) return found.data[0]; // already there: change it with PATCH instead
// A draft. created.meta.warnings lists small points you may want to fix.
const created = await call('POST', '/products', {
name: p.name, sku: p.sku, short: p.short,
variants: p.sizes.map((s) => ({ label: s.label, price: s.price, mrp: s.mrp, sku: s.sku, weight_grams: s.grams })),
}, `catalogue-${p.sku}`);
return created.data;
}
const product = await pushProduct({
name: 'Sample Product', sku: 'SAMPLE-001', short: 'A short description of the product.',
sizes: [{ label: '250 g', price: 399, mrp: 449, sku: 'SAMPLE-001-250', grams: 250 }],
});
// Publish it when it is complete. A 422 cannot_publish lists what is missing and nothing is changed.
await call('PATCH', `/products/${product.id}`, { active: true }, `publish-${product.id}`);<?php
function api(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
{
$headers = ['Authorization: Bearer ' . getenv('GROKEEPER_API_KEY'), 'Content-Type: application/json'];
if ($idempotencyKey) { $headers[] = 'Idempotency-Key: ' . $idempotencyKey; }
$ch = curl_init('https://yourstore.example.com/api/v1' . $path);
curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => $headers]);
if ($body !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); }
$json = json_decode((string) curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) {
throw new RuntimeException($status . ' ' . ($json['error']['code'] ?? 'error') . ': ' . ($json['error']['message'] ?? 'request failed'));
}
return $json;
}
// 1. Is the product there already? (a SKU is unique)
$found = api('GET', '/products?sku=' . urlencode('SAMPLE-001'));
if ($found['data']) { exit('Already there: change it with PATCH instead'); }
// 2. Create it as a DRAFT. meta.warnings lists small points you may want to fix.
$created = api('POST', '/products', [
'name' => 'Sample Product',
'sku' => 'SAMPLE-001',
'short' => 'A short description of the product.',
'variants' => [['label' => '250 g', 'price' => 399, 'mrp' => 449, 'sku' => 'SAMPLE-001-250', 'weight_grams' => 250]],
], 'catalogue-SAMPLE-001');
$id = $created['data']['id'];
// 3. Publish it when it is complete. A 422 cannot_publish lists what is missing and nothing is changed.
api('PATCH', '/products/' . $id, ['active' => true], 'publish-' . $id);import os
import requests
STORE = "https://yourstore.example.com"
def call(method, path, body=None, idempotency_key=None):
headers = {"Authorization": f"Bearer {os.environ['GROKEEPER_API_KEY']}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
res = requests.request(method, f"{STORE}/api/v1{path}", headers=headers, json=body, timeout=30)
data = res.json()
if not res.ok:
err = data["error"]
raise RuntimeError(f"{res.status_code} {err['code']}: {err['message']} {err.get('fields', {})}")
return data
# 1. Is the product there already? (a SKU is unique)
found = call("GET", "/products?sku=SAMPLE-001")
if found["data"]:
raise SystemExit("Already there: change it with PATCH instead")
# 2. Create it as a DRAFT. meta.warnings lists small points you may want to fix.
created = call("POST", "/products", {
"name": "Sample Product",
"sku": "SAMPLE-001",
"short": "A short description of the product.",
"variants": [{"label": "250 g", "price": 399, "mrp": 449, "sku": "SAMPLE-001-250", "weight_grams": 250}],
}, "catalogue-SAMPLE-001")
product_id = created["data"]["id"]
# 3. Publish it when it is complete. A 422 cannot_publish lists what is missing and nothing is changed.
call("PATCH", f"/products/{product_id}", {"active": True}, f"publish-{product_id}")Things to handle#
422 validation_failedlists each field to fix inerror.fields. An HSN code must be 4, 6 or 8 digits and is never padded for you: a code that lost its leading zero is refused with the reason.422 cannot_publishmeans the product failed the checks for publishing (a price above zero, a price not above the MRP, no duplicate size, a valid HSN). Nothing was changed; fix the points and try again.- A SKU and a slug must be unique. Each size label can appear once for a product.
- Weight is set on each size, not on the product.
- Stock, payment and order amounts can never be sent here. See what the API will never do.
Handle a return event#
When a customer asks to send items back, or a team member enters a return, the store sends the return events. Use them to open a case in your helpdesk, expect the parcel in your warehouse, record what came back, and create the credit note when the refund is done.
What you need#
- A webhook for the four return events:
return.requested,return.approved,return.received,return.refunded. - Returns have to be in use in the store. Customer return requests are off until a Super Admin switches them on; returns that staff enter themselves send events too.
- Optional: a key with
read:ordersto read the order a return belongs to.
How it works#
return.requested: a return was asked for or entered.datahas the returnnumber, theorder_number, thereason_labeland theitems.return.approved: the return was approved.shipping_payersays who pays to send the items back (storeorcustomer).return.received: the items arrived. Each item hasqty_receivedand anaction:resell(back on sale) orwriteoff(not sellable).return.refunded: the refund is recorded as done, withrefunded_amount. It is never sent while a refund is only requested.
# A return event carries the order number. Read the order for anything else you need.
curl -s "https://yourstore.example.com/api/v1/orders/GK-261008-7WNM?expand=full" \
-H "Authorization: Bearer YOUR_API_KEY"// The receiver from the first recipe, with a switch for the four return events.
// isGenuine() is the signature check shown there (and on the "Check the signature" page).
app.post('/hooks/grokeeper', express.raw({ type: 'application/json' }), async (req, res) => {
const raw = req.body.toString('utf8');
if (!isGenuine(raw, req.get('X-GroKeeper-Signature') || '')) return res.sendStatus(400);
const event = JSON.parse(raw);
// saveOnce() returns false when this event id is already stored: a repeat, so do nothing more.
if (event.test || !(await saveOnce(event.id, raw))) return res.sendStatus(200);
res.sendStatus(200); // answer first; in production run the rest from a queue
const r = event.data; // the return
switch (event.type) {
case 'return.requested':
await openReturnCase(r.number, r.order_number, r.reason_label, r.items);
break;
case 'return.approved':
await expectParcel(r.number, r.items, r.shipping_payer); // 'store' or 'customer' pays to send it back
break;
case 'return.received':
for (const i of r.items) {
await recordReturnedItem(r.number, i.name, i.variant, i.qty_received, i.action); // action: 'resell' or 'writeoff'
}
break;
case 'return.refunded':
await createCreditNote(r.order_number, r.number, r.refunded_amount);
break;
default:
break; // an event we do not use: ignore it
}
});<?php
// The receiver from the first recipe, with a switch for the four return events.
// is_genuine() is the signature check shown there (and on the "Check the signature" page).
$payload = file_get_contents('php://input');
if (!is_genuine($payload, $_SERVER['HTTP_X_GROKEEPER_SIGNATURE'] ?? '')) {
http_response_code(400);
exit;
}
$event = json_decode($payload, true);
// save_once() returns false when this event id is already stored: a repeat, so do nothing more.
if (!empty($event['test']) || !save_once($event['id'], $payload)) {
http_response_code(200);
exit;
}
http_response_code(200); // answer first; in production run the rest from a queue
$r = $event['data']; // the return
switch ($event['type']) {
case 'return.requested':
open_return_case($r['number'], $r['order_number'], $r['reason_label'], $r['items']);
break;
case 'return.approved':
expect_parcel($r['number'], $r['items'], $r['shipping_payer']); // 'store' or 'customer' pays to send it back
break;
case 'return.received':
foreach ($r['items'] as $i) {
record_returned_item($r['number'], $i['name'], $i['variant'], $i['qty_received'], $i['action']); // 'resell' or 'writeoff'
}
break;
case 'return.refunded':
create_credit_note($r['order_number'], $r['number'], $r['refunded_amount']);
break;
default:
break; // an event we do not use: ignore it
}# The receiver from the first recipe, with a branch for each of the four return events.
# is_genuine() is the signature check shown there (and on the "Check the signature" page).
@app.post("/hooks/grokeeper")
def hook():
raw = request.get_data()
if not is_genuine(raw, request.headers.get("X-GroKeeper-Signature", "")):
abort(400)
event = request.get_json(force=True)
# save_once() returns False when this event id is already stored: a repeat, so do nothing more.
if event.get("test") or not save_once(event["id"], raw):
return "", 200
queue_for_worker(event) # answer first; the worker below does the rest
return "", 200
def handle(event):
r = event["data"] # the return
kind = event["type"]
if kind == "return.requested":
open_return_case(r["number"], r["order_number"], r["reason_label"], r["items"])
elif kind == "return.approved":
expect_parcel(r["number"], r["items"], r["shipping_payer"]) # "store" or "customer" pays to send it back
elif kind == "return.received":
for i in r["items"]:
record_returned_item(r["number"], i["name"], i["variant"], i["qty_received"], i["action"]) # "resell" or "writeoff"
elif kind == "return.refunded":
create_credit_note(r["order_number"], r["number"], r["refunded_amount"])
# any other event type: ignore itThings to handle#
- A return that is rejected, or closed without a refund, sends no event.
- There is no API call that lists returns. Everything you need is in the event; use the order number to read the order.
- The return
numberis text:RT-, the date as yymmdd, a dash and four letters or digits. Order numbers keep the store's own prefix. - With personal details switched off on the endpoint, the customer's email and phone in the event are masked.
- As always, ignore repeats by event
id, and ignore event types you do not know.