Skip to content

Integration

Integrating a delivery platform: webhooks, OAuth 2.0 and idempotency

Receiving a delivery platform's orders in your own system, with no duplicates and nothing lost: architecture, signature verification, idempotent processing, OAuth 2.0 authentication and operations.

Published 4 min read

The problem: one interface per platform

A restaurant or shop selling through several delivery platforms receives its orders in as many different interfaces, on top of its own website. Staff have to watch several screens and re-enter information, and overall tracking becomes difficult. The goal of an integration is to bring every order into a single system, reliably and securely.

A hub-and-spoke architecture

The principle: an order core holds a single order model (statuses, items, amounts, customer) and the business rules. Around it, one adapter per platform translates external formats into that model. Adding a channel means writing a new adapter, without touching the core.

  1. The platform sends an event (new order, cancellation…) by webhook.
  2. The server verifies the signature, stores the event and responds immediately.
  3. Asynchronous processing checks that the event has not already been handled (idempotency).
  4. The adapter translates the event into the common model; the core creates or updates the order.
  5. The back office displays the order; status changes are sent back to the platform through its API.

Verify webhook signatures

A webhook URL is public: anyone can send a request to it. Platforms therefore sign what they send, most often with an HMAC-SHA256 computed over the request body with a shared secret. The server recomputes the signature and rejects any request that does not match.

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

const app = express();

// The raw body is essential: the signature covers the bytes received, not re-serialised JSON.
app.post("/webhooks/platform", express.raw({ type: "application/json" }), async (req, res) => {
  const received = req.get("X-Signature") ?? ""; // header name: see the platform's documentation
  const expected = crypto
    .createHmac("sha256", process.env.WEBHOOK_SECRET!)
    .update(req.body)
    .digest("hex");

  const a = Buffer.from(received);
  const b = Buffer.from(expected);
  // Constant-time comparison (timingSafeEqual requires equal lengths)
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return res.status(401).end();
  }

  const event = JSON.parse(req.body.toString("utf8"));
  await enqueue(event);    // store, then process asynchronously
  res.status(200).end();   // respond fast: the platform resends the event on error or timeout
});
  • If the platform provides a signed timestamp, rejecting events that are too old limits replays.
  • The webhook secret lives in an environment variable, different for sandbox and production.
  • Responding quickly matters: long processing inside the request causes timeouts and resends.

Process each event only once

Platforms generally guarantee “at least once” delivery: the same event may arrive several times (resent after a timeout, network incident). Without precautions, an order would be created twice. The solution: store each event's identifier under a uniqueness constraint, and only process new ones.

sql
CREATE TABLE webhook_events (
  platform     text        NOT NULL,
  event_id     text        NOT NULL,
  payload      jsonb       NOT NULL,
  received_at  timestamptz NOT NULL DEFAULT now(),
  processed_at timestamptz,
  PRIMARY KEY (platform, event_id)
);

-- No row returned: the event was already received, so it is not processed a second time.
INSERT INTO webhook_events (platform, event_id, payload)
VALUES ($1, $2, $3)
ON CONFLICT (platform, event_id) DO NOTHING
RETURNING event_id;

Events can also arrive out of order (an update before the creation). The order core therefore applies explicit status transition rules and ignores an inconsistent transition rather than overwriting a more recent state.

Call the platform's API with OAuth 2.0

To accept an order, update a status or manage a menu, the server calls the platform's API with an OAuth 2.0 access token. For server-to-server exchanges, the “client credentials” flow is common; some operations require an authorization flow by the account holder. The token is cached and renewed before it expires.

ts
let cached: { token: string; expiresAt: number } | null = null;

export async function getAccessToken() {
  if (cached && Date.now() < cached.expiresAt - 60_000) return cached.token;

  const res = await fetch(process.env.OAUTH_TOKEN_URL!, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "client_credentials",
      client_id: process.env.OAUTH_CLIENT_ID!,
      client_secret: process.env.OAUTH_CLIENT_SECRET!,
      scope: process.env.OAUTH_SCOPES ?? "",
    }),
  });
  if (!res.ok) throw new Error(`Token request failed: ${res.status}`);

  const data = await res.json();
  cached = { token: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 };
  return cached.token;
}
  • Only request the permissions (scopes) you need.
  • Separate credentials and URLs for sandbox and production, provided through environment variables.
  • Handle 401 (expired or revoked token) and 429 (too many requests) responses with spaced-out retries.

Normalise with adapters

Every platform has its own vocabulary: statuses, item and option structures, amount formats, time zones. The adapter converts all of this into the common model, for example amounts in cents and dates in UTC, with a status mapping table. The raw event is kept for auditing and troubleshooting.

Running the integration day to day

  • Structured logs with a correlation ID, from reception to the order being created.
  • Alerts on invalid signatures, processing failures and token renewal failures.
  • A queue of events that failed after several attempts, with a tool to replay them once the cause is fixed.
  • Systematic sandbox testing before any adapter goes to production.

These practices are at the heart of our Systems Integration & Automation expertise.

Key takeaways

  • A single order model and one adapter per platform make it possible to add channels without rewriting the core.
  • Verify the signature over the raw body, in constant time, then respond immediately.
  • Idempotency relies on a uniqueness constraint in the database, not on fragile application-level checks.
  • Sandbox and production have separate credentials and secrets.

Keywords

  • Webhooks
  • OAuth 2.0
  • Idempotency
  • Node.js

Contact

A technical question or a project? Let's talk.

Tell us about your need, your context or your technical challenge. We'll get back to you to discuss it, with no commitment.