Square Web Payments SDK + Payments API

Take card payments with Square: tokenise the card in the browser with the Web Payments SDK, charge it from your server with the Payments API and an idempotency key, verify webhook signatures and issue refunds.

Provider
Square (Block)
Level
Intermediate
Stacks
Node.js (Express), React
Code maturity
Sandbox-ready
Last verified
25 Nov 2026

Introduction

Square is a payments company best known for in-person point-of-sale hardware, but it also offers online payments. The Web Payments SDK renders a secure card form in your page and turns the card into a one-time payment token (a cnon: nonce). Your server then sends that token to the Payments API to actually charge the card.

This guide builds the whole loop in the Square Sandbox: card form, server-side charge with an idempotency key, webhook signature verification, status checks and refunds.

What this integration does

  • Browser: loads square.js, calls Square.payments(appId, locationId), creates a card field with payments.card(), attaches it, and calls card.tokenize() to get a token.
  • Server: calls CreatePayment (POST /v2/payments) with source_id (the token), idempotency_key, amount_money and location_id.
  • Square: authorises and (by default) completes the payment, then sends payment.created / payment.updated webhooks.

Card data never touches your server — only the single-use token does.

Countries and currencies

Square supports sellers only in a limited set of countries, and a payment's currency must match the currency of the seller's location. Check Square's official country list before you build — this guide does not restate it because availability changes.

The sandbox docs note that USD, CAD and GBP card payments require a postal code, while Japan does not support postal codes.

Warning: Do not assume a Square account can be opened in your country. Confirm seller eligibility on squareup.com before committing to this provider.

Payment methods

