Verify Lago webhooks

Lago signs every message so you can check it came from Lago and wasn't altered. Each endpoint uses one of two schemes, named in X-Lago-Signature-Algorithm: JWT, the default, puts an RS256 token in X-Lago-Signature, and HMAC puts a base64 HMAC-SHA256 of the raw body there. The code on this page covers HMAC.

The facts

Signature header
X-Lago-Signature

Also sent: X-Lago-Signature-Algorithm.

Scheme
JWT, RSA, HMAC-SHA256

Two schemes, chosen per endpoint: check which one yours uses.

Signed material
{raw body}

HMAC mode signs the body as sent. In JWT mode the token's data claim carries the body, and you compare it with what you received.

What to build
Read X-Lago-Signature-Algorithm. For hmac, recompute the base64 HMAC of the raw body and compare. For jwt, verify the token with Lago's public key and compare its data claim with the body.
Key
shared secret or public key

Lago webhook secret

HMAC mode uses your organization's HMAC signature token. JWT mode has no shared secret: it uses Lago's public key, which you fetch with your API key. Keep it in an environment variable, not in source code.

  • HMAC mode: go to Developers > Webhooks, find the HMAC signature token, then reveal and copy it.
  • The token is not your Lago API key.
  • JWT mode: fetch the public key from GET /api/v1/webhooks/json_public_key with your API key. Lago returns it base64-encoded.
  • Lago advises keeping the public key on your side, so you don't request it for each message.

Source: Lago docs ↗

Code

express/src/index.js
javascript
// Generated with: lago-webhooks skill
// https://github.com/hookdeck/webhook-skills

require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify a Lago webhook signature (HMAC mode).
 *
 * X-Lago-Signature is the base64 HMAC-SHA256 of the raw request body, keyed
 * with the organization HMAC Signature Token.
 *
 * @param {Buffer|string} rawBody  Raw request body
 * @param {string} signatureHeader Value of X-Lago-Signature
 * @param {string} secret          Organization HMAC Signature Token
 * @returns {boolean}
 */
