Skip to content

Search docs

Jump between documentation pages.

Browse docs

Accept payments with Square in DaloyJS

Square gives you one API across in-person, online, and recurring payments, useful when the same merchant takes both Tap to Pay at the counter and Apple Pay through your web app. This guide uses the square TypeScript SDK (the v40+ line, currently 46.x), Square's Web Payments SDK on the client for tokenisation, and webhook signature verification on the server.

What you should know up front

  • v40+ is a rewrite. If you see new Client({ bearerAuthCredentials }) or paymentsApi.createPayment in tutorials, you are looking at the legacy SDK. The current client is SquareClient, calls are client.payments.create(...), and parameters are camelCase. The legacy surface still ships as square/legacy for migration only.
  • Money is bigint, in the smallest unit. { amount: 1000n, currency: "USD" } means 10.00 USD. JSON.stringify throws on a bigint, so convert to a string yourself before it reaches a response body. See the callout below.
  • You charge a source ID, not a card. The Web Payments SDK returns a single-use token that your server passes as sourceId. Raw PANs never touch your code.
  • The amount comes from your order, not the request. The browser sends the token and an order id; the server loads the total. See never trust client amounts.
  • Derive the idempotencyKey from the order. Every mutating call needs one. A random UUID per call protects nothing when your own handler is retried; a key derived from the order id and version does.
  • WebhooksHelper.verifySignature is async. It returns Promise<boolean> and must be awaited. It also needs the exact notificationUrl you registered: a trailing slash or http vs https mismatch makes every event look invalid.

1. Provision

  1. Sign in at developer.squareup.com and create an application.
  2. Grab a Sandbox access token and your Application ID from Credentials. Also note a Location ID from Locations: every payment needs one.
  3. Under Webhooks -> Subscriptions, add an endpoint pointing at your DaloyJS route, subscribe to at least payment.updated and refund.updated, and copy the Signature Key. Save the full URL exactly as Square shows it.

2. Install

bash
pnpm add square

3. Environment variables

.envbash
SQUARE_ACCESS_TOKEN=EAAA_replace_me                  # sandbox or production access token
SQUARE_APPLICATION_ID=sandbox-sq0idb-replace_me      # public; also used by Web Payments SDK
SQUARE_LOCATION_ID=L_replace_me                      # default location for charges
SQUARE_WEBHOOK_SIGNATURE_KEY=replace_me              # per-subscription, from the dashboard
SQUARE_WEBHOOK_URL=https://your-app.example.com/webhooks/square
SQUARE_ENV=sandbox                                   # "sandbox" | "production"

4. Plugin

src/plugins/square.tsts
import { SquareClient, SquareEnvironment, SquareError, WebhooksHelper } from "square";
import type { App } from "@daloyjs/core";

const square = new SquareClient({
  token: process.env.SQUARE_ACCESS_TOKEN!,
  environment:
    process.env.SQUARE_ENV === "production"
      ? SquareEnvironment.Production
      : SquareEnvironment.Sandbox,
});

/** Stable key per logical operation. 40 hex chars, under Square's 45-character limit. */
export async function squareIdempotencyKey(...parts: Array<string | number>): Promise<string> {
  const digest = new Uint8Array(
    await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join(":"))),
  );
  return Array.from(digest.slice(0, 20), (b) => b.toString(16).padStart(2, "0")).join("");
}

export interface SquareClientWrapper {
  raw: SquareClient;

  createPayment(input: {
    sourceId: string;          // token from Web Payments SDK
    amountMinor: bigint;       // smallest unit, from your order
    currency: string;          // ISO 4217, uppercase
    idempotencyKey: string;    // derived from the order, never random per call
    referenceId: string;       // your order id (max 40 chars)
    verificationToken?: string; // from the Web Payments SDK buyer verification (SCA)
  }): Promise<{ id: string; status: string; receiptUrl?: string }>;

  verifyWebhookSignature(rawBody: string, signatureHeader: string | null): Promise<boolean>;

  getPayment(paymentId: string): Promise<{
    id: string;
    status: string;
    amountMinor: bigint;
    currency: string;
    referenceId?: string;
  }>;

  refund(input: {
    paymentId: string;
    amountMinor: bigint;
    currency: string;
    idempotencyKey: string;
    reason?: string;
  }): Promise<{ id: string; status: string }>;
}

