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 })orpaymentsApi.createPaymentin tutorials, you are looking at the legacy SDK. The current client isSquareClient, calls areclient.payments.create(...), and parameters are camelCase. The legacy surface still ships assquare/legacyfor migration only. - Money is
bigint, in the smallest unit.{ amount: 1000n, currency: "USD" }means 10.00 USD.JSON.stringifythrows on abigint, 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
idempotencyKeyfrom 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.verifySignatureis async. It returnsPromise<boolean>and must be awaited. It also needs the exactnotificationUrlyou registered: a trailing slash or http vs https mismatch makes every event look invalid.
1. Provision
- Sign in at developer.squareup.com and create an application.
- Grab a Sandbox access token and your Application ID from Credentials. Also note a Location ID from Locations: every payment needs one.
- Under Webhooks -> Subscriptions, add an endpoint pointing at your DaloyJS route, subscribe to at least
payment.updatedandrefund.updated, and copy the Signature Key. Save the full URL exactly as Square shows it.
2. Install
3. Environment variables
4. Plugin
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):
5. Create a payment
- 01asyncBrowserSquareWeb Payments SDK tokenises the cardreturns a single-use sourceId
- 02requestBrowserDaloyJS routePOST /checkout/square{ orderId, sourceId } only
- 03requestDaloyJS routeSquarepayments.createamount from the stored order, order-derived idempotencyKey
- 04responseDaloyJS routeBrowser201 captured, or 402 on a decline{ paymentId, status, receiptUrl }
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.
6. Webhook
- 01requestSquareDaloyJS routePOST /webhooks/squarex-square-hmacsha256-signature over URL + raw body
- 02noteDaloyJS routeDaloyJS routeawait verifySignatureraw body + signatureKey + exact notificationUrl
- 03responseDaloyJS routeSquare401 when the signature does not match{ error: 'bad signature' }
- 04asyncDaloyJS routeJob workerenqueue keyed by event_id, then 200worker refetches the payment
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:
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.