Aller au contenu principal
Aller au contenu principal
Guide développeur

Plugins boutique

Le contrat d'envoi derrière la vérification : ce qui arrive, quand, et comment le vérifier.

A check is a request and a response: you ask about a buyer, you get a score. That is the easy half, and the API guide covers it.

The hard half is everything that happens after the response. The follow-up comes due three days later. A buyer refuses a parcel from another shop and the score you cached this morning is wrong by lunchtime. Neither of those is worth a polling loop, so we push them to you.

This guide is the contract for that push, plus the exact order of operations for two platforms:

  • YouCan — a full walkthrough, including YouCan's own webhook signatures
  • Shopify — the topic mapping and where the check belongs

If you are integrating something else, everything above the platform sections still applies.


The loop, in the order it actually happens

This is the part integrations get wrong, so it is worth sixty seconds of your time.

  ①  the shopper places a COD order in your store
  ②  your plugin POSTs /v1/checks                → a score, before anything ships
  ③  you store check_id against the order        → ← the step everyone skips
  ④  you decide: ship, call the buyer, or cancel
  ⑤  the courier comes back with an answer
  ⑥  you POST /v1/checks/{id}/outcome            → we learn what happened
  ⑦  if you forget, followup.due arrives at +3d  → ask the merchant in your own UI
  ⑧  score.changed arrives whenever it moves     → put a hold on a parcel still in the shop

Step ③ is not optional and it is not our job. Every webhook body names a check_id and nothing else — no order number, no customer, no email. That is deliberate: see What a webhook never contains. If you do not write check_id into your order record at step ②, every event we send you afterwards is an orphan you cannot act on.

A single column is enough:

ALTER TABLE orders ADD COLUMN eblacklist_check_id VARCHAR(32);
CREATE INDEX idx_orders_eblacklist_check_id ON orders (eblacklist_check_id);

Step ⑥ is not optional either. The score is built entirely out of outcomes reported by sellers. A plugin that only ever calls step ② reads the network's signal and contributes nothing, and its own merchants' buyers stay thin and low-confidence because their deliveries never get counted.


Check before ship: the exact order

Call us after the order exists in your database and before anything is handed to a courier. Both halves matter.

After, because you need somewhere to put check_id. Before, because a score that arrives after the parcel has left is a report, not a decision.

store writes the order row
        │
        ▼
POST /v1/checks  ──────────── timeout? ────────► ship (fail open)
        │                                        and retry the check later
        ▼
store check_id on the order
        │
        ▼
    trust_score                 confidence
        │
        ├── 0 or 1, not low ──► hold the order, tell the merchant
        ├── 2 or 3 ──────────► flag for a confirmation call
        └── 4 or 5 ──────────► ship

Fail open on our errors, never closed. If POST /v1/checks times out or returns 5xx, ship the order and log it. A trust score is advice; a scoring service having a bad minute must never stop a merchant trading. Retry the check out of band and act on the answer if the parcel has not left yet.

Use the merchant's order id as the idempotency key. Store platforms retry their own webhooks, so your handler will run twice for the same order:

Idempotency-Key: youcan-order-<order id>

Replaying a key with an identical body returns the original check — no second check, no second follow-up. Separately, checking the same buyer and product twice within 24 hours returns the first check anyway, so a double-fire is cheap even if you get the key wrong.

Treat confidence as part of the score. A trust_score of 2 with confidence: low is a brand-new buyer we know nothing about, and will carry the reason code NO_HISTORY. A 2 with confidence: high is a genuine warning. Holding orders on the first will make your merchants turn the plugin off.


Events

Three, deliberately. Each one is a thing a store integration has to act on.

EventWhenWhat a plugin does with it
followup.due+3 days after a check, once per checkShow the merchant "what happened to this parcel?" in your own UI, and post the answer to /v1/checks/{id}/outcome
outcome.recordedAn outcome landed, by any routeClose your own task. Also fires for the implied delivery written at +7 days, which is the case your plugin cannot see any other way
score.changedA buyer you have an open check on crossed a bandPut a hold on a parcel still sitting in the shop

"A check was created" is not on the list. Your plugin made that call itself and already has the answer.

Subscribe only to what you handle. A seller may register up to 5 endpoints.


The envelope

Every delivery is a POST with this body. data differs per event; everything outside it is identical.

