Documentation / Integration guide / Part 16 of 18

16. Webhooks

Norspire sends each subscription event of your publication to your server, for example to your CRM. An event is 1 POST with a JSON body and a signature. Your receiver checks the signature, stores the event, and answers with a 2xx status. Use the entitlement read of part 17 when your server needs the access of 1 reader at once.

See also the Webhooks page in the API reference for the full schema from the public contract.

The endpoint and the signing secret

  1. An admin of the publication opens the Integration page and selects the tab Webhooks.
  2. The admin enters the address of your receiver in Endpoint address and selects Add endpoint.
  3. The page shows the signing secret 1 time. Copy it into the secret store of your server. Never put it in a page, in the repository or in a command line.

The secret is whsec_ and the standard base64 text of 30 random bytes. After a reload, the page shows the last 4 characters of the secret only. A publication has 5 endpoints at most. Each endpoint has its own secret. The tab Webhooks also shows the delivery log of the last 30 days: each attempt, its result and its status. The log shows no body and no email address.

Change a signing secret

An endpoint keeps its secret. To change it with no downtime, use 2 endpoints:

  1. Add an endpoint with the same address. The page shows a new secret.
  2. Set both secrets on your receiver. The function of this part takes a list of secrets.
  3. Delete the old endpoint on the tab Webhooks. Norspire sends no new attempt to a deleted endpoint.
  4. Remove the old secret from your receiver.

While both endpoints exist, your receiver gets each event 2 times. Each copy has its own signature and the same event ID. Your receiver stores the event 1 time, as the rule of the event ID says.

The 3 headers and the signature check

Norspire signs each request by the method of Standard Webhooks, version v1. A library of Standard Webhooks can also check it. Each request has these 3 headers:

The 3 signature headers on each webhook request
HeaderValue
webhook-idThe event ID. It is the same in each attempt of an event, and it equals id in the body.
webhook-timestampThe time of the attempt, in whole seconds since the epoch. It changes in each attempt.
webhook-signatureA list split by spaces. Each item is v1, and the standard base64 text of the signature.

The request also has content-type: application/json and user-agent: Norspire-Webhooks/1.

Check each request in this order. Answer HTTP 400 and store nothing when 1 step fails:

  1. Refuse a body above 64 KiB with 413 before you read the rest of it. An event of Norspire is far below that size. Then read the raw text of the body before your framework parses it. The signature covers these exact bytes. A body that your server wrote again gives another signature.
  2. Read the 3 headers. A missing header fails the check.
  3. Read webhook-timestamp as a whole number. Refuse a time more than 5 minutes before or after your own clock. The next section gives the reason.
  4. Take the secret of the endpoint. Remove whsec_ and decode the rest from base64. The result is the key of 30 bytes.
  5. Compute HMAC-SHA256 of the text <webhook-id>.<webhook-timestamp>.<raw body> with that key. Write the result as standard base64 text.
  6. Read each item of webhook-signature that starts with v1,. Ignore an item with another version. Accept the event when 1 item equals your value.
  7. Compare the 2 values in constant time. Do not compare them with ==.

The file docs/examples/verify-webhook.mjs does these steps. It is plain Node.js with no package. Copy the function into your receiver. The function takes the raw body, the headers and the secret, and it gives { ok: true } or { ok: false, reason }.

import { createHmac, timingSafeEqual } from 'node:crypto';

// Checks 1 webhook event of Norspire. It is plain Node.js with no package. Copy the function into
// your receiver. Give it the RAW text of the body, as your server read it, and not a body that your
// framework parsed and wrote again. 1 changed character in the body gives another signature.

/** The window of the guide: a timestamp more than 5 minutes before or after your clock fails. */
export const WINDOW_SECONDS = 300;

/** The 3 headers of each event. Node gives header names in lower case. */
export const HEADER_ID = 'webhook-id';
export const HEADER_TIMESTAMP = 'webhook-timestamp';
export const HEADER_SIGNATURE = 'webhook-signature';

/**
 * The key bytes of a signing secret: `whsec_` and the standard base64 text of the key. A text of
 * another form is a defect of your configuration, so the function throws and never answers `ok`.
 */
function keyOf(secret) {
  if (typeof secret !== 'string' || !secret.startsWith('whsec_')) {
    throw new TypeError('A signing secret starts with whsec_.');
  }
  const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
  if (key.length === 0) throw new TypeError('The signing secret holds no key.');
  return key;
}

/** The value of a header, from a Node `headers` object or from a `Headers` object. */
function headerOf(headers, name) {
  const value = typeof headers.get === 'function' ? headers.get(name) : headers[name];
  return typeof value === 'string' ? value : null;
}