// Exported so job handlers (which run outside a request) can use it too.
export const squareClient: SquareClientWrapper = {
  raw: square,

  async createPayment({ sourceId, amountMinor, currency, idempotencyKey, referenceId, verificationToken }) {
    const { payment } = await square.payments.create({
      sourceId,
      idempotencyKey,
      amountMoney: { amount: amountMinor, currency },
      locationId: process.env.SQUARE_LOCATION_ID!,
      referenceId,
      verificationToken,
      autocomplete: true,
    });
    if (!payment) throw new Error("Square returned no payment");
    return { id: payment.id!, status: payment.status!, receiptUrl: payment.receiptUrl };
  },

  async verifyWebhookSignature(rawBody, signatureHeader) {
    if (!signatureHeader) return false;
    // Async in the current SDK: always await the result.
    return await WebhooksHelper.verifySignature({
      requestBody: rawBody,
      signatureHeader,
      signatureKey: process.env.SQUARE_WEBHOOK_SIGNATURE_KEY!,
      notificationUrl: process.env.SQUARE_WEBHOOK_URL!,
    });
  },

  async getPayment(paymentId) {
    const { payment } = await square.payments.get({ paymentId });
    if (!payment) throw new Error(`Square payment ${paymentId} not found`);
    return {
      id: payment.id!,
      status: payment.status!,
      amountMinor: payment.amountMoney!.amount!,
      currency: payment.amountMoney!.currency!,
      referenceId: payment.referenceId,
    };
  },

  async refund({ paymentId, amountMinor, currency, idempotencyKey, reason }) {
    const { refund } = await square.refunds.refundPayment({
      paymentId,
      idempotencyKey,
      amountMoney: { amount: amountMinor, currency },
      reason,
    });
    if (!refund) throw new Error("Square returned no refund");
    return { id: refund.id!, status: refund.status! };
  },
};

// Call with the root app, not through app.register(): a decoration made
// inside a registered plugin is visible only to that plugin's own routes.
export function squarePlugin(app: App) {
  app.decorate("square", squareClient);
}

export { SquareError };

declare module "@daloyjs/core" {
  interface AppState {
    square: SquareClientWrapper;
  }
}

The SDK helper computes HMAC-SHA256 over the notification URL followed by the raw body and compares the base64 result with a plain string comparison. If you want a constant-time comparison, the core helper does the same check (it accepts base64 signatures):

ts
import { verifyWebhookSignature } from "@daloyjs/core";

const ok = await verifyWebhookSignature({
  payload: process.env.SQUARE_WEBHOOK_URL! + rawBody,
  signature: signatureHeader ?? "",
  secret: process.env.SQUARE_WEBHOOK_SIGNATURE_KEY!,
  algorithm: "sha256",
});

5. Create a payment

Token handoff and charge
BrowserDaloyJS routeSquare
  1. 01asyncBrowserSquareWeb Payments SDK tokenises the cardreturns a single-use sourceId
  2. 02requestBrowserDaloyJS routePOST /checkout/square{ orderId, sourceId } only
  3. 03requestDaloyJS routeSquarepayments.createamount from the stored order, order-derived idempotencyKey
  4. 04responseDaloyJS routeBrowser201 captured, or 402 on a decline{ paymentId, status, receiptUrl }
The browser tokenises the card so raw PANs never reach your server, and names only the order. The server loads the amount, derives a stable idempotency key, and maps a 402 SquareError to a card-declined response.

The client uses Square's Web Payments SDK with your SQUARE_APPLICATION_ID and SQUARE_LOCATION_ID, tokenises the card, and posts the sourceId together with the order id. The route relies on the shared app wiring (session, scoped csrf() and rateLimit()) and the overview's orders module.

src/routes/checkout-square.tsts
import { z } from "zod";
import { squarePlugin, squareIdempotencyKey, SquareError } from "../plugins/square.ts";
import { orders } from "../orders.ts";

squarePlugin(app);

app.post(
  "/checkout/square",
  {
    operationId: "createSquarePayment",
    request: {
      body: z.object({
        orderId: z.string().min(1).max(40),
        sourceId: z.string().min(1).max(512),
        verificationToken: z.string().max(512).optional(),
      }).strict(),
    },
    responses: {
      201: {
        description: "captured",
        body: z.object({ paymentId: z.string(), status: z.string(), receiptUrl: z.url().optional() }),
      },
      402: { description: "card declined", body: z.object({ error: z.string() }) },
    },
  },
  async ({ body, state }) => {
    const order = await orders.forCheckout(body.orderId, state.session.get<string>("userId"));
    try {
      const payment = await state.square.createPayment({
        sourceId: body.sourceId,
        verificationToken: body.verificationToken,
        amountMinor: BigInt(order.amountMinor), // server-side total
        currency: order.currency,
        referenceId: order.id,
        idempotencyKey: await squareIdempotencyKey("payment", order.id, order.version),
      });
      return {
        status: 201,
        body: { paymentId: payment.id, status: payment.status, receiptUrl: payment.receiptUrl },
      };
    } catch (err) {
      if (err instanceof SquareError && err.statusCode === 402) {
        // Log err.errors internally; return your own stable message.
        return { status: 402, body: { error: "The card was declined." } };
      }
      throw err;
    }
  },
);