{
  "id": "0193b1c4-5d6e-7f80-9a1b-2c3d4e5f6071",
  "type": "outcome.recorded",
  "api_version": "2026-11-15",
  "created_at": "2026-11-15T09:30:00+00:00",
  "data": {
    "check_id": "chk_01JCYQ8M3K7X2PQ4R5T6V7W8Y9",
    "outcome": "refused",
    "source": "app",
    "recorded_at": "2026-11-15T09:29:00+00:00",
    "supersedes_previous": false
  }
}

And the headers:

HeaderValue
X-EBlacklist-Signaturet=<unix seconds>,v1=<hex hmac> — see below
X-EBlacklist-Event-IdSame as the body's id. Dedupe on it
X-EBlacklist-Event-TypeSame as the body's type
X-EBlacklist-Attempt1 on the first try, up to 8
Content-Typeapplication/json
User-AgenteBlacklist-Webhooks/1

data, per event

followup.due

FieldTypeMeaning
check_idstringYour check
trust_scoreintThe score we returned at check time
confidencestringlow, medium or high
due_atRFC 3339When we started asking
closes_atRFC 3339When silence becomes an implied delivery. Show the merchant a real deadline, not "soon"

outcome.recorded

FieldTypeMeaning
check_idstringYour check
outcomestringdelivered, refused, returned, not_shipped or implied_delivered
sourcestringapp, api, push_action, email_link or system_implied
recorded_atRFC 3339When it was recorded
supersedes_previousbooltrue when this replaces an earlier answer — including an implied delivery later corrected to a refusal

score.changed

FieldTypeMeaning
check_idstringYour check on that buyer, never anyone else's
previous_trust_scoreintWhat it was
trust_scoreintWhat it is now
confidencestringlow, medium or high
reasonsstring[]Reason codes — see the table in the API guide
changed_atRFC 3339When it moved

reasons carries codes, never sentences. Branch on the code; render your own wording.


Verifying a delivery

An unverified webhook endpoint is a public API that anyone can POST to. Without this check, a stranger who guesses your URL can tell your plugin that a parcel was delivered and release a hold you put there for a reason.

The header is t=<unix seconds>,v1=<hex>, where the hex is HMAC_SHA256(key = your whsec_… secret, message = "<t>.<raw body>").

Three things people get wrong:

  1. Sign the raw body, not the re-serialized object. json_encode(json_decode($body)) is not the same bytes and will never match. Capture the body before any parsing middleware.
  2. The key is the whole whsec_… string, as UTF-8. Do not strip the prefix. Do not base64-decode it.
  3. Compare in constant time, and check the length first. timingSafeEqual throws on a length mismatch, which an attacker can trigger deliberately.

Then reject anything whose t is more than 300 seconds from your clock. That is what makes a captured delivery un-replayable — the signature is bound to one moment, not just to one body.

A test vector

Check your implementation against this before you have any traffic. These three strings produce exactly the header below; it is generated by the same code that signs real deliveries and is pinned by a test, so if your code disagrees, your code is wrong.

secret : whsec_TESTVECTORONLYdoNotUseThisKeyInProduction1
t      : 1763199000
body   : {"api_version":"2026-11-15","created_at":"2026-11-15T09:30:00+00:00","data":{"check_id":"chk_01JCYQ8M3K7X2PQ4R5T6V7W8Y9","outcome":"refused","recorded_at":"2026-11-15T09:29:00+00:00","source":"app","supersedes_previous":false},"id":"0193b1c4-5d6e-7f80-9a1b-2c3d4e5f6071","type":"outcome.recorded"}

X-EBlacklist-Signature: t=1763199000,v1=906e48ae675aae7d94c244a8cc270bdad131f21e1d1cfbb787e890be9671fc0c

PHP

<?php
/**
 * Returns the decoded event, or null if the delivery is not ours.
 * $raw must be the untouched request body: file_get_contents('php://input').
 */
