Skip to content

Verify Square webhooks

Verify that a webhook really came from Square before acting on it.

Identifier 'square'
Import import { verifySquare } from 'verihook/square'
Headers x-square-hmacsha256-signature
Signature HMAC-SHA256 of <notification URL><raw body>, base64-encoded.
Replay window None (the provider sends no timestamp)
result.eventType the body’s type, e.g. payment.updated

The subscription’s Signature Key: in the Square Developer Console, open your application → Webhooks → Subscriptions and select the subscription.

Store it in an environment variable (SQUARE_WEBHOOK_SIGNATURE_KEY below) and never commit it.

import { verifySquare } from 'verihook/square';
export async function POST(request: Request) {
const result = await verifySquare(request, process.env.SQUARE_WEBHOOK_SIGNATURE_KEY!);
if (!result.valid) {
console.warn(result.code, result.reason, result.hint);
return new Response('Invalid signature', { status: 401 });
}
console.log(result.eventType, result.event);
return Response.json({ received: true });
}

request can be a Fetch Request or { headers, body, url? } with the raw body. verifyWebhook('square', request, secret) from verihook does the same. Read why the raw body matters if verification fails behind a body parser.

app/api/webhooks/square/route.ts
import { createWebhookHandler } from 'verihook/next';
export const POST = createWebhookHandler('square', process.env.SQUARE_WEBHOOK_SIGNATURE_KEY!, async (payload, result) => {
// Runs only for a valid signature
console.log(result.eventType, result.event);
});

Each adapter responds 401 to an invalid signature, 413 to a body over maxBodySize (2 MB by default) and 200 to a duplicate when you pass a dedupeStore.

  • Square signs the notification URL exactly as you registered it. Behind a proxy, forward x-forwarded-proto and x-forwarded-host, or pass { url: 'https://your.public/url' }.

signWebhook from verihook/testing builds a correctly signed Square request for your tests:

import { signWebhook } from 'verihook/testing';
import { verifySquare } from 'verihook/square';
const hook = await signWebhook('square', {
secret: 'square_signature_key',
payload: { id: 'evt_test' },
});
const result = await verifySquare(
{ headers: hook.headers, body: hook.body, url: hook.url },
hook.secret,
);
// result.valid === true

From the command line, npx verihook simulate square --url http://localhost:3000/webhooks/square sends one to your local server.

See Testing your handlers for supertest and Fetch Request examples.

Failed results carry a code and often a hint with the likely cause. See Troubleshooting for each error code.

Square’s webhook documentation