6. Webhook

Webhook verification
SquareDaloyJS routeJob worker
  1. 01requestSquareDaloyJS routePOST /webhooks/squarex-square-hmacsha256-signature over URL + raw body
  2. 02noteDaloyJS routeDaloyJS routeawait verifySignatureraw body + signatureKey + exact notificationUrl
  3. 03responseDaloyJS routeSquare401 when the signature does not match{ error: 'bad signature' }
  4. 04asyncDaloyJS routeJob workerenqueue keyed by event_id, then 200worker refetches the payment
Await the signature check, dedupe atomically on event_id through the job idempotency key, and let the worker refetch the payment and compare it with the stored order before fulfilling.
src/webhooks/square.tsts
import { z } from "zod";
import { readBodyLimited, safeJsonParse, jobIdempotencyKey } from "@daloyjs/core";

app.post(
  "/webhooks/square",
  {
    operationId: "squareWebhook",
    // No request.body schema: the raw bytes stay readable for verification.
    responses: {
      200: { description: "ok", body: z.object({ ok: z.literal(true) }) },
      401: { description: "bad signature", body: z.object({ error: z.string() }) },
    },
  },
  async ({ request, state }) => {
    const raw = new TextDecoder().decode(await readBodyLimited(request, 1_048_576));
    const signature = request.headers.get("x-square-hmacsha256-signature");

    if (!(await state.square.verifyWebhookSignature(raw, signature))) {
      return { status: 401, body: { error: "bad signature" } };
    }

    const event = safeJsonParse(raw) as { type: string; event_id: string; data: { type: string; id: string } };
    if (event.type === "payment.updated") {
      await app.jobs!.enqueue({
        name: "square.payment",
        payload: { eventId: event.event_id, paymentId: event.data.id },
        idempotencyKey: jobIdempotencyKey({ name: "square.payment", key: event.event_id }),
      });
    }
    return { status: 200, body: { ok: true as const } };
  },
);
src/jobs/square.tsts
import type { JobHandler } from "@daloyjs/core";
import { squareClient } from "../plugins/square.ts";
import { orders } from "../orders.ts";

export const handleSquarePayment: JobHandler<{ eventId: string; paymentId: string }> = async ({ job }) => {
  const payment = await squareClient.getPayment(job.payload.paymentId);
  if (payment.status !== "COMPLETED" || !payment.referenceId) return;
  await orders.markPaid(payment.referenceId, {
    amountMinor: Number(payment.amountMinor),
    currency: payment.currency,
    providerRef: payment.id,
  });
};

Register the handler in your single app.useJobs() call (see the webhook pattern). Square includes event_id in every notification for exactly this dedupe, retries deliveries that do not get a 2xx, and can disable a subscription that keeps failing, so ack fast and do the work in the worker.

7. Refunds

Expose refunds only through a protected refund route. The plugin call:

ts
await state.square.refund({
  paymentId: order.providerRef!,
  amountMinor: 250n, // 2.50 USD, never more than captured minus refunded
  currency: "USD",
  idempotencyKey: await squareIdempotencyKey("refund", order.id, order.refundedMinor, 250),
  reason: "requested_by_customer",
});

Runtimes

The SDK uses the platform fetch when present and lists Node.js 18+, Vercel, Cloudflare Workers, Deno 1.25+, and Bun 1.0+ as supported runtimes in its README. The plugin above only adds WebCrypto (crypto.subtle) and the portable readBodyLimited() helper. See the runtime table.

Errors

Non-2xx responses throw SquareError. Inspect err.statusCode, err.body, and the structured err.errors[] array: each entry has category (for example PAYMENT_METHOD_ERROR), code (for example CARD_DECLINED, CVV_FAILURE), detail, and an optional field. Log them and map them to problem+json with your own type and title; do not forward Square's detail to the client.

Modernisation notes

  • Use the current SDK, not square/legacy. The legacy export exists so older codebases can migrate piecemeal.
  • Pin the SDK major. Each SDK release targets a Square API version, and a new major can be breaking. Pin a caret range and read the changelog before bumping.
  • Iterate paginated endpoints with for await. List responses are async-iterable; a synchronous loop only gives you the first page.
  • Verify webhooks. Do not trust the source IP. The HMAC plus the registered notification URL prove authenticity and that the request hit the right endpoint.

See also the payments overview, Braintree guide, Authorize.Net guide, and problem+json errors.

Edit this page on GitHub

Last updated