Saltar al contenido principal

Tutorial: Hello World

Build a small plugin that receives all 20 SSP events, verifies every delivery, and handles each one — in about a hundred lines of Node.js.

This is the events half of the SDK. Getting Started covers creating a project, provisioning a sandbox and calling the API; Webhooks is the reference catalog with full payloads. This page is the build-along: it assumes you already have a sandbox, a pik_ API key and a webhook secret.

What you'll build​

An HTTP endpoint that:

  • verifies X-SSP-Signature against the raw request bytes,
  • answers inside SSP's 10-second budget and does the work afterwards,
  • ignores an event it has already processed,
  • and routes all 20 events to a handler.

Step 1 — Create the project​

mkdir ssp-hello-world && cd ssp-hello-world
npm init -y
npm install express dotenv

Create .env with your webhook secret. Until you create the plugin, that's the one your sandbox showed when you provisioned it. Creating the plugin issues a new one, shown once, and from then on SSP signs every delivery with it. If you missed it, Rotate secret on the plugin page issues another (and retires the old one immediately).

PORT=3000
SSP_WEBHOOK_SECRET=your_webhook_secret_here

Step 2 — Verify the signature over the raw bytes​

Every delivery carries X-SSP-Signature, the hex HMAC-SHA256 of the exact bytes SSP transmitted, keyed with your webhook secret.

Keep those bytes. express.json() gives you a parsed object, and re-serializing it is not guaranteed to reproduce what was signed:

const crypto = require('crypto');
const express = require('express');
require('dotenv').config();

const app = express();
const SECRET = process.env.SSP_WEBHOOK_SECRET;

// `verify` hands you the raw buffer before the JSON is parsed.
app.use(
'/webhooks/ssp',
express.json({
verify: (req, _res, buf) => {
req.rawBody = buf;
},
}),
);

function signatureIsValid(req) {
if (!SECRET || !req.rawBody) return false;

const received = Buffer.from(req.headers['x-ssp-signature'] || '', 'utf8');
const expected = Buffer.from(
crypto.createHmac('sha256', SECRET).update(req.rawBody).digest('hex'),
'utf8',
);

// timingSafeEqual throws when lengths differ, so compare lengths first.
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}
The mistake almost everyone makes

Signing JSON.stringify(req.body) instead of the raw buffer. It often works in testing and then rejects valid production traffic, because key order, whitespace and unicode escaping can all differ from the bytes that were signed.

A correctly signed body sent as { "event" : "order.paid" , … } produces:

hmac over raw bytes     673a14935b01d2866d9e…
hmac over re-serialized ff092db53a12264500d1…

Two different signatures for one valid request. Always hash req.rawBody.

Step 3 — Don't process the same event twice​

SSP makes up to three attempts, and a network failure after your handler succeeded is indistinguishable from one before it. Every delivery carries an event_id (also sent as the X-SSP-Delivery header) that is the same on every retry of one event, and different for every new event:

const seen = new Set();                       // a real plugin uses its database

function deliveryId(req) {
return req.body.event_id ?? req.headers['x-ssp-delivery'] ?? null;
}

Key on event_id, not on the order or the item. An order's second status change or a second edit of one menu item is new information with its own event_id; a key built from order_id alone would swallow it as if it were a retry.

Persist the handled event_ids in your database, not in memory: a restart must not replay. Make each handler idempotent as well (apply new_status rather than "advance one step", upsert the menu item rather than append), so that work interrupted half-way can safely run again.

Step 4 — Answer fast​

You have 10 seconds. Verify, skip a repeat, acknowledge, then work:

app.post('/webhooks/ssp', (req, res) => {
if (!signatureIsValid(req)) {
return res.status(401).json({ error: 'invalid_signature' });
}

const id = deliveryId(req);
if (id && seen.has(id)) {
return res.json({ status: 'duplicate' }); // already handled: still a 2xx
}
if (id) seen.add(id);

res.json({ status: 'accepted' }); // acknowledge first

setImmediate(() => { // a real plugin uses a job queue
handleEvent(req.body).catch((err) => console.error(`handler failed: ${err.message}`));
});
});

Return 2xx even for events you don't care about. A non-2xx triggers retries that will never succeed.

Step 5 — A handler for every event​

All 20, in eight families:

EventFires when
installation.createdAn organization installs and activates your plugin
installation.removedAn organization uninstalls your plugin
trial.startedA free trial begins for a paid plugin
trial.endingThree days, and again one day, before a trial converts to paid (days_remaining)
subscription.activatedA paid subscription becomes active, at checkout or on trial conversion
order.createdAn order becomes real — see the note below
order.items_addedDishes are added to an accepted order, once per add
order.status_changedAn order's status changes, with old_status and new_status
order.paidAn order is marked paid
order.cancelledAn order is cancelled
payment.succeededA payment is captured (never a refund)
payment.failedA guest's card payment attempt fails, once per attempt
payment.refundedMoney goes back, by refund or void (positive amount, transaction_type REFUND / VOID)
menu.item_createdA menu item is created
menu.item_updatedA menu item is updated
menu.item_deletedA menu item is deleted
inventory.stock_updatedAn ingredient's stock level changes, after every movement
inventory.low_stockStock drops to or below the reorder point, with no alert already active
inventory.low_stock_resolvedStock rises back above the reorder point while an alert is active
sandbox.expiry_warningSeven days before idle-expiry would drop your sandbox schema
order.created means accepted, not inserted

An order awaiting the restaurant's acceptance sends no event at all. The event fires once, when the restaurant accepts it, so you never print, push or start a prep timer for food nobody has agreed to cook. An order the restaurant rejects never becomes real and sends nothing.

