Receive and verify webhooks

Build your endpoint: the request format, HMAC signature verification, and how to respond.

Build the endpoint that receives Preczn webhook notifications. Your endpoint confirms that each notification came from Preczn, hands it off for processing, and acknowledges it within 5 seconds.


Prerequisites

  • A webhook subscription that points at your endpoint. See Subscribe to webhooks.
  • The subscription's signing secret. The API returns it when you create the subscription, and you can reveal it in the Dashboard under Settings → Webhooks with the Reveal signing secret action. Each subscription has its own secret.
⚠️

Treat the signing secret as a credential

Anyone who holds it can sign a request that passes verification. Store it the way you store your private API keys.


What Preczn sends

Each notification is an HTTP POST with a JSON body. Every event type uses the same four top-level fields. Only data changes shape.

FieldDescription
idIdentifies this notification. Starts with what_ in Live mode and what_test_ in Test mode. It changes when Preczn sends the same event again. See Duplicate notifications
webhookIdThe subscription that sent the notification. Starts with wh_ or wh_test_
eventTypeThe event, such as transaction.approved
dataThe record the event is about. Its shape depends on eventType
{
  "id": "{notificationId}",
  "webhookId": "{webhookId}",
  "eventType": "transaction.approved",
  "data": {}
}

For the shape of data, see Transaction webhook payloads, Merchant webhook payloads, Loan webhook payloads, and Boarding form webhook payloads.

Each notification carries these headers:

HeaderValue
X-Preczn-Signaturev1= followed by the signature of the request body
User-AgentPreczn/ followed by a version that changes over time
Content-Typeapplication/json
Your custom headerSent only when the subscription has one

A custom header helps your endpoint's own authentication, but it doesn't prove that the request came from Preczn or that the body is unchanged. Only the signature does. Verify the signature even when you use a custom header.


Handle a notification

Acknowledge first, then process. Your endpoint verifies the signature, puts the notification on your own queue, and returns 2xx. A separate worker does the real work afterward.

sequenceDiagram
    participant P as Preczn
    participant E as Your endpoint
    participant Q as Your queue
    participant W as Your worker
    P->>E: POST notification with X-Preczn-Signature
    E->>E: Verify the signature over the raw body
    E->>Q: Enqueue the notification
    E-->>P: 2xx within 5 seconds
    Q-->>W: Deliver the notification
    W->>W: Apply the change by record ID

To handle each notification, your endpoint does the following:

  1. Read the raw request body as bytes, before any JSON parsing.
  2. Read the X-Preczn-Signature header and remove the v1= prefix.
  3. Compute an HMAC with SHA-256 over the raw body, using the subscription's signing secret as the key. Encode the result as lowercase hexadecimal.
  4. Compare your value with the header value in constant time. If they don't match, reject the request and don't act on it.
  5. Put the notification on your queue, or write it to a table, and return any 2xx status.

Return 2xx for every notification you verify, including event types you ignore. Any other response counts as a failed delivery, and too many failures in a row disable the subscription. Every attempt for one event shares one 5-second budget. For what Preczn retries and when it disables a subscription, see Delivery attempts.

⚠️

Two things break signature verification

Re-serialized JSON. Compute the signature over the body bytes exactly as received. If your framework parses the JSON and you serialize it again, key order and whitespace can change, and the signature never matches.

Character encoding. The body is UTF-8. Encode the signing secret as UTF-8 too, rather than relying on a platform default.

The following example handler captures the raw body, verifies the signature, enqueues the notification, and returns 2xx. Replace enqueue with your own queue or background job.

const crypto = require('crypto');
const express = require('express');

const app = express();
const SIGNING_SECRET = process.env.PRECZN_SIGNING_SECRET;

function isValidSignature(rawBody, header, secret) {
  if (!header || !header.startsWith('v1=')) return false;
  const received = Buffer.from(header.slice(3), 'utf8');
  const expected = Buffer.from(
    crypto.createHmac('sha256', secret).update(rawBody).digest('hex'),
    'utf8'
  );
  // timingSafeEqual throws when the lengths differ, so check the length first.
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

// express.raw keeps the body as the exact bytes Preczn signed.
app.post('/webhooks/preczn', express.raw({ type: 'application/json' }), (req, res) => {
  if (!isValidSignature(req.body, req.get('X-Preczn-Signature'), SIGNING_SECRET)) {
    return res.sendStatus(401);
  }
  enqueue(JSON.parse(req.body.toString('utf8')));
  res.sendStatus(200);
});
import hashlib
import hmac
import json
import os

from flask import Flask, request

app = Flask(__name__)
SIGNING_SECRET = os.environ["PRECZN_SIGNING_SECRET"].encode("utf-8")


def is_valid_signature(raw_body, header):
    if not header or not header.startswith("v1="):
        return False
    expected = hmac.new(SIGNING_SECRET, raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(header[3:].encode("utf-8"), expected.encode("utf-8"))


@app.post("/webhooks/preczn")
def preczn_webhook():
    raw_body = request.get_data()  # the exact bytes Preczn signed
    if not is_valid_signature(raw_body, request.headers.get("X-Preczn-Signature")):
        return "", 401
    enqueue(json.loads(raw_body))
    return "", 200
using System;
using System.Security.Cryptography;
using System.Text;

static bool IsValidSignature(byte[] rawBody, string header, string signingSecret)
{
    if (string.IsNullOrEmpty(header) || !header.StartsWith("v1=")) return false;
    using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(signingSecret));
    string expected = Convert.ToHexString(hmac.ComputeHash(rawBody)).ToLowerInvariant();
    return CryptographicOperations.FixedTimeEquals(
        Encoding.UTF8.GetBytes(header.Substring(3)),
        Encoding.UTF8.GetBytes(expected));
}

To test your check, change one character of a signed body on purpose and confirm that your handler rejects it. A check that accepts everything looks the same as a working one until it matters.


Make processing idempotent

The same event can reach your endpoint more than once, and notifications can arrive in any order. The id changes between copies, so don't rely on it alone. See Duplicate notifications.

Make your worker's effect idempotent:

  • Key off the record, not the notification. Apply changes by the identifier inside data, such as data.id for a transaction or data.formId for a boarding form, so that handling the same state twice converges instead of counting twice.
  • Ignore stale state. When data carries a timestamp such as modifiedOn, compare it with what you've stored, and discard anything older.

Handling the same notification twice should leave your system in the same state as handling it once.


FAQ

My signature never matches. What's wrong?

In nearly every case, the body you hash isn't the raw body. Frameworks that parse JSON automatically hand you a re-serialized version whose bytes differ from what Preczn sent. Capture the raw body before any parsing or middleware runs, and hash that.

Then check these:

  • You use the signing secret of the subscription named in webhookId. With several subscriptions, it's easy to use the wrong one.
  • You compare hexadecimal, not Base64.
  • You removed the v1= prefix.
Can I skip verification if I allowlist Preczn's IP addresses?

No. An IP allowlist confirms where a request came from, but not that its body is unchanged. Signature verification is the supported way to confirm a notification came from Preczn.

How do I see what Preczn sent?

In the Dashboard, open the subscription's Webhook Attempts. Each entry records the request body, the response or error Preczn received, the endpoint URL, and whether the delivery succeeded. See Delivery history.

How do I test my endpoint before going live?

Create a subscription with a test API key, or in the Dashboard in Test mode, and generate activity in Test mode. Test mode notifications never reach a Live subscription. See Live vs. test mode.


Did this page help you?