# Square Node.js SDK The Square TypeScript/Node.js SDK provides convenient access to Square's comprehensive commerce APIs from TypeScript and JavaScript applications. It enables developers to integrate Square's payment processing, customer management, inventory tracking, and merchant services into their applications. The SDK is auto-generated using Fern and provides type-safe interfaces for all Square API endpoints, making it easy to build point-of-sale systems, e-commerce platforms, subscription services, and custom business applications. The SDK follows modern Node.js patterns with full TypeScript support, automatic pagination, webhook signature verification, and built-in retry logic with exponential backoff. It works across multiple JavaScript runtimes including Node.js 18+, Deno, Bun, Vercel, Cloudflare Workers, and React Native. The library handles authentication via bearer tokens, supports request customization through headers and timeouts, and provides comprehensive error handling for all API operations. ## Client Initialization Initialize the SDK client with an access token ```typescript import { SquareClient } from "square"; const client = new SquareClient({ token: "YOUR_ACCESS_TOKEN", environment: "production" // or "sandbox" for testing }); // With custom configuration const client = new SquareClient({ token: process.env.SQUARE_ACCESS_TOKEN, version: "2025-09-24", // Override API version headers: { 'X-Custom-Header': 'custom value' }, fetcher: customFetchFunction // Custom fetch implementation }); ``` ## Create Payment Process a card payment with amount, customer, and location details ```typescript import { SquareClient } from "square"; const client = new SquareClient({ token: "YOUR_TOKEN" }); try { const result = await client.payments.create({ sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", idempotencyKey: "7b0f3ec5-086a-4871-8f13-3c81b3875218", amountMoney: { amount: BigInt(1000), // $10.00 in cents currency: "USD", }, appFeeMoney: { amount: BigInt(10), // Platform fee currency: "USD", }, autocomplete: true, customerId: "W92WH6P11H4Z77CTET0RNTGFW8", locationId: "L88917AVBK2S5", referenceId: "123456", note: "Brief description", }); console.log("Payment ID:", result.payment?.id); console.log("Status:", result.payment?.status); } catch (err) { if (err instanceof SquareError) { console.error("Status:", err.statusCode); console.error("Message:", err.message); console.error("Body:", err.body); } } ``` ## List Payments with Pagination Retrieve a paginated list of payments with automatic iteration ```typescript import { SquareClient } from "square"; const client = new SquareClient({ token: "YOUR_TOKEN" }); // Automatic iteration through all pages const response = await client.payments.list({ locationId: "L88917AVBK2S5", beginTime: "2023-01-01T00:00:00Z", endTime: "2023-12-31T23:59:59Z" }); for await (const payment of response) { console.log("Payment:", payment.id, payment.amountMoney?.amount); } // Manual page-by-page iteration let page = await client.payments.list(); while (page.hasNextPage()) { console.log("Processing page..."); page = page.getNextPage(); } ``` ## Update and Cancel Payment Modify payment amount or cancel an approved payment ```typescript // Update payment amount or tip const updateResult = await client.payments.update({ paymentId: "payment_id", payment: { amountMoney: { amount: BigInt(1000), currency: "USD" }, tipMoney: { amount: BigInt(100), currency: "USD" }, versionToken: "ODhwVQ35xwlzRuoZEwKXucfu7583sPTzK48c5zoGd0g6o" }, idempotencyKey: "956f8b13-e4ec-45d6-85e8-d1d95ef0c5de" }); // Cancel a payment const cancelResult = await client.payments.cancel({ paymentId: "payment_id" }); // Complete a payment with delayed capture const completeResult = await client.payments.complete({ paymentId: "payment_id" }); ``` ## Create Customer Create a new customer profile with contact and address information ```typescript const customer = await client.customers.create({ givenName: "Amelia", familyName: "Earhart", emailAddress: "Amelia.Earhart@example.com", address: { addressLine1: "500 Electric Ave", addressLine2: "Suite 600", locality: "New York", administrativeDistrictLevel1: "NY", postalCode: "10003", country: "US" }, phoneNumber: "+1-212-555-4240", referenceId: "YOUR_REFERENCE_ID", note: "a customer" }); console.log("Customer ID:", customer.customer?.id); console.log("Created at:", customer.customer?.createdAt); ``` ## Search Customers Search for customers with filters, date ranges, and sorting ```typescript const searchResult = await client.customers.search({ limit: BigInt(2), query: { filter: { creationSource: { values: ["THIRD_PARTY"], rule: "INCLUDE" }, createdAt: { startAt: "2018-01-01T00:00:00-00:00", endAt: "2018-02-01T00:00:00-00:00" }, emailAddress: { fuzzy: "example.com" }, groupIds: { all: ["545AXB44B4XXWMVQ4W8SBT3HHF"] } }, sort: { field: "CREATED_AT", order: "ASC" } } }); for (const customer of searchResult.customers || []) { console.log("Customer:", customer.givenName, customer.familyName); } ``` ## Batch Create Customers Create multiple customer profiles in a single API call ```typescript const batchResult = await client.customers.batchCreate({ customers: { "8bb76c4f-e35d-4c5b-90de-1194cd9179f0": { givenName: "Amelia", familyName: "Earhart", emailAddress: "Amelia.Earhart@example.com", address: { addressLine1: "500 Electric Ave", addressLine2: "Suite 600", locality: "New York", administrativeDistrictLevel1: "NY", postalCode: "10003", country: "US" }, phoneNumber: "+1-212-555-4240", referenceId: "YOUR_REFERENCE_ID", note: "a customer" }, "d1689f23-b25d-4932-b2f0-aed00f5e2029": { givenName: "Marie", familyName: "Curie", emailAddress: "Marie.Curie@example.com", address: { addressLine1: "500 Electric Ave", addressLine2: "Suite 601", locality: "New York", administrativeDistrictLevel1: "NY", postalCode: "10003", country: "US" }, phoneNumber: "+1-212-444-4240", referenceId: "YOUR_REFERENCE_ID", note: "another customer" } } }); console.log("Created customers:", Object.keys(batchResult.results || {}).length); ``` ## Add Card on File Link a payment card to a customer profile for future use ```typescript const cardResult = await client.customers.cards.create({ customerId: "W92WH6P11H4Z77CTET0RNTGFW8", cardNonce: "cnon:card-nonce-ok", billingAddress: { addressLine1: "500 Electric Ave", addressLine2: "Suite 600", locality: "New York", administrativeDistrictLevel1: "NY", postalCode: "10003", country: "US" }, cardholderName: "Amelia Earhart", verificationToken: "verification_token" }); console.log("Card ID:", cardResult.card?.id); console.log("Last 4:", cardResult.card?.last4); console.log("Brand:", cardResult.card?.cardBrand); ``` ## Create Order Create a comprehensive order with line items, taxes, and discounts ```typescript const order = await client.orders.create({ order: { locationId: "057P5VYJ4A5X1", referenceId: "my-order-001", lineItems: [ { name: "New York Strip Steak", quantity: "1", basePriceMoney: { amount: BigInt(1599), currency: "USD" } }, { quantity: "2", catalogObjectId: "BEMYCSMIJL46OCDV4KYIKXIB", modifiers: [ { catalogObjectId: "CHQX7Y4KY6N5KINJKZCFURPZ" } ], appliedDiscounts: [ { discountUid: "one-dollar-off" } ] } ], taxes: [ { uid: "state-sales-tax", name: "State Sales Tax", percentage: "9", scope: "ORDER" } ], discounts: [ { uid: "labor-day-sale", name: "Labor Day Sale", percentage: "5", scope: "ORDER" }, { uid: "membership-discount", catalogObjectId: "DB7L55ZH2BGWI4H23ULIWOQ7", scope: "ORDER" }, { uid: "one-dollar-off", name: "Sale - $1.00 off", amountMoney: { amount: BigInt(100), currency: "USD" }, scope: "LINE_ITEM" } ] }, idempotencyKey: "8193148c-9586-11e6-99f9-28cfe92138cf" }); console.log("Order ID:", order.order?.id); console.log("Total:", order.order?.totalMoney?.amount); ``` ## Calculate Order Preview order pricing without creating the order ```typescript const calculation = await client.orders.calculate({ order: { locationId: "D7AVYMEAPJ3A3", lineItems: [ { name: "Item 1", quantity: "1", basePriceMoney: { amount: BigInt(500), currency: "USD" } }, { name: "Item 2", quantity: "2", basePriceMoney: { amount: BigInt(300), currency: "USD" } } ], discounts: [ { name: "50% Off", percentage: "50", scope: "ORDER" } ] } }); console.log("Subtotal:", calculation.order?.totalMoney?.amount); console.log("Tax:", calculation.order?.totalTaxMoney?.amount); console.log("Total:", calculation.order?.totalMoney?.amount); ``` ## Search Orders Search for orders with advanced filters and sorting ```typescript const searchResult = await client.orders.search({ locationIds: ["057P5VYJ4A5X1", "18YC4JDH91E1H"], query: { filter: { stateFilter: { states: ["COMPLETED"] }, dateTimeFilter: { closedAt: { startAt: "2018-03-03T20:00:00+00:00", endAt: "2019-03-04T21:54:45+00:00" } } }, sort: { sortField: "CLOSED_AT", sortOrder: "DESC" } }, limit: 3, returnEntries: true }); for (const order of searchResult.orders || []) { console.log("Order:", order.id, order.totalMoney?.amount); } ``` ## Update Order Modify an existing open order's line items and properties ```typescript const updatedOrder = await client.orders.update({ orderId: "order_id", order: { locationId: "location_id", lineItems: [ { uid: "cookie_uid", name: "COOKIE", quantity: "2", basePriceMoney: { amount: BigInt(200), currency: "USD" } } ], version: 1 }, fieldsToClear: ["discounts"], idempotencyKey: "UNIQUE_STRING" }); console.log("Updated order:", updatedOrder.order?.id); console.log("Version:", updatedOrder.order?.version); ``` ## Pay Order Complete an order with one or more payment IDs ```typescript const payResult = await client.orders.pay({ orderId: "order_id", idempotencyKey: "c043a359-7ad9-4136-82a9-c3f1d66dcbff", paymentIds: [ "EnZdNAlWCmfh6Mt5FMNST1o7taB", "0LRiVlbXVwe8ozu4KbZxd12mvaB" ] }); console.log("Order status:", payResult.order?.state); console.log("Payment IDs:", payResult.order?.tenders?.map(t => t.id)); ``` ## Batch Upsert Catalog Objects Create or update multiple catalog items, variations, and modifiers ```typescript const catalogResult = await client.catalog.batchUpsert({ idempotencyKey: "789ff020-f723-43a9-b4b5-43b5dc1fa3dc", batches: [ { objects: [ { type: "ITEM", id: "#Coffee", presentAtAllLocations: true, itemData: { name: "Coffee", description: "Premium roast coffee", categoryId: "#Beverages", variations: [ { type: "ITEM_VARIATION", id: "#Small", itemVariationData: { itemId: "#Coffee", name: "Small", pricingType: "FIXED_PRICING", priceMoney: { amount: BigInt(250), currency: "USD" } } } ] } }, { type: "TAX", id: "#SalesTax", presentAtAllLocations: true, taxData: { name: "Sales Tax", calculationPhase: "TAX_SUBTOTAL_PHASE", inclusionType: "ADDITIVE", percentage: "8.5", enabled: true } } ] } ] }); console.log("Upserted objects:", catalogResult.objects?.length); ``` ## Search Catalog Objects Search for catalog items with prefix and custom queries ```typescript const catalogSearch = await client.catalog.search({ objectTypes: ["ITEM"], query: { prefixQuery: { attributeName: "name", attributePrefix: "tea" } }, limit: 100 }); for (const obj of catalogSearch.objects || []) { console.log("Item:", obj.itemData?.name); } ``` ## Search Catalog Items Advanced search with filters for custom attributes and stock levels ```typescript const itemSearch = await client.catalog.searchItems({ textFilter: "red", categoryIds: ["WINE_CATEGORY_ID"], stockLevels: ["OUT", "LOW"], enabledLocationIds: ["ATL_LOCATION_ID"], limit: 100, sortOrder: "ASC", productTypes: ["REGULAR"], customAttributeFilters: [ { customAttributeDefinitionId: "VEGAN_DEFINITION_ID", boolFilter: true }, { customAttributeDefinitionId: "BRAND_DEFINITION_ID", stringFilter: "Dark Horse" }, { key: "VINTAGE", numberFilter: { min: "2015", max: "2020" } } ] }); console.log("Found items:", itemSearch.items?.length); ``` ## Batch Get Catalog Objects Retrieve multiple catalog objects by ID with related objects ```typescript const batchGet = await client.catalog.batchGet({ objectIds: [ "W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK" ], includeRelatedObjects: true }); for (const obj of batchGet.objects || []) { console.log("Object:", obj.type, obj.id); } ``` ## List Locations Retrieve all business locations for the merchant ```typescript const locations = await client.locations.list(); for (const location of locations.locations || []) { console.log("Location:", location.name); console.log("Address:", location.address?.addressLine1); console.log("Status:", location.status); } ``` ## Create Location Add a new business location with address and details ```typescript const newLocation = await client.locations.create({ location: { name: "Midtown", address: { addressLine1: "1234 Peachtree St. NE", locality: "Atlanta", administrativeDistrictLevel1: "GA", postalCode: "30309" }, description: "Midtown Atlanta store" } }); console.log("Location ID:", newLocation.location?.id); console.log("Created at:", newLocation.location?.createdAt); ``` ## Update Location Update location business hours and other properties ```typescript const updatedLocation = await client.locations.update({ locationId: "location_id", location: { businessHours: { periods: [ { dayOfWeek: "FRI", startLocalTime: "07:00", endLocalTime: "18:00" }, { dayOfWeek: "SAT", startLocalTime: "07:00", endLocalTime: "18:00" }, { dayOfWeek: "SUN", startLocalTime: "09:00", endLocalTime: "15:00" } ] }, description: "Midtown Atlanta store - Open weekends" } }); console.log("Updated location:", updatedLocation.location?.name); ``` ## Create Subscription Enroll a customer in a recurring subscription plan ```typescript const subscription = await client.subscriptions.create({ idempotencyKey: "8193148c-9586-11e6-99f9-28cfe92138cf", locationId: "S8GWD5R9QB376", planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", startDate: "2023-06-20", cardId: "ccof:qy5x8hHGYsgLrp4Q4GB", timezone: "America/Los_Angeles", source: { name: "My Application" }, phases: [ { ordinal: BigInt(0), orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY" } ] }); console.log("Subscription ID:", subscription.subscription?.id); console.log("Status:", subscription.subscription?.status); ``` ## Create Refund Issue a refund for a payment ```typescript const refund = await client.refunds.create({ idempotencyKey: "a7e36d40-d24b-11e8-b568-0800200c9a66", amountMoney: { amount: BigInt(100), currency: "USD" }, paymentId: "PAYMENT_ID", reason: "Customer requested refund" }); console.log("Refund ID:", refund.refund?.id); console.log("Status:", refund.refund?.status); console.log("Amount:", refund.refund?.amountMoney?.amount); ``` ## Create Loyalty Account Create a loyalty account for a customer with phone mapping ```typescript const loyaltyAccount = await client.loyalty.accounts.create({ loyaltyAccount: { programId: "d619f755-2d17-41f3-990d-c04ecedd64dd", mapping: { phoneNumber: "+14155551234" } }, idempotencyKey: "ec78c477-b1c3-4899-a209-a4e71337c996" }); console.log("Account ID:", loyaltyAccount.loyaltyAccount?.id); console.log("Balance:", loyaltyAccount.loyaltyAccount?.balance); ``` ## Create Loyalty Reward Create a reward for redemption from loyalty points ```typescript const reward = await client.loyalty.rewards.create({ reward: { loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", orderId: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY" }, idempotencyKey: "18c2e5ea-a620-4b1f-ad60-7b167285e451" }); console.log("Reward ID:", reward.reward?.id); console.log("Points:", reward.reward?.points); ``` ## Search Loyalty Events Search for loyalty program events with filters ```typescript const events = await client.loyalty.searchEvents({ query: { filter: { orderFilter: { orderId: "PyATxhYLfsMqpVkcKJITPydgEYfZY" } } }, limit: 30 }); for (const event of events.events || []) { console.log("Event:", event.type, event.createdAt); } ``` ## List Invoices Retrieve invoices for a specific location with pagination ```typescript const invoicesResponse = await client.invoices.list({ locationId: "location_id" }); for await (const invoice of invoicesResponse) { console.log("Invoice:", invoice.invoiceNumber); console.log("Status:", invoice.status); console.log("Amount:", invoice.primaryRecipient?.emailAddress); } ``` ## Verify Webhook Signature Verify that webhook events originate from Square ```typescript import { WebhooksHelper } from "square"; // In your webhook endpoint handler app.post("/webhook", (req, res) => { const signatureHeader = req.headers['x-square-hmacsha256-signature']; const requestBody = JSON.stringify(req.body); const isValid = WebhooksHelper.verifySignature({ requestBody: requestBody, signatureHeader: signatureHeader, signatureKey: "YOUR_SIGNATURE_KEY", notificationUrl: "https://example.com/webhook" }); if (!isValid) { return res.status(403).send("Invalid signature"); } // Process webhook event const event = req.body; console.log("Event type:", event.type); console.log("Event data:", event.data); res.status(200).send("OK"); }); ``` ## Error Handling Handle API errors with typed exception classes ```typescript import { SquareClient, SquareError } from "square"; const client = new SquareClient({ token: "YOUR_TOKEN" }); try { const payment = await client.payments.create({ sourceId: "ccof:invalid", idempotencyKey: "unique-key", amountMoney: { amount: BigInt(100), currency: "USD" } }); } catch (err) { if (err instanceof SquareError) { console.error("HTTP Status:", err.statusCode); console.error("Error message:", err.message); console.error("Error body:", err.body); console.error("Errors:", err.body?.errors); } else { console.error("Unexpected error:", err); } } ``` ## Request Options Customize requests with timeouts, retries, and custom headers ```typescript // Override timeout for specific request const response = await client.payments.create( { sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", idempotencyKey: "unique-key", amountMoney: { amount: BigInt(1000), currency: "USD" } }, { timeoutInSeconds: 30, maxRetries: 3, version: "2024-05-04", headers: { 'X-Custom-Header': 'custom-value' } } ); // Abort request with AbortController const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); const payment = await client.payments.create( { sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", idempotencyKey: "unique-key", amountMoney: { amount: BigInt(1000), currency: "USD" } }, { abortSignal: controller.signal } ); ``` ## Type Definitions Import and use Square type definitions ```typescript import { Square } from "square"; const createPaymentRequest: Square.CreatePaymentRequest = { sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", idempotencyKey: "unique-key", amountMoney: { amount: BigInt(1000), currency: "USD" } }; const payment: Square.Payment = { id: "payment_id", status: "COMPLETED", amountMoney: { amount: BigInt(1000), currency: "USD" } }; // Type-safe customer object const customer: Square.Customer = { id: "customer_id", givenName: "John", familyName: "Doe", emailAddress: "john.doe@example.com", createdAt: "2023-01-01T00:00:00Z" }; ``` ## Legacy SDK Compatibility Use both new and legacy SDK APIs in the same application ```typescript import { randomUUID } from "crypto"; import { Square, SquareClient } from "square"; import { Client } from "square/legacy"; // New SDK client const client = new SquareClient({ token: process.env.SQUARE_ACCESS_TOKEN }); // Legacy SDK client const legacyClient = new Client({ bearerAuthCredentials: { accessToken: process.env.SQUARE_ACCESS_TOKEN! } }); // Use new SDK for simple operations async function getLocation(): Promise { return ( await client.locations.get({ locationId: "YOUR_LOCATION_ID" }) ).location!; } // Use legacy SDK for operations not yet migrated async function createOrder() { const location = await getLocation(); await legacyClient.ordersApi.createOrder({ idempotencyKey: randomUUID(), order: { locationId: location.id!, lineItems: [ { name: "New Item", quantity: "1", basePriceMoney: { amount: BigInt(100), currency: "USD" } } ] } }); } createOrder(); ``` --- The Square SDK enables a wide range of commerce integration patterns for modern applications. For e-commerce platforms, developers can create complete checkout flows by combining the Orders API with the Payments API - first creating an order with line items, taxes, and discounts, then processing payment against that order, and finally handling fulfillment. The SDK's built-in pagination support makes it easy to build customer dashboards that display order history, payment records, and subscription status. The idempotency keys ensure that network retries don't result in duplicate charges, which is critical for production payment systems. For point-of-sale and retail applications, the SDK provides comprehensive inventory management through the Catalog and Inventory APIs. Merchants can maintain product catalogs with variations, modifiers, and images, track stock levels across multiple locations, and sync inventory changes in real-time. The Locations API allows multi-location businesses to manage separate configurations for each store while maintaining centralized customer and loyalty data. The Customers API with card-on-file support enables fast checkout experiences, while the Loyalty API helps merchants build retention programs with points, rewards, and promotions. The webhook signature verification utilities ensure secure handling of asynchronous events like payment status updates, order fulfillment notifications, and inventory alerts. With support for subscriptions, recurring billing, and custom attributes, the SDK provides the building blocks for sophisticated commerce applications across retail, hospitality, services, and digital goods sectors.