function eblacklist_verify(string $raw, string $header, string $secret, int $tolerance = 300): ?array
{
    $timestamp = null;
    $candidates = [];
    foreach (explode(',', $header) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) !== 2) {
            continue;
        }
        if ($pair[0] === 't') {
            $timestamp = (int) $pair[1];
        } elseif ($pair[0] === 'v1') {
            $candidates[] = $pair[1];
        }
    }
    if ($timestamp === null || $candidates === []) {
        return null;
    }

    $expected = hash_hmac('sha256', $timestamp . '.' . $raw, $secret);

    $matched = false;
    foreach ($candidates as $candidate) {
        // hash_equals is constant time and safe on unequal lengths.
        if (hash_equals($expected, $candidate)) {
            $matched = true;
        }
    }
    if (!$matched) {
        return null;
    }

    // abs(): a clock correction must not turn an old capture into a valid delivery.
    if (abs(time() - $timestamp) > $tolerance) {
        return null;
    }

    return json_decode($raw, true);
}

// --- the handler -----------------------------------------------------------

$raw    = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_EBLACKLIST_SIGNATURE'] ?? '';
$event  = eblacklist_verify($raw, $header, getenv('EBLACKLIST_WEBHOOK_SECRET'));

if ($event === null) {
    http_response_code(400);
    exit;
}

// Answer first, work afterwards. One attempt gets 10 seconds in total.
http_response_code(204);
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
}

if (already_processed($event['id'])) {   // at-least-once: you will see duplicates
    exit;
}
mark_processed($event['id']);

switch ($event['type']) {
    case 'score.changed':
        if ($event['data']['trust_score'] <= 1) {
            hold_order_for_check($event['data']['check_id'], $event['data']['reasons']);
        }
        break;
    case 'followup.due':
        open_merchant_task($event['data']['check_id'], $event['data']['closes_at']);
        break;
    case 'outcome.recorded':
        close_merchant_task($event['data']['check_id'], $event['data']['outcome']);
        break;
}

JavaScript (Node, Express)

import crypto from "node:crypto";
import express from "express";