/**
 * Checks the signature and the time of 1 event.
 *
 * - `secret`: the signing secret of the endpoint, or a list of secrets while you change a secret.
 * - `headers`: the headers of the request.
 * - `body`: the raw text of the body.
 * - `now`: your clock in milliseconds. The default is `Date.now()`. A value that is not a finite
 *   number is a defect of your code, so the function throws and never turns the window off.
 *
 * It gives `{ ok: true }`, or `{ ok: false, reason }` with the reason `headers`, `timestamp` or
 * `signature`. Answer a request that fails with a 4xx status and store nothing.
 */
export function verifyWebhook({ secret, headers, body, now = Date.now() }) {
  if (!Number.isFinite(now)) throw new TypeError('now is your clock in milliseconds.');
  const id = headerOf(headers, HEADER_ID);
  const timestamp = headerOf(headers, HEADER_TIMESTAMP);
  const signature = headerOf(headers, HEADER_SIGNATURE);
  if (id === null || timestamp === null || signature === null || typeof body !== 'string') {
    return { ok: false, reason: 'headers' };
  }
  // The timestamp is whole seconds. Refuse a time outside the window before you check the signature.
  if (!/^\d{1,12}$/.test(timestamp)) return { ok: false, reason: 'timestamp' };
  if (!(Math.abs(Math.floor(now / 1000) - Number(timestamp)) <= WINDOW_SECONDS)) {
    return { ok: false, reason: 'timestamp' };
  }
  // The header is a list split by spaces. Each item is `v1,` and the base64 text of the signature.
  // A list can hold more than 1 item, so read each `v1,` item and ignore another version.
  const given = signature
    .split(' ')
    .filter((item) => item.startsWith('v1,'))
    .map((item) => Buffer.from(item.slice('v1,'.length), 'base64'));
  for (const candidate of Array.isArray(secret) ? secret : [secret]) {
    const expected = createHmac('sha256', keyOf(candidate))
      .update(`${id}.${timestamp}.${body}`)
      .digest();
    // `timingSafeEqual` needs 2 values of the same length. A length is no secret.
    if (
      given.some((value) => value.length === expected.length && timingSafeEqual(value, expected))
    ) {
      return { ok: true };
    }
  }
  return { ok: false, reason: 'signature' };
}

A receiver in a framework passes the raw text of the body to the function. The demo site in the repository implements this in demo/site.tsx. It answers 204 for accepted or repeated events, and 400 for requests that fail the check.

The window of 5 minutes

A receiver refuses a timestamp more than 5 minutes before or after its own clock. A copy of an old request then fails, also with a valid signature. Keep the clock of your server correct with NTP. Each attempt of an event has a new timestamp and a new signature, so a retry after 3 days passes the check.

The event types and the body

Each event has 1 of these 20 types. A later version can add a type, by the rule of unknown values below.

The 20 webhook event types and their meanings
TypeMeaning
subscription.createdA reader started a subscription. The subscription is active or in its trial.
charge.succeededA charge of the subscription succeeded. The member charge holds its amount.
charge.failedA charge of the subscription failed. The member charge holds its amount. The subscription can be past_due.
charge.refundedA refund of a charge completed. The member refund holds its amount.
refund.failedA refund of a charge failed. The member refund holds its amount.
subscription.payment_method_changedThe reader changed the payment method of the subscription.
subscription.cancel_requestedThe reader asked to end the subscription at the end of the current period.
subscription.agreement_stoppedThe reader stopped the payment agreement in the app of the payment provider.
subscription.resumedThe reader resumed a subscription that was set to end.
subscription.withdrawnThe reader withdrew from the subscription inside the withdrawal period.
subscription.endedThe subscription ended. The member endReason gives the reason.
refund.requestedA staff member asked for a refund of a charge. The member refund holds its amount.
subscription.price_change_notifiedNorspire sent the notice of a price change to the reader.
subscription.price_change_notice_failedNorspire failed to send the notice of a price change to the reader.
subscription.plan_changedThe plan of the subscription changed at once.
subscription.plan_change_scheduledA plan change is set for the end of the current period.
subscription.plan_change_canceledThe reader or staff canceled a scheduled plan change.
subscription.plan_change_revertedA plan change failed to take payment, so the subscription returned to its earlier plan.
account.deletedThe reader deleted the account. The member reader holds no email address.
subscription.swish_consent_endedThe Swish consent of the subscription ended outside Norspire. Norspire can no longer charge the subscription.

The body is a JSON object of this form. Each time is UTC with Z. The body holds no text of a locale catalog.