function verifyLagoSignature(rawBody, signatureHeader, secret) {
  if (!signatureHeader || !secret) return false;

  const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('base64');
  const a = Buffer.from(signatureHeader);
  const b = Buffer.from(expected);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// Raw body for every content type, so the signature is computed over the exact bytes
app.post('/webhooks/lago', express.raw({ type: '*/*' }), (req, res) => {
  const signature = req.headers['x-lago-signature'];
  const algorithm = req.headers['x-lago-signature-algorithm'];

  if (!signature) {
    return res.status(400).send('Missing X-Lago-Signature header');
  }

  // Lago defaults to jwt; this handler only supports hmac
  if (algorithm && algorithm !== 'hmac') {
    return res.status(400).send('Unsupported signature algorithm: create the Lago endpoint with hmac');
  }

  if (!Buffer.isBuffer(req.body) || !verifyLagoSignature(req.body, signature, process.env.LAGO_HMAC_KEY)) {
    return res.status(400).send('Invalid signature');
  }

  let event;
  try {
    event = JSON.parse(req.body.toString('utf8'));
  } catch {
    return res.status(400).send('Invalid JSON');
  }

  // X-Lago-Unique-Key is the idempotency key: skip keys you have already processed
  const uniqueKey = req.headers['x-lago-unique-key'];
  const object = event[event.object_type] || {};

  switch (event.webhook_type) {
    case 'invoice.created':
      console.log('Invoice created:', object.lago_id, uniqueKey);
      // Your code: Record receivable, send invoice
      break;

    case 'invoice.payment_status_updated':
      console.log('Invoice payment status:', object.lago_id, object.payment_status);
      // Your code: Mark invoice paid/failed internally
      break;

    case 'subscription.started':
      console.log('Subscription started:', object.external_id ?? object.lago_id);
      // Your code: Provision access
      break;

    case 'subscription.terminated':
      console.log('Subscription terminated:', object.external_id ?? object.lago_id);
      // Your code: Revoke access
      break;

    case 'customer.created':
      console.log('Customer created:', object.external_id ?? object.lago_id);
      // Your code: Sync customer to CRM
      break;

    case 'wallet.depleted_ongoing_balance':
      console.log('Wallet depleted:', object.lago_id);
      // Your code: Prompt a top-up
      break;

    default:
      console.log(`Unhandled event type: ${event.webhook_type}`);
  }

  res.json({ received: true });
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = { app, verifyLagoSignature };

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/lago`);
  });
}
nextjs/app/webhooks/lago/route.ts
typescript
// Generated with: lago-webhooks skill
// https://github.com/hookdeck/webhook-skills

import { NextRequest, NextResponse } from 'next/server';
import { verifyLagoSignature } from '../../../lib/lago';

interface LagoEvent {
  webhook_type: string;
  object_type?: string;
  organization_id?: string;
  [key: string]: unknown;
}

export async function POST(request: NextRequest) {
  // Raw body for signature verification (any content type)
  const rawBody = await request.text();
  const signature = request.headers.get('x-lago-signature');
  const algorithm = request.headers.get('x-lago-signature-algorithm');

  if (!signature) {
    return NextResponse.json({ error: 'Missing X-Lago-Signature header' }, { status: 400 });
  }

  // Lago defaults to jwt; this handler only supports hmac
  if (algorithm && algorithm !== 'hmac') {
    return NextResponse.json(
      { error: 'Unsupported signature algorithm: create the Lago endpoint with hmac' },
      { status: 400 }
    );
  }

  if (!verifyLagoSignature(rawBody, signature, process.env.LAGO_HMAC_KEY ?? '')) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  let event: LagoEvent;
  try {
    event = JSON.parse(rawBody);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  // X-Lago-Unique-Key is the idempotency key: skip keys you have already processed
  const uniqueKey = request.headers.get('x-lago-unique-key');
  const object = (event.object_type ? (event[event.object_type] as Record<string, unknown>) : undefined) ?? {};

  switch (event.webhook_type) {
    case 'invoice.created':
      console.log('Invoice created:', object.lago_id, uniqueKey);
      // Your code: Record receivable, send invoice
      break;

    case 'invoice.payment_status_updated':
      console.log('Invoice payment status:', object.lago_id, object.payment_status);
      // Your code: Mark invoice paid/failed internally
      break;

    case 'subscription.started':
      console.log('Subscription started:', object.external_id ?? object.lago_id);
      // Your code: Provision access
      break;

    case 'subscription.terminated':
      console.log('Subscription terminated:', object.external_id ?? object.lago_id);
      // Your code: Revoke access
      break;

    case 'customer.created':
      console.log('Customer created:', object.external_id ?? object.lago_id);
      // Your code: Sync customer to CRM
      break;

    case 'wallet.depleted_ongoing_balance':
      console.log('Wallet depleted:', object.lago_id);
      // Your code: Prompt a top-up
      break;

    default:
      console.log(`Unhandled event type: ${event.webhook_type}`);
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: lago-webhooks skill
# https://github.com/hookdeck/webhook-skills

import base64
import hashlib
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()


def verify_lago_signature(raw_body: bytes, signature_header: str | None, secret: str | None) -> bool:
    """Verify a Lago webhook signature (HMAC mode).

    X-Lago-Signature is the base64 HMAC-SHA256 of the raw request body, keyed
    with the organization HMAC Signature Token.
    """
    if not signature_header or not secret:
        return False

    digest = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).digest()
    expected = base64.b64encode(digest).decode("ascii")
    return hmac.compare_digest(signature_header.encode("utf-8"), expected.encode("ascii"))


@app.post("/webhooks/lago")
async def lago_webhook(request: Request):
    # Raw bytes for signature verification (any content type)
    raw_body = await request.body()
    signature = request.headers.get("x-lago-signature")
    algorithm = request.headers.get("x-lago-signature-algorithm")

    if not signature:
        raise HTTPException(status_code=400, detail="Missing X-Lago-Signature header")

    # Lago defaults to jwt; this handler only supports hmac
    if algorithm and algorithm != "hmac":
        raise HTTPException(
            status_code=400,
            detail="Unsupported signature algorithm: create the Lago endpoint with hmac",
        )

    if not verify_lago_signature(raw_body, signature, os.getenv("LAGO_HMAC_KEY")):
        raise HTTPException(status_code=400, detail="Invalid signature")

    try:
        event = json.loads(raw_body)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    # X-Lago-Unique-Key is the idempotency key: skip keys you have already processed
    unique_key = request.headers.get("x-lago-unique-key")
    event_type = event.get("webhook_type")
    obj = event.get(event.get("object_type") or "") or {}

    if event_type == "invoice.created":
        print("Invoice created:", obj.get("lago_id"), unique_key)
        # Your code: Record receivable, send invoice
    elif event_type == "invoice.payment_status_updated":
        print("Invoice payment status:", obj.get("lago_id"), obj.get("payment_status"))
        # Your code: Mark invoice paid/failed internally
    elif event_type == "subscription.started":
        print("Subscription started:", obj.get("external_id") or obj.get("lago_id"))
        # Your code: Provision access
    elif event_type == "subscription.terminated":
        print("Subscription terminated:", obj.get("external_id") or obj.get("lago_id"))
        # Your code: Revoke access
    elif event_type == "customer.created":
        print("Customer created:", obj.get("external_id") or obj.get("lago_id"))
        # Your code: Sync customer to CRM
    elif event_type == "wallet.depleted_ongoing_balance":
        print("Wallet depleted:", obj.get("lago_id"))
        # Your code: Prompt a top-up
    else:
        print(f"Unhandled event type: {event_type}")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}

From hookdeck/webhook-skills ↗

Or install the Lago webhooks skill:

npx skills add hookdeck/webhook-skills --skill lago-webhooks

Common failures

Endpoint uses JWT

Lago uses JWT unless you choose HMAC, and an HMAC check can't match a token. Check X-Lago-Signature-Algorithm, then change the endpoint's signature or verify the token with Lago's public key.

Body parsed before verification

The HMAC covers the exact bytes Lago sent. Verify against the raw request body, before any parsing.

API key used as the key

HMAC mode uses your organization's HMAC signature token from Developers > Webhooks, not your Lago API key.

Hex compared with base64

The header holds a base64 digest, so comparing it with a hex digest always fails.

From Hookdeck's Lago guide

Let Event Gateway verify Lago's HMAC signatures.

Create your Lago endpoint with the HMAC signature, and Event Gateway verifies each message before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Lago. Facts are compiled from public sources and linked inline.