Cloudflare Workers recipe
Native ATM test checkout and signed webhook verification in a Cloudflare Worker.
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
Keep secrets in environment bindings and keep attempts and delivery claims in D1, Durable Objects or an external database. The SDK needs Workers’ Node.js compatibility.
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.
# For example, a supplied package tarball:
npm install ./atmosphere-money-app-node-<version>.tgzConfigure 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.
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.
import type { AtmCreateCheckoutInput } from "@atmosphere-money/app-node";
export default {
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
const match = url.pathname.match(/^\/orders\/([^/]+)\/checkout$/);
if (request.method !== "POST" || !match) return new Response("Not found", { status: 404 });
// Your session and CSRF checks run first; load the order by its owner.
const order = await loadOwnedOrder(request, match[1]);
if (!order) return Response.json({ error: "OrderNotFound" }, { status: 404 });
await attempts.capture(order.attemptId, order.request);
const attempt = await attempts.recover(order.attemptId);
return Response.json(
{ url: attempt.checkout!.url }, // never the statusToken
{ headers: { "cache-control": "private, no-store" } },
);
},
};
// Your app: the buyer's own order, with its attempt ID and request stored once.
declare function loadOwnedOrder(
request: Request,
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.
import { createCloudflareWorkerWebhookHandler } from "@atmosphere-money/app-node";
type Env = { ATM_WEBHOOK_SECRET: string; ATM_WEBHOOK_PREVIOUS_SECRET?: string };
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const handler = createCloudflareWorkerWebhookHandler({
secret: [env.ATM_WEBHOOK_SECRET, env.ATM_WEBHOOK_PREVIOUS_SECRET]
.filter((value): value is string => Boolean(value)),
deliveryStore: {
// Atomic D1 or Durable Object transitions keyed by delivery and claimId.
claim: claimWebhookDelivery,
complete: completeWebhookDelivery,
release: releaseWebhookDelivery,
},
onEvent: async (event) => {
if (event.environment !== "test" || event.apiVersion !== "2026-07")
return { status: 422, body: { error: "UnexpectedEventBinding" } };
await enqueueReconciliation(event); // e.g. a Queue the worker consumes
return { body: { ok: true } };
},
});
return handler.fetch(request);
},
};Reconcile and fulfil
Fulfilment is the same in Cloudflare Workers. 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.
// 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.
npx wrangler dev
# Then post a signed fixture from @atmosphere-money/testing to /webhooks/atm.Runtime notes
| Node.js compatibility | The SDK uses node:crypto and Buffer. Enable the nodejs_compat compatibility flag for your Worker. |
|---|---|
| Storage | Use D1, Durable Objects or an external database with compare-and-swap. KV alone and in-memory sets are not enough. |
| Secrets | Keep webhook secrets and service-auth credentials in environment bindings. |
| Starter | The Hono / Workers starter runs native test checkout on Workers with nodejs_compat, a D1 attempt store and a Cron Trigger status sweep. |