Getting started

Webhooks

Webhooks let Qualy tell your systems when something happens in your account, so your integration doesn't have to poll the API. You register an HTTPS endpoint, and Qualy sends it a signed POST request each time a subscribed event occurs.


How webhooks work

  1. You register an HTTPS destination URL and a secret in the Qualy Dashboard (or through the API), and choose the events it should receive.
  2. Qualy checks that you control the URL with a one-time verification challenge.
  3. When a subscribed event happens, for example a direct debit transaction is approved or a payment becomes overdue, Qualy sends a JSON payload to your URL, signed with your secret.
  4. Your endpoint verifies the signature, returns a 2xx response quickly, and processes the event.

If your endpoint doesn't answer with a 2xx, Qualy retries the delivery for just over a day.

Treat webhooks as a fast signal, not your only source of truth. In rare cases an event may not reach you at all, so reconcile important state through the API.

See the events reference for every event Qualy sends.


The event payload

A single action can create several events. For example, when a customer pays, you can receive transactions.create, paymentIntents.update, splitIntents.create, splitIntents.update and transactions.update.

Every delivery is a POST with a JSON body in the same envelope. This one is a transaction created by a PayTo direct debit:

{
  "event": "transactions.create",
  "tenantId": "eu1-nonhozilnwbeuo1qkdftdkqg",
  "messageId": "8960447655358365",
  "version": "v1",
  "data": {
    "_id": "653fc551d14abfe63d4fd48b",
    "paymentIntent": "653fc43fd14abee63d4fcb63",
    "amount": 87700,
    "contact": "65351dfbde8f28fb4a757585",
    "transactionType": "charge",
    "method": "ZAI_PAYTO",
    "currency": "AUD",
    "documents": [],
    "status": "processing",
    "createdAt": "2023-10-30T15:01:37.187Z",
    "number": 1906
  }
}
PropertyDescription
eventThe event type, in resource.action form. Use it to decide how to process the delivery. The shape of data depends on it.
tenantIdThe Qualy account that generated the event. Each Qualy account is a tenant in our multi-tenant infrastructure. If one endpoint receives events for several Qualy accounts, use this to tell them apart.
messageIdUnique per event, and the same on every retry of that event. Use it to ignore duplicates.
versionThe API version the data object follows. Currently v1, matching the v1 API.
dataThe object the event is about. Its content depends on the event.

Request headers

HeaderDescription
Signature-Headersha256=<hex>: an HMAC-SHA256 of the raw request body, keyed with your webhook secret. See verifying signatures.
Webhook-Signaturet=<unix seconds>,v1=<hex>: an HMAC-SHA256 of <t>.<raw body>, keyed with your webhook secret. It includes the time of the attempt, so you can reject replayed requests.
Webhook-Delivery-Attempt1 for the first attempt, 2 for the first retry, and so on.
Content-Typeapplication/json

Why events get generated

SourceTrigger
DashboardQualy users change payments, contacts and other objects in the Dashboard.
Contact portalCustomers make a payment or change an object in the tenant's contact portal, for example paying by card.
Partner portalA partner changes their details, adds a bank account and so on, in their partner portal.
APIYou call the API directly.
External eventsQualy receives an external event, such as a direct debit failure or an incoming bank transfer.

Setting up a webhook

Only super admins can manage webhooks in the Dashboard.

  1. Open the Qualy Dashboard.
  2. Click the Settings icon in the top-right corner.
  3. Click API keys & webhooks.
  4. Click Add new.
  5. Enter your destination URL and a secret, and choose the events you want to receive. The URL must meet the destination rules.
  6. Make sure your endpoint answers the verification challenge, then click Save.

You choose the secret, so store it in your secrets manager. Use the whole secret string as the HMAC key when you verify signatures.

To stop deliveries, click Remove next to the webhook in API keys & webhooks. Once a webhook is removed, Qualy stops queued and future deliveries to it. An attempt already in progress at that moment may still arrive.

Each Qualy account can have up to 100 active webhooks, including ones that integrations create, and one active webhook per destination URL. Super admins get a notification when a webhook is created, and when Qualy deactivates one after repeated delivery failures. Removing a webhook yourself doesn't send one.

Creating a webhook via the API

To create, list and remove webhooks with the Qualy API, see the Webhooks API reference. The same verification challenge and destination rules apply.

Destination rules

  • The URL must use https.
  • It must resolve to a public internet address. Qualy refuses private, internal, loopback and link-local addresses.
  • It must not include a username or password.

Qualy checks the address again before every delivery. If your hostname starts resolving to a private address, Qualy refuses the delivery and doesn't retry it.


One-time verification challenge

When you add a webhook, Qualy first sends a GET request to your URL with a random validationToken query parameter:

GET https://example.com/webhooks/qualy?validationToken=5f2c0d…

Your endpoint must reply within 30 seconds with a 2xx status and the token, exactly as received, as a plain-text body, with no added whitespace or newline. Redirects aren't followed. If it doesn't reply correctly, the webhook isn't created and you'll see an error.

app.get('/webhooks/qualy', (req, res) => {
  const { validationToken } = req.query

  if (typeof validationToken !== 'string') {
    return res.status(400).send('Missing validationToken')
  }

  res.type('text/plain').send(validationToken)
})

Your URL must answer both GET (the challenge) and POST (deliveries).


Verifying signatures

Every delivery is signed with your webhook secret, so you can confirm it came from Qualy and wasn't changed on the way. Verify one of the two signature headers before you trust a delivery. We recommend Webhook-Signature, because its timestamp also protects you against replayed requests.

Sign the raw body, not the parsed one