This guide covers cards. The Web Payments SDK also offers other methods (for example Apple Pay, Google Pay, ACH bank payments, Cash App Pay, Afterpay/Clearpay and gift cards — see the quickstart repository's examples) but availability depends on the seller's country. Each method has its own setup steps in the official docs.

When to use it

  • You already use Square for in-person sales and want online payments in the same account and reporting.
  • You want an embedded card form (not a redirect) with PCI scope reduced by tokenisation.
  • You operate in a country where Square onboards sellers.

When not to use it

  • Your business is in a country Square does not support.
  • You need local methods such as mobile money, UPI or Pix — pick a regional provider.
  • You need a fully hosted checkout page with no front-end work — Square has Payment Links/Checkout API for that, which this guide does not cover.

Typical scenarios

  • A café with Square POS that adds online pre-orders.
  • A small online shop that wants an inline card form instead of redirecting to a hosted page.
  • A booking site that charges a fixed deposit at reservation time.

Registration

  • Create a Square account and sign in to the Developer Console.
  • Create an application. Each application has Sandbox and Production credentials.
  • Note the Application ID and a Location ID (every payment belongs to a location).

Sandbox

Square's Sandbox is a separate environment with its own credentials:

  • API base URL: https://connect.squareupsandbox.com (production: https://connect.squareup.com), as defined in the official Node SDK's SquareEnvironment.
  • Browser script: https://sandbox.web.squarecdn.com/v1/square.js (production: https://web.squarecdn.com/v1/square.js).
  • Sandbox Application IDs start with sandbox-sq0idb- and only work with the sandbox script.

Tip: The production script URL was probed on 2026-11-25 (HTTP 200); the sandbox URL comes from Square's official quickstart. Never mix a sandbox application ID with the production script.

Credentials

  • Application ID + Location ID — public, used in the browser.
  • Access token — secret, server only. Grants API access to the seller account.
  • Webhook signature key — secret, per webhook subscription, used to verify notifications.

Security: The access token must never be shipped to the browser or committed to git. Load it from an environment variable or a secrets manager.

Environment configuration

Keep every secret in environment variables. A .env.example with placeholders only:

.env.example · Node.js (Express)

SQUARE_ENV=sandbox                     # sandbox | production
SQUARE_ACCESS_TOKEN=replace-me         # server only
SQUARE_LOCATION_ID=replace-me
SQUARE_WEBHOOK_SIGNATURE_KEY=replace-me
SQUARE_WEBHOOK_URL=https://your-domain.example/webhooks/square  # must match the subscription URL exactly
# Front end (public values)
REACT_APP_SQUARE_APP_ID=sandbox-sq0idb-replace-me
REACT_APP_SQUARE_LOCATION_ID=replace-me

Authentication

Server calls use a bearer access token (Authorization: Bearer <token>). The official SDK does this for you:

new SquareClient({ token, environment: SquareEnvironment.Sandbox }).

The browser never authenticates with the access token; it uses only the public Application ID and Location ID.

Backend: create the payment

The server receives the token and the order id from the browser — never the amount. It looks up the price itself, then calls client.payments.create. Money amounts are integers in the smallest currency unit and the SDK expects them as BigInt.

server.js — charge a tokenised card (square SDK v40+) · Node.js (Express)

import express from "express";
import { randomUUID } from "node:crypto";
import { SquareClient, SquareEnvironment, SquareError } from "square";

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

const app = express();
// NOTE: the webhook route (see Webhooks) is registered BEFORE express.json().
app.use(express.json());

app.post("/api/pay", async (req, res) => {
  const { sourceId, orderId } = req.body;
  const order = await db.orders.findById(orderId);           // your DB
  if (!order || order.status !== "pending") return res.status(400).json({ error: "invalid order" });

  // One idempotency key per payment attempt, stored so a retry reuses it.
  order.idempotencyKey ??= randomUUID();
  await db.orders.save(order);

  try {
    const { payment } = await square.payments.create({
      sourceId,
      idempotencyKey: order.idempotencyKey,
      amountMoney: { amount: BigInt(order.amountMinor), currency: order.currency },
      locationId: process.env.SQUARE_LOCATION_ID,
      referenceId: order.id,
    });
    await db.orders.update(order.id, { squarePaymentId: payment.id, squareStatus: payment.status });
    // BigInt cannot be JSON.stringify'd — send only plain fields back.
    res.json({ status: payment.status, paymentId: payment.id });
  } catch (err) {
    if (err instanceof SquareError) {
      return res.status(402).json({ errors: err.errors?.map((e) => e.code) });
    }
    throw err;
  }
});

app.listen(4242);

Warning: JSON.stringify throws on BigInt values. Never return the raw SDK response object from an Express route — pick the fields you need, or convert amounts with Number()/String() first.

Frontend: card form and tokenisation

Square does not publish an official React wrapper. Load square.js once, then initialise the card in an effect. (react-square-web-payments-sdk exists on npm but is community-maintained, not by Square.)

SquareCardForm.jsx · React

import { useEffect, useRef, useState } from "react";

const SCRIPT = "https://sandbox.web.squarecdn.com/v1/square.js"; // production: https://web.squarecdn.com/v1/square.js

function loadSquare() {
  if (window.Square) return Promise.resolve(window.Square);
  return new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = SCRIPT;
    s.onload = () => resolve(window.Square);
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

export default function SquareCardForm({ orderId, amount, currencyCode, onDone }) {
  const cardRef = useRef(null);
  const [msg, setMsg] = useState("");

  useEffect(() => {
    let card;
    loadSquare().then(async (Square) => {
      const payments = Square.payments(process.env.REACT_APP_SQUARE_APP_ID, process.env.REACT_APP_SQUARE_LOCATION_ID);
      card = await payments.card();
      await card.attach("#card-container");
      cardRef.current = card;
    }).catch(() => setMsg("Could not load the payment form."));
    return () => { card?.destroy(); };
  }, []);

  async function pay() {
    const result = await cardRef.current.tokenize({
      amount, currencyCode, intent: "CHARGE", customerInitiated: true, sellerKeyedIn: false,
    });
    if (result.status !== "OK") {
      setMsg(result.errors?.map((e) => e.message).join(", ") || "Card was not accepted.");
      return;
    }
    const res = await fetch("/api/pay", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ sourceId: result.token, orderId }), // never send the amount
    });
    const data = await res.json();
    onDone?.(data); // UI only — fulfilment is decided server-side
  }

  return (
    <div>
      <div id="card-container" />
      <button type="button" onClick={pay}>Pay</button>
      <p role="status">{msg}</p>
    </div>
  );
}

Tip: tokenize() accepts verification details (amount, currencyCode, intent, billingContact, customerInitiated, sellerKeyedIn) so Square can run buyer verification such as 3-D Secure where required.

Initiating a payment

  • Your server creates an order record (pending) with the price in minor units.
  • The browser tokenises the card and POSTs { sourceId, orderId }.
  • The server calls payments.create with an idempotency key stored on the order, so a network retry cannot charge twice.

Confirming the payment

The CreatePayment response contains payment.status. With the default autocomplete: true, a successful card payment is normally COMPLETED. Payment statuses are APPROVED, PENDING, COMPLETED, CANCELED and FAILED.

Fulfil only when your server has seen COMPLETED — from the API response or from a verified webhook — never because the browser said so.

Webhooks

Subscribe to payment.created, payment.updated, refund.created and refund.updated in the Developer Console. Square signs each notification with the x-square-hmacsha256-signature header: an HMAC-SHA256 over the notification URL + the raw request body, keyed with the subscription's signature key.