export function verify(raw, header, secret, toleranceSeconds = 300) {
  let timestamp = null;
  const candidates = [];
  for (const part of header.split(",")) {
    const index = part.indexOf("=");
    if (index === -1) continue;
    const key = part.slice(0, index).trim();
    const value = part.slice(index + 1).trim();
    if (key === "t") timestamp = Number.parseInt(value, 10);
    else if (key === "v1" && value) candidates.push(value);
  }
  if (!Number.isFinite(timestamp) || candidates.length === 0) return null;

  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${timestamp}.${raw}`, "utf8")
    .digest("hex");

  // The length check is not optional: timingSafeEqual THROWS on unequal
  // lengths, and an attacker can trigger that on purpose.
  const matched = candidates.some(
    (candidate) =>
      candidate.length === expected.length &&
      crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(expected)),
  );
  if (!matched) return null;

  if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > toleranceSeconds) return null;

  return JSON.parse(raw);
}

const app = express();

// express.raw, NOT express.json: the HMAC is over the bytes we sent.
app.post(
  "/eblacklist/webhook",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    const event = verify(
      req.body.toString("utf8"),
      req.get("X-EBlacklist-Signature") ?? "",
      process.env.EBLACKLIST_WEBHOOK_SECRET,
    );
    if (!event) return res.sendStatus(400);

    // Answer immediately; one attempt gets 10 seconds in total.
    res.sendStatus(204);

    if (await alreadyProcessed(event.id)) return; // at-least-once
    await markProcessed(event.id);

    switch (event.type) {
      case "score.changed":
        if (event.data.trust_score <= 1) {
          await holdOrderForCheck(event.data.check_id, event.data.reasons);
        }
        break;
      case "followup.due":
        await openMerchantTask(event.data.check_id, event.data.closes_at);
        break;
      case "outcome.recorded":
        await closeMerchantTask(event.data.check_id, event.data.outcome);
        break;
    }
  },
);

Delivery, honestly

At least once, not at most once. A 2xx lost on the way back looks exactly like a timeout, so you will occasionally see the same event twice. The body's id — also in X-EBlacklist-Event-Id — does not change across retries, so "ignore an id I have already processed" is a complete fix on your side. Write it down before you act, not after.

Answer fast. One attempt gets 10 seconds, end to end — resolving your hostname, connecting, writing the body and reading your response all come out of the same budget, and when it runs out the attempt is a timeout and goes into the retry schedule below. A handler that answers in nine seconds is inside it and is still a handler nobody should ship. Return 2xx as soon as the signature checks out and do the work afterwards. Anything outside 200–299 is a failure.

Retries. Eight attempts, with exponential backoff and jitter:

After attemptWait
110s
230s
31m 30s
44m 30s
513m 30s
640m 30s
72h 01m 30s

That is about three hours end to end (a little under four with jitter). A receiver that is down for a deploy misses nothing. One that is down all afternoon gets switched off.

Redirects are not followed. A 301 or 302 is a failed attempt, not a hop. Register the final URL.

410 Gone means stop. Answer 410 and we disable the endpoint immediately and drop whatever was queued for it. Use it when a merchant uninstalls your plugin — it is cleaner than letting the endpoint fail its way to being disabled, and it is the only status with this meaning. Everything else 4xx is just a failure.

Consecutive failures disable an endpoint. 20 failed attempts in a row — roughly two and a half fully exhausted deliveries — and we switch it off with a reason the merchant can read in their settings, then drop the queue. That last part is deliberate: a plugin coming back after a day does not want a day of stale "should I ship?" questions whose parcels left hours ago.

Re-enable it with PATCH /v1/webhooks/{id} and {"enabled": true}, which also clears the failure counter.

Delivery records are kept 30 days.


Managing endpoints

MethodPathScope
GET/v1/webhooksread
GET/v1/webhooks/{id}read
POST/v1/webhookswebhooks:write
PATCH/v1/webhooks/{id}webhooks:write
DELETE/v1/webhooks/{id}webhooks:write
POST/v1/webhooks/{id}/testwebhooks:write

webhooks:write is a separate scope from checks:write, and it is worth understanding why before you ask a merchant for it. An endpoint registration decides where every future event goes. A token that can add one can quietly copy a merchant's entire event stream somewhere else, durably, in a way revoking the token afterwards does not undo. Ask for it only in the token your plugin uses to set itself up, and use a checks:write/outcomes:write token for day-to-day traffic.

curl -s https://api.eblacklist.app/v1/webhooks \
  -H "Authorization: Bearer $EBLACKLIST_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "label": "YouCan store",
        "url": "https://shop.example.com/eblacklist/webhook",
        "events": ["followup.due", "outcome.recorded", "score.changed"]
      }'
{
  "id": "0193b1c4-5d6e-7f80-9a1b-2c3d4e5f6071",
  "label": "YouCan store",
  "url": "https://shop.example.com/eblacklist/webhook",
  "events": ["followup.due", "outcome.recorded", "score.changed"],
  "enabled": true,
  "failure_count": 0,
  "secret": "whsec_…"
}

secret is returned once, here, and never again. Not by the list, not by a read. Store it the moment you receive it. There is no rotation endpoint: if you lose it, delete the endpoint and register it again.

Requirements on the URL

  • https only, on a publicly resolvable hostname.
  • No credentials in the URL. https://user:pass@… is rejected; use a header or a path segment.
  • Private address space is refused, at registration and again after DNS resolution on every single attempt. 127.0.0.1, 10.0.0.0/8, 169.254.169.254 and friends are all out, including via a hostname that resolves to one. If a registered hostname later starts answering with a private address, that attempt fails and the endpoint is disabled with the reason unsafe_target.

Because of that last rule, you cannot point a webhook at localhost while developing, not even in a development environment — the resolution check runs on every attempt and will disable the endpoint. Use a public tunnel (ngrok, cloudflared) and register the tunnel's public https URL.

Test it

curl -s -X POST https://api.eblacklist.app/v1/webhooks/$ID/test \
  -H "Authorization: Bearer $EBLACKLIST_TOKEN"
{ "delivered": true, "response_code": 204, "error": null, "latency_ms": 143 }

One synthetic followup.due, delivered immediately, with a real signature and a check id of all zeroes (chk_0000…) so your existing switch handles it. One attempt, no retries, and a failure here does not count against the endpoint. error is a short machine-readable string — timeout, http_503, dns_unresolved, unsafe_target.


What a webhook never contains

A check response goes to the merchant who asked the question, and they already have the buyer's details — they typed them in. A webhook goes somewhere else: to whatever server a merchant pasted a URL for. The buyer agreed to give a phone number to a shop, not to that shop's vendor stack.

So a payload carries the merchant's own check_id, the score, and reason codes. It will never contain:

  • the buyer's phone, name or address, in any form;
  • the internal buyer identity id — that is the one identifier shared across merchants, and two plugins comparing notes could use it to confirm the same buyer ordered from both, which is exactly the correlation /v1/checks refuses to perform;
  • any other merchant, their name, their id, their checks or their products;
  • a one-tap follow-up link, which is a bearer credential that would let a receiver report outcomes in the merchant's name.

This cuts both ways, and that is the point: the same wall keeps your merchants' data out of everyone else's integration.


Shopify

Shopify's own webhooks tell you an order exists. Ours tell you what happened to it.

Topic mapping

Shopify topicWhat your plugin does
orders/createThe check. If the order is COD, POST /v1/checks and store check_id on the order
orders/paidReport delivered. COD is a manual payment method: the order is created unpaid and a human marks it paid once the cash is in hand, so this is the merchant telling you the parcel was accepted
orders/fulfilledNothing yet. Fulfilled means it left the shop, not that it was accepted. This is the moment to stop acting on score.changed for that order
orders/cancelledIf the parcel never shipped, POST /v1/checks/{id}/outcome with not_shipped. This never counts against the buyer
fulfillments/createOptional: when your carrier integration later reports delivery or return, map it to delivered / returned

Shopify lists COD as one of its manual payment methods, alongside money orders and bank transfers: an order placed with one is created Pending and unpaid, and stays that way until someone marks it paid. So the COD test is on the order's payment method, not on a tag — read it from the orders/create payload and skip everything else. There is no point scoring a prepaid order.

Note that "Cash on Delivery (COD)" is a name Shopify reserves, so a merchant cannot have renamed it to something you would fail to recognise.

Shopify gives a webhook handler a 5 second budget for the whole request, and a 1 second connection timeout. POST /v1/checks can take longer than that when a buyer's identity needs resolving, so do not call us inline from the Shopify handler. Acknowledge Shopify, queue a job, and make the check there.

Verifying Shopify's own webhooks

Different from ours in every detail, so do not reuse the function:

eBlacklistShopify
HeaderX-EBlacklist-SignatureX-Shopify-Hmac-Sha256
Shapet=…,v1=…the digest alone
Encodinghexbase64
Signed string"{t}.{body}"the raw body
Keyyour whsec_…your app's client secret
Dedupe onX-EBlacklist-Event-IdX-Shopify-Webhook-Id
Expected replyany 2xx200 specifically — a 3xx counts as an error
import crypto from "node:crypto";

export function verifyShopify(rawBody, header, clientSecret) {
  const expected = crypto
    .createHmac("sha256", clientSecret)
    .update(rawBody) // the raw Buffer, before any JSON parsing
    .digest("base64");
  const received = Buffer.from(header ?? "", "utf8");
  const digest = Buffer.from(expected, "utf8");
  return received.length === digest.length && crypto.timingSafeEqual(received, digest);
}

Shopify also sends X-Shopify-Topic, X-Shopify-Shop-Domain and X-Shopify-API-Version. Treat header names as case-insensitive.

Putting the hold somewhere a merchant will see it

Shopify has no "risky buyer" concept of its own, so land the result where staff already look:

  • trust_score 0–1 with confidence above low → hold the fulfillment order and add an order note naming the reason codes;
  • 2–3 → add a tag such as eblacklist-review so it shows in the order list;
  • 4–5 → nothing.

Tag rather than cancel. The merchant decides; your plugin gives them the reason.


When an endpoint goes quiet

In order of how often it turns out to be the cause:

  1. Your handler is slow. One attempt gets 10 seconds in total. Acknowledge first, work after.
  2. The body was parsed before it was verified. Framework JSON middleware consumes the raw bytes, and re-serializing changes them. Every signature fails, every delivery is rejected, and after twenty of those the endpoint is disabled.
  3. A clock is wrong. Outside 300 seconds in either direction, every signature looks stale. Run NTP.
  4. A redirect. We do not follow them. Register the final URL.
  5. DNS moved. If the hostname starts resolving into private space, deliveries stop with unsafe_target and the endpoint is disabled. A hostname that stops resolving at all is different: that is an ordinary failed attempt (dns_unresolved), retried on the schedule above, because a nameserver having a bad minute is not a reason to drop your queue.
  6. It was disabled. GET /v1/webhooks/{id} reports enabled and disabled_reason: too_many_failures, endpoint_gone (you answered 410), unsafe_target or by_seller.

POST /v1/webhooks/{id}/test answers 1, 3, 4 and 5 in one call.