Compute the HMAC over the raw request body, the exact bytes Qualy sent. Parsing the JSON and serializing it again can reorder keys or change whitespace, and then no signature will match. In Express, capture the raw body with express.json({ verify: (req, _res, buf) => { req.rawBody = buf } }).

  1. Split the header on , and each part on the first =, to get t and v1.
  2. Compute HMAC-SHA256 of the string <t>.<raw body> (the timestamp, a dot, then the raw body) with your secret, as hex.
  3. Compare it with v1 in constant time. If the header carries more than one v1, accept the delivery when any of them matches.
  4. Reject the delivery if t is more than 5 minutes away from your clock.

Each retry carries a fresh t, so a delivery that's retried later still passes the time check.

import crypto from 'node:crypto'
import express from 'express'

const app = express()
const secret = process.env.QUALY_WEBHOOK_SECRET // the whole secret string
const TOLERANCE_SECONDS = 5 * 60

function verifyWebhookSignature(header, rawBody) {
  let t = ''
  const signatures = []
  for (const part of header.split(',')) {
    const i = part.indexOf('=')
    const key = part.slice(0, i).trim()
    const value = part.slice(i + 1).trim()
    if (key === 't') t = value
    if (key === 'v1') signatures.push(value)
  }

  if (!/^\d+$/.test(t)) return false
  if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE_SECONDS) return false

  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${t}.`)
    .update(rawBody)
    .digest()

  // Check the format first: timingSafeEqual throws when lengths differ.
  return signatures.some(
    (v1) =>
      /^[0-9a-f]{64}$/i.test(v1) &&
      crypto.timingSafeEqual(Buffer.from(v1, 'hex'), expected),
  )
}

app.post(
  '/webhooks/qualy',
  express.json({ verify: (req, _res, buf) => { req.rawBody = buf } }),
  (req, res) => {
    if (!verifyWebhookSignature(req.get('Webhook-Signature') ?? '', req.rawBody)) {
      return res.status(401).send('Invalid signature')
    }

    // Acknowledge first, then process asynchronously.
    res.sendStatus(204)
    handleEvent(req.body).catch((error) => console.error('Webhook processing failed', error))
  },
)

Using Signature-Header

Signature-Header is sha256= followed by the hex HMAC-SHA256 of the raw body. Compute the same value and compare the whole string in constant time:

const expected =
  'sha256=' + crypto.createHmac('sha256', secret).update(req.rawBody).digest('hex')
const received = req.get('Signature-Header') ?? ''

// Check the format first, so both strings are ASCII and the same length.
const valid =
  /^sha256=[0-9a-f]{64}$/i.test(received) &&
  crypto.timingSafeEqual(Buffer.from(received.toLowerCase()), Buffer.from(expected))

It has no timestamp, so it doesn't protect against replays on its own. Pair it with duplicate handling on messageId.


Event delivery behaviors

Responses

Qualy treats any 2xx status as delivered. Anything else counts as a failed attempt: a 3xx, 4xx or 5xx status, no answer within 30 seconds, or a connection error.

Qualy doesn't follow redirects, so a 301 or 302 is a failure. Register the final URL.

Retries

After a failed attempt, Qualy tries again on this schedule:

AttemptSent after the previous attemptTime since the first attempt
21 minute1 minute
35 minutes6 minutes
430 minutes36 minutes
52 hours2 hours 36 minutes
66 hours8 hours 36 minutes
712 hours20 hours 36 minutes
86 hours26 hours 36 minutes

That's 8 attempts over about 26½ hours. If the last attempt fails, Qualy stops trying that event.

If your endpoint responds 410 Gone, Qualy stops retrying that event straight away and the webhook stays active for future events, unless that delivery had already been waiting 24 hours (see deactivation).

While one event is being retried, Qualy keeps sending new events, so be ready to receive them out of order.

Deactivation

If a delivery has been waiting 24 hours or more since it was queued and its next attempt also fails, with any status including 410, Qualy deactivates the webhook. The last retry comes after that point, so an event that fails every attempt also deactivates the webhook. Once it's deactivated:

  • Super admins get a notification.
  • It no longer appears in API keys & webhooks.
  • Events that hadn't been delivered yet aren't sent.
  • Events created while it's off aren't queued and won't be sent later.

To start receiving events again, fix your endpoint, then add the webhook again. Use the API to fetch anything you missed in the meantime.

Event ordering

Qualy doesn't guarantee that events arrive in the order they happened, and a retried event can arrive after newer ones. For example, a direct debit transfer might generate these events:

  • transactions.create
  • paymentIntents.update
  • splitIntents.create
  • splitIntents.update (if there are splits to partners)
  • transactions.update

Your endpoint shouldn't expect them in this order. Use the timestamps in data, such as updatedAt, and fetch the latest state from the API when the order matters. For example, you can fetch the payment, transaction and splits using the IDs in the event.


Best practices

Handle duplicate events

Your endpoint may occasionally receive the same event more than once, for example if your 2xx response was lost. Record the messageId of each event you've processed and skip any you've already seen.

Return a 2xx quickly

Acknowledge the delivery before doing slow work. Put the event on a queue or background job and return 2xx straight away. A slow response can hit the 30-second limit and be retried even though you received it.

Reconcile with the API

Webhooks tell you something changed. They don't guarantee you'll hear about every change. For anything that matters, such as marking an invoice paid, confirm the current state with the API, for example GET /v1/payment-intents/{id}, and periodically check for anything you may have missed.

Verify every delivery

Check the signature on every POST before acting on it, and keep your secret out of source control.

Subscribe only to what you need

Choose only the events your integration uses. Listening for extra events, or all of them, puts needless load on your server.

Use HTTPS on a public address

Destination URLs must use https and resolve to a public internet address, with no username or password in the URL. See the destination rules.

Previous
Creating your API keys