{
  "id": "0193f0b2-5c1e-7a4e-9d2b-3f6a8c1e2d4f",
  "type": "subscription.created",
  "timestamp": "2027-01-10T09:00:00Z",
  "data": {
    "sequence": 1,
    "host": "konto.example.no",
    "reader": { "id": "0193f0b2-1111-7a4e-9d2b-3f6a8c1e2d4f", "email": "reader@example.no" },
    "subscription": {
      "id": "0193f0b2-2222-7a4e-9d2b-3f6a8c1e2d4f",
      "status": "active",
      "plan": { "id": "0193f0b2-3333-7a4e-9d2b-3f6a8c1e2d4f", "name": "Monthly A1" },
      "accessKeys": ["paid"],
      "currentPeriodEnd": "2027-02-10T09:00:00Z",
      "cancelAtPeriodEnd": false,
      "endsAt": null,
      "endReason": null,
      "paymentMethod": "card",
      "currency": "NOK"
    },
    "charge": null,
    "refund": null
  }
}
Fields in the JSON body of a webhook event
FieldValue
idThe event ID.
typeThe type of the event.
timestampThe time of the event, in UTC.
data.sequenceThe sequence number of the event in its subscription.
data.hostThe host of the publication.
data.reader.idThe reader ID. It does not change. It equals readerId of the entitlement read in part 17.
data.reader.emailThe email address of the reader at the time of the attempt, or null after the reader deletes the account.
data.subscriptionThe subscription after the event: id, status, plan, accessKeys, currentPeriodEnd, cancelAtPeriodEnd, endsAt, endReason, paymentMethod and currency. status is trialing, active, past_due or ended, and plan holds id and name.
data.chargenull, or { "amount": { "minor": 9900, "currency": "NOK" }, "invoiceNumber": "000001" } for the 3 charge types. invoiceNumber is null for a failed charge.
data.refundnull, or { "amount": ..., "creditNoteNumber": "000003" } for the 3 refund types. creditNoteNumber is null for a refund with no credit note.

endsAt is the end of the current period while cancelAtPeriodEnd is true, the end date of an ended subscription, or null. The member webhooks of /docs/api/openapi.json holds the schema of each type.

The sequence number

data.sequence starts at 1 for each subscription and grows by 1 for each event of that subscription. Use it to put the events of 1 subscription in order, because events can arrive in another order. A retry of an old event can come after a newer event.

An endpoint gets the events from its creation. The first event of an older subscription that your endpoint gets can have a sequence number above 1. Do not wait for the number 1.

The event ID and repeats

The event ID is the same in each attempt of an event, and it is webhook-id and id in the body. Norspire sends an event 1 time or more. Store the ID of each accepted event, and answer 2xx for an ID that you already hold. Do not process the event again.

Retries and their end

A status from 200 to 299 is a delivery. Each other result is a failure. Failures include statuses 300 to 599, timeouts, network errors and refused addresses. After a failed attempt, Norspire waits and tries again:

Wait interval after each failed webhook delivery attempt
After failed attemptWait
11 minute
210 minutes
31 hour
43 hours
56 hours
612 hours
724 hours
824 hours

Attempt 9 is about 70 hours and 11 minutes after attempt 1. After a failed attempt 9, the delivery is failed and Norspire sends no more attempts. A failed or waiting event does not stop a later event. Answer a request that you cannot accept with a status that is not 2xx, so that Norspire tries again. The delivery log of the tab Webhooks shows each attempt for 30 days.

The time limit and no redirect

Norspire waits 10 seconds for the status line and the headers of your answer, from the start of the name lookup. A later answer is a time-out. Answer first and process after. Norspire reads no body of your answer. It follows no redirect, so a status from 300 to 399 is a failure. Give the endpoint its final address.

The address rules

  • The address uses https. A development or sandbox installation also accepts http. Production refuses http.
  • The address has no user part, no password part and no fragment, and it has 2,048 characters or fewer. It can have a port, a path and a query. Norspire refuses port 0.
  • Norspire looks up the name at each attempt and connects to the address that it checked. It refuses an attempt when 1 address of the name is in a private, loopback, link-local, shared, documentation, multicast or reserved range. It also refuses a name such as localhost, a name that ends in .internal and a name with 1 label.
  • A sandbox delivers webhooks to public addresses. A development installation delivers to localhost and *.localhost names only, and the name goes to 127.0.0.1.
  • Use a certificate that a public authority signed. Norspire checks the certificate of an https address with the default store of certificate authorities.

The event account.deleted

When a reader deletes the account, Norspire sends account.deleted with the reader ID and the newest subscription. The field data.reader.email is null. A reader with no subscription gives no event. The event is the last event of the reader, and it has the next sequence number. Delete or anonymize the data that you hold for that reader ID by your own rules.

Unknown fields and unknown values

  • Ignore each field that you do not know. Norspire adds a field to a body as an addition, and it never removes or renames a field.
  • Treat an unknown value of paymentMethod or endReason as another value. Norspire adds a value, for example a new payment method, with no change of the body.
  • Answer an event of a type that you do not know with 2xx. Store it as it is, or store nothing.