Docs

Fastify recipe

Native ATM test checkout and signed webhook verification in a Fastify app.

Closed beta@atmosphere-money/app-nodeSDK beta: 0.0.0-beta.3ATM API beta: 2026-0671 published lexicons

Compatible with the closed-beta ATM app APIs and versioned ATM event headers. Check atm-api-version on every webhook or XRPC receiver event.

Install SDK

Fastify needs a raw-body strategy for ATM webhooks. Checkout routes can use ordinary JSON request bodies.

Install the pinned native build supplied for your integration and keep its integrity hash in your lockfile. Older npm betas may not include the native checkout helpers.

sh
# For example, a supplied package tarball, plus Fastify:
npm install ./atmosphere-money-app-node-<version>.tgz fastify

Configure attempts

Every recipe shares one durable attempt store. An attempt keeps the exact native request and idempotency key, ATM's response and the latest canonical status, so a retry never builds a second request.

ts
import {
  createAtmCheckoutAttempts,
  type AtmCheckoutAttempt,
  type AtmDurableStore,
} from "@atmosphere-money/app-node";

// Implement AtmDurableStore with compare-and-swap in your database. Serverless
// and edge filesystems are not durable; createAtmFileStore suits one server only.
declare const attemptStore: AtmDurableStore<AtmCheckoutAttempt>;

export const attempts = createAtmCheckoutAttempts({
  // Your assigned test configuration: app DID, test broker DID and checkout origin.
  appDid: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
  brokerDid: "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb",
  brokerUrl: "https://your-assigned-test-checkout.example",
  store: attemptStore,
  // A NEW token per call, signed by your PDS via com.atproto.server.getServiceAuth.
  getServiceAuthToken: ({ lxm, aud }) => mintMyAppServiceAuthJwt({ lxm, aud }),
});

Create checkout route

Create the order and its attempt once, with a unique attempt ID that also serves as the idempotency key. The checkout route runs only after an authorized Buy click: it captures that stored request, sends it, and returns only the checkout URL. A repeat click or a retry recovers the same operation. The status token stays on your server.

ts
import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
import type { AtmCreateCheckoutInput } from "@atmosphere-money/app-node";

const fastify = Fastify();

fastify.post("/orders/:id/checkout", async (request: FastifyRequest, reply: FastifyReply) => {
  // Your session and CSRF hooks run first; load the order by its owner.
  const { id } = request.params as { id: string };
  const order = await loadOwnedOrder(request, id);
  if (!order) return reply.code(404).send({ error: "OrderNotFound" });

  await attempts.capture(order.attemptId, order.request);
  const attempt = await attempts.recover(order.attemptId);
  return reply
    .header("cache-control", "private, no-store")
    .send({ url: attempt.checkout!.url }); // never the statusToken
});

export default fastify;

// Your app: the buyer's own order, with its attempt ID and request stored once.
declare function loadOwnedOrder(
  request: FastifyRequest,
  orderId: string,
): Promise<{ attemptId: string; request: AtmCreateCheckoutInput } | null>;

Add event receiver

AT Protocol apps use the canonical #AtmEventReceiver / money.atmosphere.event.receiveEvent wake-up transport by default. A conventional web app can explicitly select the signed HTTP webhook shown in this recipe. Verify each delivery, claim it, and queue reconciliation before acknowledging.

ts
import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
import { constructAtmWebhookEvent } from "@atmosphere-money/app-node";

const fastify = Fastify();

fastify.post("/webhooks/atm", async (request: FastifyRequest, reply: FastifyReply) => {
  // A raw-body parser must store the exact incoming bytes as request.rawBody.
  const rawBody = String((request as { rawBody?: unknown }).rawBody ?? "");
  const event = constructAtmWebhookEvent({
    rawBody,
    secret: [process.env.ATM_WEBHOOK_SECRET, process.env.ATM_WEBHOOK_PREVIOUS_SECRET]
      .filter((value): value is string => Boolean(value)),
    headers: {
      signature: request.headers["atm-signature"] as string | undefined,
      deliveryId: request.headers["atm-delivery-id"] as string | undefined,
      event: request.headers["atm-event"] as string | undefined,
      apiVersion: request.headers["atm-api-version"] as string | undefined,
      environment: request.headers["atm-environment"] as string | undefined,
    },
  });
  if (event.environment !== "test" || event.apiVersion !== "2026-07")
    return reply.code(422).send({ error: "UnexpectedEventBinding" });

  const claim = await claimWebhookDelivery(event.id, event);
  if (claim.status === "completed") {
    return reply.send({ ok: true, duplicate: true });
  }
  if (claim.status === "busy") {
    return reply.code(503).header("retry-after", "1").send({ error: "DeliveryBusy" });
  }

  try {
    await enqueueReconciliation(event); // the worker reads canonical status
    await completeWebhookDelivery(event.id, claim.claimId, event);
    return reply.send({ ok: true });
  } catch (error) {
    await releaseWebhookDelivery(event.id, claim.claimId, event, error);
    throw error;
  }
});

Reconcile and fulfil

Fulfilment is the same in Fastify. A background worker reconciles each attempt on a schedule and whenever a notification is queued, even if the buyer never returns. Only completed status with fulfillment “fulfil” grants a direct digital purchase.

ts
// Background worker: on a schedule, and for every queued notification.
export async function reconcileOrder(
  attemptId: string,
  app: {
    grantPurchaseOnce(effectKey: string): Promise<void>;
    markUnpaid(): Promise<void>;
    pollAgainLater(): Promise<void>;
    holdForReview(): Promise<void>;
  },
) {
  const result = await attempts.reconcile(attemptId); // POSTs getCheckoutStatus
  switch (result.action) {
    case "fulfil":
      // Insert result.effectKey under a unique constraint and grant the
      // purchase in the SAME database transaction.
      return app.grantPurchaseOnce(result.effectKey!);
    case "closed": // failed, canceled or expired
      return app.markUnpaid();
    case "wait": // pending; deadlines passing are not outcomes
      return app.pollAgainLater();
    case "order": // an order owner must confirm; not used by fixed digital checkout
      return app.holdForReview();
  }
}

Run local test fixture

The examples/atm-node-app Node reference is the runnable native starter. Your tests should prove capture before any request, recovery after a restart or lost reply, status polling by POST, and a single grant for a repeated completed status. With push enabled, use signed fixtures from @atmosphere-money/testing to prove raw-body verification and duplicate delivery handling.

sh
node --test test/atm-webhook.test.js
# Make the fixture assert that Fastify receives the exact raw JSON body.

Runtime notes

Raw bodyRegister a raw-body parser or plugin and store the exact bytes before parsing JSON.
Snippetdocs/developer/examples/fastify-webhook-route.ts is the copyable route example.
IdempotencyUse an atomic claim with an expiring lease; complete only after the wake-up is queued, and release failures for redrive.