Route them:

const log = (label) => (data, envelope) =>
console.log(` ${label}`, JSON.stringify({ installation: envelope.installation_id, ...data }));

const handlers = {
'order.created': log('New order'),
'order.items_added': log('Items added'),
'order.status_changed': log('Status changed'),
'order.paid': log('Order paid'),
'order.cancelled': log('Order cancelled'),

'payment.succeeded': log('Payment succeeded'),
'payment.failed': log('Payment failed'),
'payment.refunded': log('Payment refunded'),

'menu.item_created': log('Menu item created'),
'menu.item_updated': log('Menu item updated'),
'menu.item_deleted': log('Menu item deleted'),

'inventory.stock_updated': log('Stock moved'),
'inventory.low_stock': log('Low stock'),
'inventory.low_stock_resolved': log('Low stock resolved'),

'installation.created': log('Installed'),
'installation.removed': log('Uninstalled'),

'trial.started': log('Trial started'),
'trial.ending': log('Trial ending'),
'subscription.activated': log('Subscription active'),

'sandbox.expiry_warning': log('Sandbox expiring'),
};

async function handleEvent(envelope) {
const handler = handlers[envelope.event];
if (!handler) {
console.log(` (no handler for ${envelope.event} — ignored)`);
return;
}
await handler(envelope.data ?? {}, envelope);
}

Replace each log(…) with real work as you build. Read the fields you need and ignore the rest — payloads gain fields over time, and an unrecognised key must never fail a handler. Full payloads per event: Webhooks.

Don't shadow process

Naming that function process shadows Node's global, and process.env silently becomes undefined — the server then crashes on startup reading your config.

Step 6 — Subscribe​

Set supported_events on your plugin listing. Wildcards cover a family:

{ "supported_events": ["order.*", "payment.*", "menu.*", "inventory.*", "installation.*", "trial.*", "subscription.*", "sandbox.*"] }
Lifecycle events need explicit opt-in

With an explicit supported_events list, the installation, subscription and trial families are not included by default. A plugin that provisions tenants headlessly must subscribe to installation.*. Leaving supported_events unset subscribes you to everything; an empty list ([]) to nothing.

Step 7 — Run it and prove it works​

Finish index.js by starting the server:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
node index.js
# ◇ injected env (2) from .env
# listening on 3000

The first line is dotenv (17 and later) reporting what it loaded. Use require('dotenv').config({ quiet: true }) to turn it off.

Send a correctly signed event:

SECRET=your_webhook_secret_here
BODY='{"event_id":"0b9a6c1e-4f1d-4a6e-9c55-2d1f0f3e7a10","event":"order.created","timestamp":"2026-05-30T12:00:00+00:00","installation_id":42,"data":{"order_id":1001,"unique_orderid":"ABC12345","table_number":"7","total":48.5}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //')

curl -s -X POST http://127.0.0.1:3000/webhooks/ssp \
-H "Content-Type: application/json" \
-H "X-SSP-Event: order.created" \
-H "X-SSP-Signature: $SIG" \
--data-raw "$BODY"

What you should see:

valid signature      -> 200 {"status":"accepted"}
replay (same event) -> 200 {"status":"duplicate"}
wrong signature -> 401 {"error":"invalid_signature"}
no signature -> 401 {"error":"invalid_signature"}
tampered body -> 401 {"error":"invalid_signature"}

And in the server log:

  New order {"installation":42,"order_id":1001,"unique_orderid":"ABC12345","table_number":"7","total":48.5}

A replay returning 200 rather than an error is deliberate — the event was handled, so the delivery succeeded.

Step 8 — Let SSP reach you​

SSP delivers only to public HTTPS addresses, checked at delivery time: a rejected URL shows up as a failed log entry, not as an error when you save it. An http:// URL, localhost, a LAN IP or host.docker.internal is rejected — even by a backend running on your own machine. Expose your local server through a tunnel:

ngrok http 3000
# use https://<id>.ngrok-free.app/webhooks/ssp as your webhook_endpoint

When you create the plugin in the Developer Portal (Create plugin on your project), step 2 is where SSP learns where to deliver:

FieldWhat to enter for this tutorial
Integration typeWebhook
Webhook endpointhttps://<id>.ngrok-free.app/webhooks/ssp — every delivery goes here. Required for a Webhook plugin
API endpointLeave it empty. It's where SSP would call your API, and this plugin doesn't have one
API keyLeave it empty. SSP presents it only when calling your API

Step 3 is the subscription from Step 6: Select all in each group subscribes you to every event by name. Copy the webhook secret shown after Create plugin into .env and restart the server.

Then fire a test from the sandbox's Webhook Tester and poll the returned log ID for the outcome. Sandbox ids start at 1000000000, so a test order.created carries an id like that, not 1. A test delivery's data is the real event's, and its envelope adds "test": true.

Real events work too, while the plugin is still a draft. Open SSP Manager against your sandbox (Open SSP Manager on the sandbox page) and create an order: your server logs order.created, and an order.status_changed each time its status moves.

When delivery fails​

PropertyValue
Request timeout10 seconds
Attempts3 in total
Backoff60s before the second attempt, 300s before the third
SuccessAny 2xx
RedirectsNot followed

A skipped log means SSP never attempted delivery — no endpoint, no secret, the event isn't in your subscriptions, or the installation isn't active. An organic event that gets filtered out writes no log row at all, so an empty log is itself a signal that your subscription or endpoint is misconfigured.

What's next​