Use the SDK's WebhooksHelper.verifySignature(...). In the current SDK it returns a Promise<boolean> — you must await it (the README example omits the await, and an un-awaited Promise is always truthy).

webhook route — register BEFORE express.json() · Node.js (Express)

import { WebhooksHelper } from "square";

app.post("/webhooks/square", express.raw({ type: "application/json" }), async (req, res) => {
  const requestBody = req.body.toString("utf8");          // raw body, unparsed
  const valid = await WebhooksHelper.verifySignature({
    requestBody,
    signatureHeader: req.get("x-square-hmacsha256-signature") ?? "",
    signatureKey: process.env.SQUARE_WEBHOOK_SIGNATURE_KEY,
    notificationUrl: process.env.SQUARE_WEBHOOK_URL,       // exactly as registered
  });
  if (!valid) return res.sendStatus(403);

  const event = JSON.parse(requestBody);
  // Idempotency: Square may deliver the same event more than once.
  const firstTime = await db.webhookEvents.insertIfAbsent(event.event_id);
  if (!firstTime) return res.sendStatus(200);

  if (event.type === "payment.updated" || event.type === "payment.created") {
    const p = event.data.object.payment;
    // Re-read from the API rather than trusting the payload alone.
    const { payment } = await square.payments.get({ paymentId: p.id });
    if (payment.status === "COMPLETED") {
      await fulfilOnce(payment.referenceId, payment.id); // no-op if already fulfilled
    }
  }
  res.sendStatus(200);
});

Security: If you verify manually, compute the HMAC over notificationUrl + rawBody and compare with a constant-time function. Any proxy that rewrites the URL (http vs https, trailing slash) breaks the signature.

Checking status

Retrieve a payment with GetPayment (client.payments.get({ paymentId })). Use it in a reconciliation job for orders stuck in pending, and after any webhook before changing order state.

Refunds

Refund with RefundPayment (POST /v2/refunds), which also requires an idempotency key. Refunds can be partial. The final result arrives via refund.updated.

refund (staff-only route) · Node.js (Express)

app.post("/admin/orders/:id/refund", requireStaff, async (req, res) => {
  const order = await db.orders.findById(req.params.id);
  order.refundKey ??= randomUUID();                       // reuse on retry
  await db.orders.save(order);
  const { refund } = await square.refunds.refundPayment({
    idempotencyKey: order.refundKey,
    paymentId: order.squarePaymentId,
    amountMoney: { amount: BigInt(order.amountMinor), currency: order.currency },
    reason: "Customer request",
  });
  res.json({ refundId: refund.id, status: refund.status });
});

Errors

The SDK throws SquareError for non-2xx responses; inspect err.statusCode and err.errors (each has a category, code and detail). Card declines come back as errors on CreatePayment. Show a generic message to the buyer and log the code server-side.

Going to production

  • Switch to production Application ID, Location ID, access token and the production square.js URL — all four together.
  • Serve the payment page over HTTPS.
  • Create a production webhook subscription; it has a different signature key.
  • Add a reconciliation job that checks pending orders with GetPayment.

Security

  • Access token and webhook signature key in env vars only.
  • Price comes from your database, never from the browser.
  • Verify every webhook signature against the raw body and exact URL.
  • Persist idempotency keys and processed event_ids.
  • Refund routes require staff authorisation and are audited.

Testing

Square's published sandbox values:

  • Success: Visa 4111 1111 1111 1111, CVV 111, any future expiry (add a postal code for USD/CAD/GBP).
  • CVV 911 → incorrect CVV; postal code 99999 → incorrect postal code; expiry 01/40 → incorrect expiration.
  • 4000 0000 0000 0002 → card declined.

Send test webhooks from the Developer Console to check your signature verification.

Common mistakes

  • Not awaiting WebhooksHelper.verifySignature — the Promise is truthy, so every request "passes".
  • Parsing the body with express.json() before verification — the re-serialised JSON no longer matches the signature.
  • Generating a fresh idempotency key on every retry, which defeats idempotency.
  • Sending the amount from the browser.
  • Returning SDK objects that contain BigInt via res.json() ("Do not know how to serialize a BigInt").
  • Mixing sandbox and production IDs/scripts.

Troubleshooting

  • Card form never appears: wrong script for the Application ID's environment, or #card-container is not in the DOM when attach runs.
  • Webhook signature always invalid: notificationUrl differs from the subscription URL, body was parsed/modified, or you used the sandbox key in production.
  • TypeError: Do not know how to serialize a BigInt: see Common mistakes.
  • Payment in wrong currency rejected: currency must match the location's currency.

Further reading

Official documentation

Official documentation

Sources

More payment guides