出品者:Arnav

Full-featured TypeScript/Node.js SDK for the Square API, covering payments, orders, catalog, customers, loyalty, and more. Includes pagination helpers, webhook verification, and a legacy compatibility layer.
This block provides the full TypeScript source of the Square Node.js SDK (user@example.com), giving you direct access to Square's payment, order, customer, catalog, and dozens of other commerce APIs. It is aimed at Node.js/TypeScript backend developers who need to integrate Square into an Express, Fastify, or similar server application. The SDK is strongly typed, supports pagination, file uploads, webhook verification, and optional legacy compatibility.
api/ - All resource clients (payments, orders, customers, catalog, etc.) and their TypeScript request/response typesauth/ - Authentication utilities used internally by the clientcore/ - HTTP transport, retry logic, pagination helpers, and raw response handlingerrors/ - SquareError and SquareTimeoutError error classesserialization/ - Fern-generated serialization/deserialization layer for all API typeswrapper/ - WebhooksHelper for verifying incoming webhook signaturesBaseClient.ts - Abstract base containing shared option types (BaseClientOptions, BaseRequestOptions)Client.ts - SquareClient - the main entry point you instantiate in application codeenvironments.ts - SquareEnvironment enum (Production, Sandbox)exports.ts - Re-exports for convenience aliasingindex.ts - Root barrel: all public exports collected in one placeversion.ts - SDK version constant used in User-Agent headersnpm install square form-data form-data-encoder formdata-node node-fetch readable-stream square-legacy
No native build steps, pod installs, or Expo prebuild are required. This is a pure Node.js package.
Copy the source. Place the source/ directory anywhere inside your project, e.g. src/square/. All internal imports use .js extensions (ESM-compatible).
TypeScript config. Ensure your tsconfig.json targets ES2020+ and uses , , or module resolution:
隔離されたサンドボックスを起動しサーバー側で実行 — ローカル設定不要。
このバージョンの Tetrees AI Review
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
パイプライン avcp-2026-08-04.1 · SHA-256 ad289d892b1ac6cd…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
レビュー日 2026年8月4日
この製品をお使いのAI IDE・Webビルダー・クラウドIDEに直接取り込みます。
Tetreesを対応AI IDEに接続し、所有製品の一覧取得と検証済みZIPの取得を、販売者のアップロード権限を公開せずに行えます。
まだレビューがありません。
Sign in to join the discussion
Loading discussion…
node16nodenextbundler{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"outDir": "dist"
}
}
# .env
SQUARE_ACCESS_TOKEN=EAAAl...your_token
SQUARE_ENVIRONMENT=sandbox # or production
import { SquareClient, SquareEnvironment } from "./square/index.js";
moduleResolution is NodeNext or bundler. If you use Webpack/Vite, add an alias from square to ./src/square/index.ts in your bundler config.import { SquareClient, SquareEnvironment } from "./square/index.js";
const client = new SquareClient({
token: process.env.SQUARE_ACCESS_TOKEN,
environment: SquareEnvironment.Sandbox, // or Production
});
The main SDK entry point. Accepts BaseClientOptions including token, environment, maxRetries, timeoutInSeconds, and additionalHeaders. Every Square API surface is accessible as a sub-client property (client.payments, client.orders, client.customers, etc.).
import { SquareEnvironment } from "./square/index.js";
// SquareEnvironment.Production → "https://connect.squareup.com"
// SquareEnvironment.Sandbox → "https://connect.squareupsandbox.com"
An enum that selects the API base URL. Pass it to SquareClient at construction time. Use Sandbox for testing and Production for live traffic.
import { SquareError, SquareTimeoutError } from "./square/index.js";
try {
await client.payments.create({ ... });
} catch (err) {
if (err instanceof SquareTimeoutError) {
console.error("Request timed out");
} else if (err instanceof SquareError) {
console.error(err.statusCode, err.message, err.body);
}
}
Typed error classes thrown by all API calls. SquareError carries statusCode and body. Catch them separately to distinguish network timeouts from API-level errors.
import { WebhooksHelper } from "./square/index.js";
const isValid = WebhooksHelper.isValidWebhookEventSignature(
rawBody, // string - the raw request body
signature, // string - value of "x-square-hmacsha256-signature" header
signatureKey, // string - from Square developer dashboard
notificationUrl // string - the URL Square POST'd to
);
Verifies that an incoming webhook request genuinely came from Square. Always validate before processing webhook payloads.
Takes a nonce (card token from Square Web Payments SDK) and charges a customer.
import { SquareClient, SquareEnvironment, SquareError } from "./square/index.js";
const client = new SquareClient({
token: process.env.SQUARE_ACCESS_TOKEN!,
environment: SquareEnvironment.Sandbox,
});
async function chargeCard(sourceId: string, customerId: string) {
try {
const response = await client.payments.create({
sourceId,
idempotencyKey: crypto.randomUUID(),
amountMoney: {
amount: BigInt("1500"), // $15.00 in cents
currency: "USD",
},
customerId,
locationId: process.env.SQUARE_LOCATION_ID!,
note: "Order #1042",
});
console.log("Payment created:", response.payment?.id);
return response.payment;
} catch (err) {
if (err instanceof SquareError) {
console.error("Square API error", err.statusCode, err.body);
}
throw err;
}
}
Retrieve all orders for a location using the built-in pagination support.
import { SquareClient, SquareEnvironment } from "./square/index.js";
const client = new SquareClient({
token: process.env.SQUARE_ACCESS_TOKEN!,
environment: SquareEnvironment.Sandbox,
});
async function fetchAllOrders(locationId: string) {
const allOrders = [];
// The SDK returns a pager; iterate with for-await
const pager = await client.orders.search({
locationIds: [locationId],
limit: 50,
});
for await (const order of pager) {
allOrders.push(order);
}
console.log(`Fetched ${allOrders.length} orders`);
return allOrders;
}
Verify Square webhook signatures before trusting the payload.
import express from "express";
import { WebhooksHelper, SquareError } from "./square/index.js";
const app = express();
// Must use raw body for signature verification
app.post(
"/webhooks/square",
express.raw({ type: "application/json" }),
(req, res) => {
const signature = req.headers["x-square-hmacsha256-signature"] as string;
const rawBody = req.body.toString("utf8");
const signatureKey = process.env.SQUARE_WEBHOOK_SIGNATURE_KEY!;
const notificationUrl = process.env.SQUARE_WEBHOOK_URL!;
const valid = WebhooksHelper.isValidWebhookEventSignature(
rawBody,
signature,
signatureKey,
notificationUrl
);
if (!valid) {
res.status(403).send("Invalid signature");
return;
}
const event = JSON.parse(rawBody);
console.log("Received Square event:", event.type);
res.status(200).send("OK");
}
);
app.listen(3000);
import { SquareClient, SquareEnvironment } from "./square/index.js";
const client = new SquareClient({
token: process.env.SQUARE_ACCESS_TOKEN!,
environment: SquareEnvironment.Production,
});
async function onboardCustomer(email: string, givenName: string) {
const { customer } = await client.customers.create({
idempotencyKey: crypto.randomUUID(),
givenName,
emailAddress: email,
});
console.log("Customer ID:", customer?.id);
const { bankAccounts } = await client.bankAccounts.list({});
console.log("Bank accounts on file:", bankAccounts?.length ?? 0);
return customer;
}
index.ts - Root barrel; re-exports SquareClient, SquareEnvironment, SquareError, SquareTimeoutError, WebhooksHelper, and the full Square namespace.Client.ts - Implements SquareClient; wires together all resource sub-clients and applies auth headers.BaseClient.ts - Defines BaseClientOptions and BaseRequestOptions shared across all request methods.environments.ts - Declares the SquareEnvironment enum mapping names to base URLs.exports.ts - Additional convenience re-exports consumed by index.ts.version.ts - Holds the SDK version string injected into the User-Agent header.api/ - Contains every resource namespace (payments, orders, customers, etc.) and their TypeScript request/response types.api/resources/ - One sub-directory per Square API domain; each contains a Client.ts and typed requests/ objects.auth/ - Bearer token and OAuth credential handling used internally.core/ - Low-level HTTP fetcher, retry/backoff, pagination cursor logic, and raw-response accessor.errors/ - SquareError and SquareTimeoutError exported for consumer catch blocks.serialization/ - Auto-generated encode/decode layer; transforms API JSON to/from SDK TypeScript types.wrapper/ - Houses WebhooksHelper for HMAC-SHA256 signature verification.moduleResolution must be node16/nodenext/bundler - The source uses .js extensions in imports; older node resolution silently fails. Fix: set "moduleResolution": "NodeNext" in tsconfig.json.BigInt serialization to JSON - amount fields use BigInt; JSON.stringify throws by default. Fix: use a replacer or serialize with .toString() before logging.express.json() parses and discards the raw buffer. Fix: use express.raw({ type: 'application/json' }) on the webhook route before parsing.SquareEnvironment.Sandbox. Fix: set environment to match your token type.SQUARE_ACCESS_TOKEN undefined at runtime - Missing .env loading. Fix: call require('dotenv').config() or use --env-file .env (Node 20+) before instantiating SquareClient.square-legacy - If you import from square/legacy you need the square-legacy package. Fix: ensure it is installed (npm install square-legacy) even if you only use the new SDK.I have dropped the Square Node.js SDK TypeScript source into `src/square/`
in my project. The entry point is `src/square/index.ts`.
I also have `USAGE.md` in the project root describing the public API.
Upstream package: user@example.com
Please help me integrate this SDK into my existing project step by step:
1. Read `USAGE.md` and `src/square/index.ts` to understand all exports.
2. Update my `tsconfig.json` to use `moduleResolution: NodeNext` if not already set.
3. Create a `src/squareClient.ts` singleton that reads SQUARE_ACCESS_TOKEN
and SQUARE_ENVIRONMENT from process.env and exports a ready-to-use
`SquareClient` instance.
4. Add an Express route (or equivalent) that calls the Square API method
I need: [DESCRIBE YOUR USE CASE HERE].
5. Add a `/webhooks/square` route that verifies the signature with
`WebhooksHelper` before processing events.
6. Handle `SquareError` and `SquareTimeoutError` in all API call sites.
7. Show me only the changed/new files, with full file contents.
The Square Node.js SDK is released by Square under the Apache-2.0 License (see source/LICENSE if present, or the upstream repository). This block wraps user@example.com published on npm at https://www.npmjs.com/package/square.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完全なインストールガイドと統合プロンプトは購入後に解放されます。
eCommerce, Marketplace & POS Systems
無料