chub-dev 0.1.0 → 0.1.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +55 -0
  2. package/bin/chub-mcp +2 -0
  3. package/dist/airtable/docs/database/javascript/DOC.md +1437 -0
  4. package/dist/airtable/docs/database/python/DOC.md +1735 -0
  5. package/dist/amplitude/docs/analytics/javascript/DOC.md +1282 -0
  6. package/dist/amplitude/docs/analytics/python/DOC.md +1199 -0
  7. package/dist/anthropic/docs/claude-api/javascript/DOC.md +503 -0
  8. package/dist/anthropic/docs/claude-api/python/DOC.md +389 -0
  9. package/dist/asana/docs/tasks/DOC.md +1396 -0
  10. package/dist/assemblyai/docs/transcription/DOC.md +1043 -0
  11. package/dist/atlassian/docs/confluence/javascript/DOC.md +1347 -0
  12. package/dist/atlassian/docs/confluence/python/DOC.md +1604 -0
  13. package/dist/auth0/docs/identity/javascript/DOC.md +968 -0
  14. package/dist/auth0/docs/identity/python/DOC.md +1199 -0
  15. package/dist/aws/docs/s3/javascript/DOC.md +1773 -0
  16. package/dist/aws/docs/s3/python/DOC.md +1807 -0
  17. package/dist/binance/docs/trading/javascript/DOC.md +1315 -0
  18. package/dist/binance/docs/trading/python/DOC.md +1454 -0
  19. package/dist/braintree/docs/gateway/javascript/DOC.md +1278 -0
  20. package/dist/braintree/docs/gateway/python/DOC.md +1179 -0
  21. package/dist/chromadb/docs/embeddings-db/javascript/DOC.md +1263 -0
  22. package/dist/chromadb/docs/embeddings-db/python/DOC.md +1707 -0
  23. package/dist/clerk/docs/auth/javascript/DOC.md +1220 -0
  24. package/dist/clerk/docs/auth/python/DOC.md +274 -0
  25. package/dist/cloudflare/docs/workers/javascript/DOC.md +918 -0
  26. package/dist/cloudflare/docs/workers/python/DOC.md +994 -0
  27. package/dist/cockroachdb/docs/distributed-db/DOC.md +1500 -0
  28. package/dist/cohere/docs/llm/DOC.md +1335 -0
  29. package/dist/datadog/docs/monitoring/javascript/DOC.md +1740 -0
  30. package/dist/datadog/docs/monitoring/python/DOC.md +1815 -0
  31. package/dist/deepgram/docs/speech/javascript/DOC.md +885 -0
  32. package/dist/deepgram/docs/speech/python/DOC.md +685 -0
  33. package/dist/deepl/docs/translation/javascript/DOC.md +887 -0
  34. package/dist/deepl/docs/translation/python/DOC.md +944 -0
  35. package/dist/deepseek/docs/llm/DOC.md +1220 -0
  36. package/dist/directus/docs/headless-cms/javascript/DOC.md +1128 -0
  37. package/dist/directus/docs/headless-cms/python/DOC.md +1276 -0
  38. package/dist/discord/docs/bot/javascript/DOC.md +1090 -0
  39. package/dist/discord/docs/bot/python/DOC.md +1130 -0
  40. package/dist/elasticsearch/docs/search/DOC.md +1634 -0
  41. package/dist/elevenlabs/docs/text-to-speech/javascript/DOC.md +336 -0
  42. package/dist/elevenlabs/docs/text-to-speech/python/DOC.md +552 -0
  43. package/dist/firebase/docs/auth/DOC.md +1015 -0
  44. package/dist/gemini/docs/genai/javascript/DOC.md +691 -0
  45. package/dist/gemini/docs/genai/python/DOC.md +555 -0
  46. package/dist/github/docs/octokit/DOC.md +1560 -0
  47. package/dist/google/docs/bigquery/javascript/DOC.md +1688 -0
  48. package/dist/google/docs/bigquery/python/DOC.md +1503 -0
  49. package/dist/hubspot/docs/crm/javascript/DOC.md +1805 -0
  50. package/dist/hubspot/docs/crm/python/DOC.md +2033 -0
  51. package/dist/huggingface/docs/transformers/DOC.md +948 -0
  52. package/dist/intercom/docs/messaging/javascript/DOC.md +1844 -0
  53. package/dist/intercom/docs/messaging/python/DOC.md +1797 -0
  54. package/dist/jira/docs/issues/javascript/DOC.md +1420 -0
  55. package/dist/jira/docs/issues/python/DOC.md +1492 -0
  56. package/dist/kafka/docs/streaming/javascript/DOC.md +1671 -0
  57. package/dist/kafka/docs/streaming/python/DOC.md +1464 -0
  58. package/dist/landingai-ade/docs/api/DOC.md +620 -0
  59. package/dist/landingai-ade/docs/sdk/python/DOC.md +489 -0
  60. package/dist/landingai-ade/docs/sdk/typescript/DOC.md +542 -0
  61. package/dist/landingai-ade/skills/SKILL.md +489 -0
  62. package/dist/launchdarkly/docs/feature-flags/javascript/DOC.md +1191 -0
  63. package/dist/launchdarkly/docs/feature-flags/python/DOC.md +1671 -0
  64. package/dist/linear/docs/tracker/DOC.md +1554 -0
  65. package/dist/livekit/docs/realtime/javascript/DOC.md +303 -0
  66. package/dist/livekit/docs/realtime/python/DOC.md +163 -0
  67. package/dist/mailchimp/docs/marketing/DOC.md +1420 -0
  68. package/dist/meilisearch/docs/search/DOC.md +1241 -0
  69. package/dist/microsoft/docs/onedrive/javascript/DOC.md +1421 -0
  70. package/dist/microsoft/docs/onedrive/python/DOC.md +1549 -0
  71. package/dist/mongodb/docs/atlas/DOC.md +2041 -0
  72. package/dist/notion/docs/workspace-api/javascript/DOC.md +1435 -0
  73. package/dist/notion/docs/workspace-api/python/DOC.md +1400 -0
  74. package/dist/okta/docs/identity/javascript/DOC.md +1171 -0
  75. package/dist/okta/docs/identity/python/DOC.md +1401 -0
  76. package/dist/openai/docs/chat/javascript/DOC.md +407 -0
  77. package/dist/openai/docs/chat/python/DOC.md +568 -0
  78. package/dist/paypal/docs/checkout/DOC.md +278 -0
  79. package/dist/pinecone/docs/sdk/javascript/DOC.md +984 -0
  80. package/dist/pinecone/docs/sdk/python/DOC.md +1395 -0
  81. package/dist/plaid/docs/banking/javascript/DOC.md +1163 -0
  82. package/dist/plaid/docs/banking/python/DOC.md +1203 -0
  83. package/dist/playwright-community/skills/login-flows/SKILL.md +108 -0
  84. package/dist/postmark/docs/transactional-email/DOC.md +1168 -0
  85. package/dist/prisma/docs/orm/javascript/DOC.md +1419 -0
  86. package/dist/prisma/docs/orm/python/DOC.md +1317 -0
  87. package/dist/qdrant/docs/vector-search/javascript/DOC.md +1221 -0
  88. package/dist/qdrant/docs/vector-search/python/DOC.md +1653 -0
  89. package/dist/rabbitmq/docs/message-queue/javascript/DOC.md +1193 -0
  90. package/dist/rabbitmq/docs/message-queue/python/DOC.md +1243 -0
  91. package/dist/razorpay/docs/payments/javascript/DOC.md +1219 -0
  92. package/dist/razorpay/docs/payments/python/DOC.md +1330 -0
  93. package/dist/redis/docs/key-value/javascript/DOC.md +1851 -0
  94. package/dist/redis/docs/key-value/python/DOC.md +2054 -0
  95. package/dist/registry.json +2817 -0
  96. package/dist/replicate/docs/model-hosting/DOC.md +1318 -0
  97. package/dist/resend/docs/email/DOC.md +1271 -0
  98. package/dist/salesforce/docs/crm/javascript/DOC.md +1241 -0
  99. package/dist/salesforce/docs/crm/python/DOC.md +1183 -0
  100. package/dist/search-index.json +1 -0
  101. package/dist/sendgrid/docs/email-api/javascript/DOC.md +371 -0
  102. package/dist/sendgrid/docs/email-api/python/DOC.md +656 -0
  103. package/dist/sentry/docs/error-tracking/javascript/DOC.md +1073 -0
  104. package/dist/sentry/docs/error-tracking/python/DOC.md +1309 -0
  105. package/dist/shopify/docs/storefront/DOC.md +457 -0
  106. package/dist/slack/docs/workspace/javascript/DOC.md +933 -0
  107. package/dist/slack/docs/workspace/python/DOC.md +271 -0
  108. package/dist/square/docs/payments/javascript/DOC.md +1855 -0
  109. package/dist/square/docs/payments/python/DOC.md +1728 -0
  110. package/dist/stripe/docs/api/DOC.md +1727 -0
  111. package/dist/stripe/docs/payments/DOC.md +1726 -0
  112. package/dist/stytch/docs/auth/javascript/DOC.md +1813 -0
  113. package/dist/stytch/docs/auth/python/DOC.md +1962 -0
  114. package/dist/supabase/docs/client/DOC.md +1606 -0
  115. package/dist/twilio/docs/messaging/python/DOC.md +469 -0
  116. package/dist/twilio/docs/messaging/typescript/DOC.md +946 -0
  117. package/dist/vercel/docs/platform/DOC.md +1940 -0
  118. package/dist/weaviate/docs/vector-db/javascript/DOC.md +1268 -0
  119. package/dist/weaviate/docs/vector-db/python/DOC.md +1388 -0
  120. package/dist/zendesk/docs/support/javascript/DOC.md +2150 -0
  121. package/dist/zendesk/docs/support/python/DOC.md +2297 -0
  122. package/package.json +22 -6
  123. package/skills/get-api-docs/SKILL.md +84 -0
  124. package/src/commands/annotate.js +83 -0
  125. package/src/commands/build.js +12 -1
  126. package/src/commands/feedback.js +150 -0
  127. package/src/commands/get.js +83 -42
  128. package/src/commands/search.js +7 -0
  129. package/src/index.js +43 -17
  130. package/src/lib/analytics.js +90 -0
  131. package/src/lib/annotations.js +57 -0
  132. package/src/lib/bm25.js +170 -0
  133. package/src/lib/cache.js +69 -6
  134. package/src/lib/config.js +8 -3
  135. package/src/lib/identity.js +99 -0
  136. package/src/lib/registry.js +103 -20
  137. package/src/lib/telemetry.js +86 -0
  138. package/src/mcp/server.js +177 -0
  139. package/src/mcp/tools.js +251 -0
@@ -0,0 +1,1855 @@
1
+ ---
2
+ name: payments
3
+ description: "Square SDK coding guide for payments, POS, and commerce checkout"
4
+ metadata:
5
+ languages: "javascript"
6
+ versions: "43.2.0"
7
+ updated-on: "2026-03-02"
8
+ source: maintainer
9
+ tags: "square,payments,pos,commerce,checkout"
10
+ ---
11
+
12
+ # Square SDK Coding Guide
13
+
14
+ ## 1. Golden Rule
15
+
16
+ **Always use the official Square SDK package:**
17
+ - Package name: `square` (Node.js/TypeScript library for Square API)
18
+ - Official repository: https://github.com/square/square-nodejs-sdk
19
+
20
+ **Never use deprecated libraries:**
21
+ - `square-connect` (DEPRECATED - replaced by `square`)
22
+ - `connect-nodejs-sdk` (DEPRECATED - replaced by `square`)
23
+
24
+ **Current SDK Version:** v43.2.0
25
+
26
+ **API Versioning:** Square uses date-based API versioning (e.g., 2025-08-20). Your account is automatically pinned to an API version. You can override this when initializing the client or in the Square Dashboard.
27
+
28
+ ## 2. Installation
29
+
30
+ ```bash
31
+ npm install square
32
+ ```
33
+
34
+ ```bash
35
+ yarn add square
36
+ ```
37
+
38
+ ```bash
39
+ pnpm add square
40
+ ```
41
+
42
+ **Requirements:** Node.js 16+ (Node.js 18+ recommended for production)
43
+
44
+ ### Environment Variables
45
+
46
+ ```bash
47
+ # Required
48
+ SQUARE_ACCESS_TOKEN=EAAAl... # Your Square access token
49
+ SQUARE_ENVIRONMENT=sandbox # or "production"
50
+
51
+ # Optional
52
+ SQUARE_LOCATION_ID=L88917... # Default location ID for operations
53
+ ```
54
+
55
+ **CRITICAL:** Never commit access tokens to version control. Use environment variables or secure secret management systems. Use sandbox tokens for development and testing.
56
+
57
+ ## 3. Initialization
58
+
59
+ ### Basic Initialization
60
+
61
+ ```javascript
62
+ const { SquareClient, SquareEnvironment } = require("square");
63
+
64
+ const client = new SquareClient({
65
+ token: process.env.SQUARE_ACCESS_TOKEN,
66
+ environment: SquareEnvironment.Sandbox,
67
+ });
68
+ ```
69
+
70
+ ### TypeScript Initialization
71
+
72
+ ```typescript
73
+ import { SquareClient, SquareEnvironment, SquareError } from "square";
74
+
75
+ const client = new SquareClient({
76
+ token: process.env.SQUARE_ACCESS_TOKEN!,
77
+ environment: SquareEnvironment.Production,
78
+ });
79
+ ```
80
+
81
+ ### Advanced Configuration
82
+
83
+ ```javascript
84
+ const { SquareClient, SquareEnvironment } = require("square");
85
+
86
+ const client = new SquareClient({
87
+ token: process.env.SQUARE_ACCESS_TOKEN,
88
+ environment: SquareEnvironment.Production,
89
+ timeout: 60000, // 60 second timeout
90
+ squareVersion: "2025-08-20", // Override API version
91
+ additionalHeaders: {
92
+ "User-Agent": "MyApp/1.0.0",
93
+ },
94
+ });
95
+ ```
96
+
97
+ ### ES Module Import
98
+
99
+ ```javascript
100
+ import { SquareClient, SquareEnvironment } from "square";
101
+
102
+ const client = new SquareClient({
103
+ token: process.env.SQUARE_ACCESS_TOKEN,
104
+ environment: SquareEnvironment.Sandbox,
105
+ });
106
+ ```
107
+
108
+ ### Error Handling Setup
109
+
110
+ ```javascript
111
+ const { SquareClient, SquareError } = require("square");
112
+
113
+ async function makeSquareRequest() {
114
+ try {
115
+ // Make API calls here
116
+ } catch (error) {
117
+ if (error instanceof SquareError) {
118
+ // Handle Square-specific errors
119
+ error.errors.forEach(e => {
120
+ console.log(`Category: ${e.category}`);
121
+ console.log(`Code: ${e.code}`);
122
+ console.log(`Detail: ${e.detail}`);
123
+ });
124
+ } else {
125
+ console.log("Unexpected error:", error);
126
+ }
127
+ }
128
+ }
129
+ ```
130
+
131
+ ## 4. Core API Surfaces
132
+
133
+ ### Locations API
134
+
135
+ Get information about business locations.
136
+
137
+ **List All Locations:**
138
+
139
+ ```javascript
140
+ async function listLocations() {
141
+ try {
142
+ const response = await client.locations.list();
143
+ const locations = response.locations;
144
+
145
+ locations.forEach(location => {
146
+ console.log(`${location.id}: ${location.name}`);
147
+ console.log(`Address: ${location.address.addressLine1}`);
148
+ console.log(`City: ${location.address.locality}`);
149
+ });
150
+
151
+ return locations;
152
+ } catch (error) {
153
+ if (error instanceof SquareError) {
154
+ console.error("Error listing locations:", error.errors);
155
+ }
156
+ throw error;
157
+ }
158
+ }
159
+ ```
160
+
161
+ **Retrieve Single Location:**
162
+
163
+ ```javascript
164
+ async function getLocation(locationId) {
165
+ try {
166
+ const response = await client.locations.retrieve(locationId);
167
+ return response.location;
168
+ } catch (error) {
169
+ if (error instanceof SquareError) {
170
+ console.error("Error retrieving location:", error.errors);
171
+ }
172
+ throw error;
173
+ }
174
+ }
175
+ ```
176
+
177
+ ### Payments API
178
+
179
+ Process and manage payments.
180
+
181
+ **Create Payment (Minimal):**
182
+
183
+ ```javascript
184
+ import { randomUUID } from 'crypto';
185
+
186
+ async function createPayment(sourceId, amountMoney, locationId) {
187
+ try {
188
+ const response = await client.payments.create({
189
+ sourceId: sourceId,
190
+ idempotencyKey: randomUUID(),
191
+ amountMoney: {
192
+ amount: BigInt(amountMoney),
193
+ currency: "USD",
194
+ },
195
+ locationId: locationId,
196
+ });
197
+
198
+ return response.payment;
199
+ } catch (error) {
200
+ if (error instanceof SquareError) {
201
+ console.error("Payment error:", error.errors);
202
+ }
203
+ throw error;
204
+ }
205
+ }
206
+ ```
207
+
208
+ **Create Payment (Advanced):**
209
+
210
+ ```javascript
211
+ import { randomUUID } from 'crypto';
212
+
213
+ async function createAdvancedPayment(paymentData) {
214
+ try {
215
+ const response = await client.payments.create({
216
+ sourceId: paymentData.sourceId,
217
+ idempotencyKey: randomUUID(),
218
+ amountMoney: {
219
+ amount: BigInt(paymentData.amount),
220
+ currency: paymentData.currency || "USD",
221
+ },
222
+ locationId: paymentData.locationId,
223
+ customerId: paymentData.customerId,
224
+ referenceId: paymentData.referenceId,
225
+ note: paymentData.note,
226
+ autocomplete: true,
227
+ buyerEmailAddress: paymentData.email,
228
+ billingAddress: {
229
+ addressLine1: paymentData.addressLine1,
230
+ locality: paymentData.city,
231
+ administrativeDistrictLevel1: paymentData.state,
232
+ postalCode: paymentData.postalCode,
233
+ country: paymentData.country || "US",
234
+ },
235
+ });
236
+
237
+ return response.payment;
238
+ } catch (error) {
239
+ if (error instanceof SquareError) {
240
+ console.error("Payment creation failed:", error.errors);
241
+ }
242
+ throw error;
243
+ }
244
+ }
245
+ ```
246
+
247
+ **List Payments:**
248
+
249
+ ```javascript
250
+ async function listPayments(locationId, beginTime, endTime) {
251
+ try {
252
+ const response = await client.payments.list({
253
+ locationId: locationId,
254
+ beginTime: beginTime,
255
+ endTime: endTime,
256
+ sortOrder: "DESC",
257
+ limit: 100,
258
+ });
259
+
260
+ return response.payments;
261
+ } catch (error) {
262
+ if (error instanceof SquareError) {
263
+ console.error("Error listing payments:", error.errors);
264
+ }
265
+ throw error;
266
+ }
267
+ }
268
+ ```
269
+
270
+ **Get Payment:**
271
+
272
+ ```javascript
273
+ async function getPayment(paymentId) {
274
+ try {
275
+ const response = await client.payments.retrieve(paymentId);
276
+ return response.payment;
277
+ } catch (error) {
278
+ if (error instanceof SquareError) {
279
+ console.error("Error retrieving payment:", error.errors);
280
+ }
281
+ throw error;
282
+ }
283
+ }
284
+ ```
285
+
286
+ **Complete Payment (for delayed capture):**
287
+
288
+ ```javascript
289
+ async function completePayment(paymentId) {
290
+ try {
291
+ const response = await client.payments.complete(paymentId);
292
+ return response.payment;
293
+ } catch (error) {
294
+ if (error instanceof SquareError) {
295
+ console.error("Error completing payment:", error.errors);
296
+ }
297
+ throw error;
298
+ }
299
+ }
300
+ ```
301
+
302
+ **Cancel Payment:**
303
+
304
+ ```javascript
305
+ async function cancelPayment(paymentId) {
306
+ try {
307
+ const response = await client.payments.cancel(paymentId);
308
+ return response.payment;
309
+ } catch (error) {
310
+ if (error instanceof SquareError) {
311
+ console.error("Error canceling payment:", error.errors);
312
+ }
313
+ throw error;
314
+ }
315
+ }
316
+ ```
317
+
318
+ ### Refunds API
319
+
320
+ Manage payment refunds.
321
+
322
+ **Create Refund (Minimal):**
323
+
324
+ ```javascript
325
+ import { randomUUID } from 'crypto';
326
+
327
+ async function createRefund(paymentId, amountMoney, currency) {
328
+ try {
329
+ const response = await client.refunds.create({
330
+ idempotencyKey: randomUUID(),
331
+ paymentId: paymentId,
332
+ amountMoney: {
333
+ amount: BigInt(amountMoney),
334
+ currency: currency || "USD",
335
+ },
336
+ });
337
+
338
+ return response.refund;
339
+ } catch (error) {
340
+ if (error instanceof SquareError) {
341
+ console.error("Refund error:", error.errors);
342
+ }
343
+ throw error;
344
+ }
345
+ }
346
+ ```
347
+
348
+ **Create Refund (Advanced):**
349
+
350
+ ```javascript
351
+ import { randomUUID } from 'crypto';
352
+
353
+ async function createAdvancedRefund(refundData) {
354
+ try {
355
+ const response = await client.refunds.create({
356
+ idempotencyKey: randomUUID(),
357
+ paymentId: refundData.paymentId,
358
+ amountMoney: {
359
+ amount: BigInt(refundData.amount),
360
+ currency: refundData.currency || "USD",
361
+ },
362
+ reason: refundData.reason,
363
+ locationId: refundData.locationId,
364
+ });
365
+
366
+ return response.refund;
367
+ } catch (error) {
368
+ if (error instanceof SquareError) {
369
+ console.error("Refund creation failed:", error.errors);
370
+ }
371
+ throw error;
372
+ }
373
+ }
374
+ ```
375
+
376
+ **Get Refund:**
377
+
378
+ ```javascript
379
+ async function getRefund(refundId) {
380
+ try {
381
+ const response = await client.refunds.retrieve(refundId);
382
+ return response.refund;
383
+ } catch (error) {
384
+ if (error instanceof SquareError) {
385
+ console.error("Error retrieving refund:", error.errors);
386
+ }
387
+ throw error;
388
+ }
389
+ }
390
+ ```
391
+
392
+ **List Refunds:**
393
+
394
+ ```javascript
395
+ async function listRefunds(locationId, beginTime, endTime) {
396
+ try {
397
+ const response = await client.refunds.list({
398
+ locationId: locationId,
399
+ beginTime: beginTime,
400
+ endTime: endTime,
401
+ sortOrder: "DESC",
402
+ });
403
+
404
+ return response.refunds;
405
+ } catch (error) {
406
+ if (error instanceof SquareError) {
407
+ console.error("Error listing refunds:", error.errors);
408
+ }
409
+ throw error;
410
+ }
411
+ }
412
+ ```
413
+
414
+ ### Orders API
415
+
416
+ Create and manage orders.
417
+
418
+ **Create Order (Minimal):**
419
+
420
+ ```javascript
421
+ import { randomUUID } from 'crypto';
422
+
423
+ async function createOrder(locationId) {
424
+ try {
425
+ const response = await client.orders.create({
426
+ idempotencyKey: randomUUID(),
427
+ order: {
428
+ locationId: locationId,
429
+ lineItems: [
430
+ {
431
+ name: "Item Name",
432
+ quantity: "1",
433
+ basePriceMoney: {
434
+ amount: BigInt(1000),
435
+ currency: "USD",
436
+ },
437
+ },
438
+ ],
439
+ },
440
+ });
441
+
442
+ return response.order;
443
+ } catch (error) {
444
+ if (error instanceof SquareError) {
445
+ console.error("Order creation error:", error.errors);
446
+ }
447
+ throw error;
448
+ }
449
+ }
450
+ ```
451
+
452
+ **Create Order (Advanced):**
453
+
454
+ ```javascript
455
+ import { randomUUID } from 'crypto';
456
+
457
+ async function createAdvancedOrder(orderData) {
458
+ try {
459
+ const response = await client.orders.create({
460
+ idempotencyKey: randomUUID(),
461
+ order: {
462
+ locationId: orderData.locationId,
463
+ referenceId: orderData.referenceId,
464
+ customerId: orderData.customerId,
465
+ lineItems: orderData.lineItems.map(item => ({
466
+ name: item.name,
467
+ quantity: item.quantity.toString(),
468
+ basePriceMoney: {
469
+ amount: BigInt(item.price),
470
+ currency: item.currency || "USD",
471
+ },
472
+ note: item.note,
473
+ })),
474
+ taxes: [
475
+ {
476
+ name: "Sales Tax",
477
+ percentage: "8.5",
478
+ scope: "ORDER",
479
+ },
480
+ ],
481
+ discounts: orderData.discounts?.map(discount => ({
482
+ name: discount.name,
483
+ percentage: discount.percentage,
484
+ scope: "ORDER",
485
+ })) || [],
486
+ },
487
+ });
488
+
489
+ return response.order;
490
+ } catch (error) {
491
+ if (error instanceof SquareError) {
492
+ console.error("Order creation failed:", error.errors);
493
+ }
494
+ throw error;
495
+ }
496
+ }
497
+ ```
498
+
499
+ **Retrieve Order:**
500
+
501
+ ```javascript
502
+ async function retrieveOrder(orderId) {
503
+ try {
504
+ const response = await client.orders.retrieve(orderId);
505
+ return response.order;
506
+ } catch (error) {
507
+ if (error instanceof SquareError) {
508
+ console.error("Error retrieving order:", error.errors);
509
+ }
510
+ throw error;
511
+ }
512
+ }
513
+ ```
514
+
515
+ **Update Order:**
516
+
517
+ ```javascript
518
+ async function updateOrder(orderId, updates) {
519
+ try {
520
+ const response = await client.orders.update(orderId, {
521
+ order: updates,
522
+ });
523
+
524
+ return response.order;
525
+ } catch (error) {
526
+ if (error instanceof SquareError) {
527
+ console.error("Error updating order:", error.errors);
528
+ }
529
+ throw error;
530
+ }
531
+ }
532
+ ```
533
+
534
+ **Search Orders:**
535
+
536
+ ```javascript
537
+ async function searchOrders(locationIds, query) {
538
+ try {
539
+ const response = await client.orders.search({
540
+ locationIds: locationIds,
541
+ query: {
542
+ filter: {
543
+ stateFilter: {
544
+ states: ["OPEN", "COMPLETED"],
545
+ },
546
+ dateTimeFilter: query.dateTimeFilter,
547
+ customerFilter: query.customerId ? {
548
+ customerIds: [query.customerId],
549
+ } : undefined,
550
+ },
551
+ sort: {
552
+ sortField: "CREATED_AT",
553
+ sortOrder: "DESC",
554
+ },
555
+ },
556
+ limit: query.limit || 100,
557
+ });
558
+
559
+ return response.orders;
560
+ } catch (error) {
561
+ if (error instanceof SquareError) {
562
+ console.error("Error searching orders:", error.errors);
563
+ }
564
+ throw error;
565
+ }
566
+ }
567
+ ```
568
+
569
+ ### Customers API
570
+
571
+ Manage customer profiles.
572
+
573
+ **Create Customer (Minimal):**
574
+
575
+ ```javascript
576
+ import { randomUUID } from 'crypto';
577
+
578
+ async function createCustomer(emailAddress, givenName, familyName) {
579
+ try {
580
+ const response = await client.customers.create({
581
+ idempotencyKey: randomUUID(),
582
+ emailAddress: emailAddress,
583
+ givenName: givenName,
584
+ familyName: familyName,
585
+ });
586
+
587
+ return response.customer;
588
+ } catch (error) {
589
+ if (error instanceof SquareError) {
590
+ console.error("Customer creation error:", error.errors);
591
+ }
592
+ throw error;
593
+ }
594
+ }
595
+ ```
596
+
597
+ **Create Customer (Advanced):**
598
+
599
+ ```javascript
600
+ import { randomUUID } from 'crypto';
601
+
602
+ async function createAdvancedCustomer(customerData) {
603
+ try {
604
+ const response = await client.customers.create({
605
+ idempotencyKey: randomUUID(),
606
+ givenName: customerData.givenName,
607
+ familyName: customerData.familyName,
608
+ emailAddress: customerData.emailAddress,
609
+ phoneNumber: customerData.phoneNumber,
610
+ address: {
611
+ addressLine1: customerData.addressLine1,
612
+ addressLine2: customerData.addressLine2,
613
+ locality: customerData.city,
614
+ administrativeDistrictLevel1: customerData.state,
615
+ postalCode: customerData.postalCode,
616
+ country: customerData.country || "US",
617
+ },
618
+ referenceId: customerData.referenceId,
619
+ note: customerData.note,
620
+ birthday: customerData.birthday,
621
+ companyName: customerData.companyName,
622
+ });
623
+
624
+ return response.customer;
625
+ } catch (error) {
626
+ if (error instanceof SquareError) {
627
+ console.error("Customer creation failed:", error.errors);
628
+ }
629
+ throw error;
630
+ }
631
+ }
632
+ ```
633
+
634
+ **List Customers:**
635
+
636
+ ```javascript
637
+ async function listCustomers(cursor = null, limit = 100) {
638
+ try {
639
+ const response = await client.customers.list({
640
+ cursor: cursor,
641
+ limit: limit,
642
+ sortField: "CREATED_AT",
643
+ sortOrder: "DESC",
644
+ });
645
+
646
+ return {
647
+ customers: response.customers,
648
+ cursor: response.cursor,
649
+ };
650
+ } catch (error) {
651
+ if (error instanceof SquareError) {
652
+ console.error("Error listing customers:", error.errors);
653
+ }
654
+ throw error;
655
+ }
656
+ }
657
+ ```
658
+
659
+ **Retrieve Customer:**
660
+
661
+ ```javascript
662
+ async function retrieveCustomer(customerId) {
663
+ try {
664
+ const response = await client.customers.retrieve(customerId);
665
+ return response.customer;
666
+ } catch (error) {
667
+ if (error instanceof SquareError) {
668
+ console.error("Error retrieving customer:", error.errors);
669
+ }
670
+ throw error;
671
+ }
672
+ }
673
+ ```
674
+
675
+ **Update Customer:**
676
+
677
+ ```javascript
678
+ async function updateCustomer(customerId, updates) {
679
+ try {
680
+ const response = await client.customers.update(customerId, updates);
681
+ return response.customer;
682
+ } catch (error) {
683
+ if (error instanceof SquareError) {
684
+ console.error("Error updating customer:", error.errors);
685
+ }
686
+ throw error;
687
+ }
688
+ }
689
+ ```
690
+
691
+ **Delete Customer:**
692
+
693
+ ```javascript
694
+ async function deleteCustomer(customerId) {
695
+ try {
696
+ const response = await client.customers.delete(customerId);
697
+ return response;
698
+ } catch (error) {
699
+ if (error instanceof SquareError) {
700
+ console.error("Error deleting customer:", error.errors);
701
+ }
702
+ throw error;
703
+ }
704
+ }
705
+ ```
706
+
707
+ **Search Customers:**
708
+
709
+ ```javascript
710
+ async function searchCustomers(query) {
711
+ try {
712
+ const response = await client.customers.search({
713
+ query: {
714
+ filter: {
715
+ emailAddress: query.email ? {
716
+ exact: query.email,
717
+ } : undefined,
718
+ phoneNumber: query.phone ? {
719
+ exact: query.phone,
720
+ } : undefined,
721
+ createdAt: query.createdAt,
722
+ },
723
+ },
724
+ limit: query.limit || 100,
725
+ });
726
+
727
+ return response.customers;
728
+ } catch (error) {
729
+ if (error instanceof SquareError) {
730
+ console.error("Error searching customers:", error.errors);
731
+ }
732
+ throw error;
733
+ }
734
+ }
735
+ ```
736
+
737
+ ### Catalog API
738
+
739
+ Manage items, categories, taxes, and modifiers.
740
+
741
+ **Create Catalog Item (Minimal):**
742
+
743
+ ```javascript
744
+ import { randomUUID } from 'crypto';
745
+
746
+ async function createCatalogItem(name, price) {
747
+ try {
748
+ const response = await client.catalog.upsertCatalogObject({
749
+ idempotencyKey: randomUUID(),
750
+ object: {
751
+ type: "ITEM",
752
+ id: `#${name.replace(/\s/g, '_')}`,
753
+ itemData: {
754
+ name: name,
755
+ variations: [
756
+ {
757
+ type: "ITEM_VARIATION",
758
+ id: `#${name.replace(/\s/g, '_')}_variation`,
759
+ itemVariationData: {
760
+ name: "Regular",
761
+ pricingType: "FIXED_PRICING",
762
+ priceMoney: {
763
+ amount: BigInt(price),
764
+ currency: "USD",
765
+ },
766
+ },
767
+ },
768
+ ],
769
+ },
770
+ },
771
+ });
772
+
773
+ return response.catalogObject;
774
+ } catch (error) {
775
+ if (error instanceof SquareError) {
776
+ console.error("Catalog item creation error:", error.errors);
777
+ }
778
+ throw error;
779
+ }
780
+ }
781
+ ```
782
+
783
+ **Create Catalog Item (Advanced):**
784
+
785
+ ```javascript
786
+ import { randomUUID } from 'crypto';
787
+
788
+ async function createAdvancedCatalogItem(itemData) {
789
+ try {
790
+ const response = await client.catalog.upsertCatalogObject({
791
+ idempotencyKey: randomUUID(),
792
+ object: {
793
+ type: "ITEM",
794
+ id: `#${itemData.name.replace(/\s/g, '_')}`,
795
+ itemData: {
796
+ name: itemData.name,
797
+ description: itemData.description,
798
+ categoryId: itemData.categoryId,
799
+ taxIds: itemData.taxIds,
800
+ variations: itemData.variations.map((variation, index) => ({
801
+ type: "ITEM_VARIATION",
802
+ id: `#${itemData.name.replace(/\s/g, '_')}_var_${index}`,
803
+ itemVariationData: {
804
+ name: variation.name,
805
+ sku: variation.sku,
806
+ pricingType: "FIXED_PRICING",
807
+ priceMoney: {
808
+ amount: BigInt(variation.price),
809
+ currency: variation.currency || "USD",
810
+ },
811
+ trackInventory: variation.trackInventory || false,
812
+ },
813
+ })),
814
+ },
815
+ },
816
+ });
817
+
818
+ return response.catalogObject;
819
+ } catch (error) {
820
+ if (error instanceof SquareError) {
821
+ console.error("Catalog item creation failed:", error.errors);
822
+ }
823
+ throw error;
824
+ }
825
+ }
826
+ ```
827
+
828
+ **List Catalog:**
829
+
830
+ ```javascript
831
+ async function listCatalog(types = ["ITEM"], cursor = null) {
832
+ try {
833
+ const response = await client.catalog.list({
834
+ cursor: cursor,
835
+ types: types,
836
+ });
837
+
838
+ return {
839
+ objects: response.objects,
840
+ cursor: response.cursor,
841
+ };
842
+ } catch (error) {
843
+ if (error instanceof SquareError) {
844
+ console.error("Error listing catalog:", error.errors);
845
+ }
846
+ throw error;
847
+ }
848
+ }
849
+ ```
850
+
851
+ **Retrieve Catalog Object:**
852
+
853
+ ```javascript
854
+ async function retrieveCatalogObject(objectId) {
855
+ try {
856
+ const response = await client.catalog.retrieve(objectId, {
857
+ includeRelatedObjects: true,
858
+ });
859
+
860
+ return response.object;
861
+ } catch (error) {
862
+ if (error instanceof SquareError) {
863
+ console.error("Error retrieving catalog object:", error.errors);
864
+ }
865
+ throw error;
866
+ }
867
+ }
868
+ ```
869
+
870
+ **Search Catalog Items:**
871
+
872
+ ```javascript
873
+ async function searchCatalogItems(query) {
874
+ try {
875
+ const response = await client.catalog.searchCatalogItems({
876
+ textFilter: query.text,
877
+ categoryIds: query.categoryIds,
878
+ stockLevels: query.stockLevels,
879
+ enabledLocationIds: query.locationIds,
880
+ limit: query.limit || 100,
881
+ });
882
+
883
+ return response.items;
884
+ } catch (error) {
885
+ if (error instanceof SquareError) {
886
+ console.error("Error searching catalog:", error.errors);
887
+ }
888
+ throw error;
889
+ }
890
+ }
891
+ ```
892
+
893
+ **Delete Catalog Object:**
894
+
895
+ ```javascript
896
+ async function deleteCatalogObject(objectId) {
897
+ try {
898
+ const response = await client.catalog.deleteCatalogObject(objectId);
899
+ return response;
900
+ } catch (error) {
901
+ if (error instanceof SquareError) {
902
+ console.error("Error deleting catalog object:", error.errors);
903
+ }
904
+ throw error;
905
+ }
906
+ }
907
+ ```
908
+
909
+ **Batch Upsert Catalog Objects:**
910
+
911
+ ```javascript
912
+ import { randomUUID } from 'crypto';
913
+
914
+ async function batchUpsertCatalogObjects(objects) {
915
+ try {
916
+ const response = await client.catalog.batchUpsertCatalogObjects({
917
+ idempotencyKey: randomUUID(),
918
+ batches: [
919
+ {
920
+ objects: objects,
921
+ },
922
+ ],
923
+ });
924
+
925
+ return response.objects;
926
+ } catch (error) {
927
+ if (error instanceof SquareError) {
928
+ console.error("Batch upsert error:", error.errors);
929
+ }
930
+ throw error;
931
+ }
932
+ }
933
+ ```
934
+
935
+ ### Inventory API
936
+
937
+ Track and manage inventory.
938
+
939
+ **Retrieve Inventory Count:**
940
+
941
+ ```javascript
942
+ async function retrieveInventoryCount(catalogObjectId, locationIds) {
943
+ try {
944
+ const response = await client.inventory.retrieveInventoryCount(
945
+ catalogObjectId,
946
+ {
947
+ locationIds: locationIds.join(','),
948
+ }
949
+ );
950
+
951
+ return response.counts;
952
+ } catch (error) {
953
+ if (error instanceof SquareError) {
954
+ console.error("Error retrieving inventory:", error.errors);
955
+ }
956
+ throw error;
957
+ }
958
+ }
959
+ ```
960
+
961
+ **Batch Retrieve Inventory Counts:**
962
+
963
+ ```javascript
964
+ async function batchRetrieveInventoryCounts(catalogObjectIds, locationIds) {
965
+ try {
966
+ const response = await client.inventory.batchRetrieveInventoryCounts({
967
+ catalogObjectIds: catalogObjectIds,
968
+ locationIds: locationIds,
969
+ });
970
+
971
+ return response.counts;
972
+ } catch (error) {
973
+ if (error instanceof SquareError) {
974
+ console.error("Error retrieving inventory counts:", error.errors);
975
+ }
976
+ throw error;
977
+ }
978
+ }
979
+ ```
980
+
981
+ **Adjust Inventory:**
982
+
983
+ ```javascript
984
+ import { randomUUID } from 'crypto';
985
+
986
+ async function adjustInventory(catalogObjectId, locationId, adjustment) {
987
+ try {
988
+ const response = await client.inventory.batchChangeInventory({
989
+ idempotencyKey: randomUUID(),
990
+ changes: [
991
+ {
992
+ type: "ADJUSTMENT",
993
+ adjustment: {
994
+ catalogObjectId: catalogObjectId,
995
+ locationId: locationId,
996
+ quantity: adjustment.quantity.toString(),
997
+ fromState: "IN_STOCK",
998
+ toState: "IN_STOCK",
999
+ occurredAt: new Date().toISOString(),
1000
+ },
1001
+ },
1002
+ ],
1003
+ });
1004
+
1005
+ return response.counts;
1006
+ } catch (error) {
1007
+ if (error instanceof SquareError) {
1008
+ console.error("Error adjusting inventory:", error.errors);
1009
+ }
1010
+ throw error;
1011
+ }
1012
+ }
1013
+ ```
1014
+
1015
+ ### Invoices API
1016
+
1017
+ Create and manage invoices.
1018
+
1019
+ **Create Invoice (Minimal):**
1020
+
1021
+ ```javascript
1022
+ import { randomUUID } from 'crypto';
1023
+
1024
+ async function createInvoice(locationId, customerId, orderId) {
1025
+ try {
1026
+ const response = await client.invoices.create({
1027
+ invoice: {
1028
+ locationId: locationId,
1029
+ orderId: orderId,
1030
+ primaryRecipient: {
1031
+ customerId: customerId,
1032
+ },
1033
+ paymentRequests: [
1034
+ {
1035
+ requestType: "BALANCE",
1036
+ dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
1037
+ .toISOString()
1038
+ .split('T')[0],
1039
+ },
1040
+ ],
1041
+ },
1042
+ idempotencyKey: randomUUID(),
1043
+ });
1044
+
1045
+ return response.invoice;
1046
+ } catch (error) {
1047
+ if (error instanceof SquareError) {
1048
+ console.error("Invoice creation error:", error.errors);
1049
+ }
1050
+ throw error;
1051
+ }
1052
+ }
1053
+ ```
1054
+
1055
+ **Create Invoice (Advanced):**
1056
+
1057
+ ```javascript
1058
+ import { randomUUID } from 'crypto';
1059
+
1060
+ async function createAdvancedInvoice(invoiceData) {
1061
+ try {
1062
+ const response = await client.invoices.create({
1063
+ invoice: {
1064
+ locationId: invoiceData.locationId,
1065
+ orderId: invoiceData.orderId,
1066
+ primaryRecipient: {
1067
+ customerId: invoiceData.customerId,
1068
+ givenName: invoiceData.givenName,
1069
+ familyName: invoiceData.familyName,
1070
+ emailAddress: invoiceData.emailAddress,
1071
+ },
1072
+ paymentRequests: [
1073
+ {
1074
+ requestType: "BALANCE",
1075
+ dueDate: invoiceData.dueDate,
1076
+ fixedAmountRequestedMoney: invoiceData.fixedAmount ? {
1077
+ amount: BigInt(invoiceData.fixedAmount),
1078
+ currency: invoiceData.currency || "USD",
1079
+ } : undefined,
1080
+ reminders: [
1081
+ {
1082
+ relativeScheduledDays: -1,
1083
+ message: "Payment reminder",
1084
+ },
1085
+ ],
1086
+ },
1087
+ ],
1088
+ deliveryMethod: "EMAIL",
1089
+ invoiceNumber: invoiceData.invoiceNumber,
1090
+ title: invoiceData.title,
1091
+ description: invoiceData.description,
1092
+ },
1093
+ idempotencyKey: randomUUID(),
1094
+ });
1095
+
1096
+ return response.invoice;
1097
+ } catch (error) {
1098
+ if (error instanceof SquareError) {
1099
+ console.error("Invoice creation failed:", error.errors);
1100
+ }
1101
+ throw error;
1102
+ }
1103
+ }
1104
+ ```
1105
+
1106
+ **Publish Invoice:**
1107
+
1108
+ ```javascript
1109
+ async function publishInvoice(invoiceId) {
1110
+ try {
1111
+ const response = await client.invoices.publish(invoiceId, {
1112
+ version: 0,
1113
+ });
1114
+
1115
+ return response.invoice;
1116
+ } catch (error) {
1117
+ if (error instanceof SquareError) {
1118
+ console.error("Error publishing invoice:", error.errors);
1119
+ }
1120
+ throw error;
1121
+ }
1122
+ }
1123
+ ```
1124
+
1125
+ **Get Invoice:**
1126
+
1127
+ ```javascript
1128
+ async function getInvoice(invoiceId) {
1129
+ try {
1130
+ const response = await client.invoices.retrieve(invoiceId);
1131
+ return response.invoice;
1132
+ } catch (error) {
1133
+ if (error instanceof SquareError) {
1134
+ console.error("Error retrieving invoice:", error.errors);
1135
+ }
1136
+ throw error;
1137
+ }
1138
+ }
1139
+ ```
1140
+
1141
+ **Search Invoices:**
1142
+
1143
+ ```javascript
1144
+ async function searchInvoices(locationIds, query) {
1145
+ try {
1146
+ const response = await client.invoices.search({
1147
+ query: {
1148
+ locationIds: locationIds,
1149
+ filter: {
1150
+ customerIds: query.customerIds,
1151
+ stateFilter: query.states,
1152
+ },
1153
+ sort: {
1154
+ field: "INVOICE_SORT_DATE",
1155
+ order: "DESC",
1156
+ },
1157
+ },
1158
+ limit: query.limit || 100,
1159
+ });
1160
+
1161
+ return response.invoices;
1162
+ } catch (error) {
1163
+ if (error instanceof SquareError) {
1164
+ console.error("Error searching invoices:", error.errors);
1165
+ }
1166
+ throw error;
1167
+ }
1168
+ }
1169
+ ```
1170
+
1171
+ ### Subscriptions API
1172
+
1173
+ Manage recurring payments and subscriptions.
1174
+
1175
+ **Create Subscription (Minimal):**
1176
+
1177
+ ```javascript
1178
+ import { randomUUID } from 'crypto';
1179
+
1180
+ async function createSubscription(locationId, customerId, planId) {
1181
+ try {
1182
+ const response = await client.subscriptions.create({
1183
+ idempotencyKey: randomUUID(),
1184
+ locationId: locationId,
1185
+ planId: planId,
1186
+ customerId: customerId,
1187
+ });
1188
+
1189
+ return response.subscription;
1190
+ } catch (error) {
1191
+ if (error instanceof SquareError) {
1192
+ console.error("Subscription creation error:", error.errors);
1193
+ }
1194
+ throw error;
1195
+ }
1196
+ }
1197
+ ```
1198
+
1199
+ **Create Subscription (Advanced):**
1200
+
1201
+ ```javascript
1202
+ import { randomUUID } from 'crypto';
1203
+
1204
+ async function createAdvancedSubscription(subscriptionData) {
1205
+ try {
1206
+ const response = await client.subscriptions.create({
1207
+ idempotencyKey: randomUUID(),
1208
+ locationId: subscriptionData.locationId,
1209
+ planId: subscriptionData.planId,
1210
+ customerId: subscriptionData.customerId,
1211
+ startDate: subscriptionData.startDate,
1212
+ taxPercentage: subscriptionData.taxPercentage,
1213
+ priceOverrideMoney: subscriptionData.priceOverride ? {
1214
+ amount: BigInt(subscriptionData.priceOverride),
1215
+ currency: subscriptionData.currency || "USD",
1216
+ } : undefined,
1217
+ cardId: subscriptionData.cardId,
1218
+ });
1219
+
1220
+ return response.subscription;
1221
+ } catch (error) {
1222
+ if (error instanceof SquareError) {
1223
+ console.error("Subscription creation failed:", error.errors);
1224
+ }
1225
+ throw error;
1226
+ }
1227
+ }
1228
+ ```
1229
+
1230
+ **Retrieve Subscription:**
1231
+
1232
+ ```javascript
1233
+ async function retrieveSubscription(subscriptionId) {
1234
+ try {
1235
+ const response = await client.subscriptions.retrieve(subscriptionId, {
1236
+ include: "actions",
1237
+ });
1238
+
1239
+ return response.subscription;
1240
+ } catch (error) {
1241
+ if (error instanceof SquareError) {
1242
+ console.error("Error retrieving subscription:", error.errors);
1243
+ }
1244
+ throw error;
1245
+ }
1246
+ }
1247
+ ```
1248
+
1249
+ **Cancel Subscription:**
1250
+
1251
+ ```javascript
1252
+ async function cancelSubscription(subscriptionId) {
1253
+ try {
1254
+ const response = await client.subscriptions.cancel(subscriptionId);
1255
+ return response.subscription;
1256
+ } catch (error) {
1257
+ if (error instanceof SquareError) {
1258
+ console.error("Error canceling subscription:", error.errors);
1259
+ }
1260
+ throw error;
1261
+ }
1262
+ }
1263
+ ```
1264
+
1265
+ **Search Subscriptions:**
1266
+
1267
+ ```javascript
1268
+ async function searchSubscriptions(query) {
1269
+ try {
1270
+ const response = await client.subscriptions.search({
1271
+ query: {
1272
+ filter: {
1273
+ customerIds: query.customerIds,
1274
+ locationIds: query.locationIds,
1275
+ },
1276
+ },
1277
+ limit: query.limit || 100,
1278
+ });
1279
+
1280
+ return response.subscriptions;
1281
+ } catch (error) {
1282
+ if (error instanceof SquareError) {
1283
+ console.error("Error searching subscriptions:", error.errors);
1284
+ }
1285
+ throw error;
1286
+ }
1287
+ }
1288
+ ```
1289
+
1290
+ ### Checkout API
1291
+
1292
+ Create hosted checkout pages.
1293
+
1294
+ **Create Checkout (Minimal):**
1295
+
1296
+ ```javascript
1297
+ import { randomUUID } from 'crypto';
1298
+
1299
+ async function createCheckout(locationId, orderId) {
1300
+ try {
1301
+ const response = await client.checkout.create(locationId, {
1302
+ idempotencyKey: randomUUID(),
1303
+ order: {
1304
+ orderId: orderId,
1305
+ },
1306
+ });
1307
+
1308
+ return response.checkout.checkoutPageUrl;
1309
+ } catch (error) {
1310
+ if (error instanceof SquareError) {
1311
+ console.error("Checkout creation error:", error.errors);
1312
+ }
1313
+ throw error;
1314
+ }
1315
+ }
1316
+ ```
1317
+
1318
+ **Create Checkout (Advanced):**
1319
+
1320
+ ```javascript
1321
+ import { randomUUID } from 'crypto';
1322
+
1323
+ async function createAdvancedCheckout(locationId, checkoutData) {
1324
+ try {
1325
+ const response = await client.checkout.create(locationId, {
1326
+ idempotencyKey: randomUUID(),
1327
+ order: {
1328
+ orderId: checkoutData.orderId,
1329
+ locationId: locationId,
1330
+ },
1331
+ askForShippingAddress: checkoutData.askForShippingAddress || false,
1332
+ merchantSupportEmail: checkoutData.merchantEmail,
1333
+ prePopulateBuyerEmail: checkoutData.buyerEmail,
1334
+ redirectUrl: checkoutData.redirectUrl,
1335
+ additionalRecipients: checkoutData.additionalRecipients,
1336
+ });
1337
+
1338
+ return response.checkout;
1339
+ } catch (error) {
1340
+ if (error instanceof SquareError) {
1341
+ console.error("Checkout creation failed:", error.errors);
1342
+ }
1343
+ throw error;
1344
+ }
1345
+ }
1346
+ ```
1347
+
1348
+ ### Bookings API
1349
+
1350
+ Manage appointments and bookings.
1351
+
1352
+ **Create Booking (Minimal):**
1353
+
1354
+ ```javascript
1355
+ import { randomUUID } from 'crypto';
1356
+
1357
+ async function createBooking(locationId, customerId, startAt, serviceVariationId, teamMemberId) {
1358
+ try {
1359
+ const response = await client.bookings.create({
1360
+ idempotencyKey: randomUUID(),
1361
+ booking: {
1362
+ locationId: locationId,
1363
+ customerId: customerId,
1364
+ startAt: startAt,
1365
+ appointmentSegments: [
1366
+ {
1367
+ durationMinutes: 60,
1368
+ serviceVariationId: serviceVariationId,
1369
+ teamMemberId: teamMemberId,
1370
+ },
1371
+ ],
1372
+ },
1373
+ });
1374
+
1375
+ return response.booking;
1376
+ } catch (error) {
1377
+ if (error instanceof SquareError) {
1378
+ console.error("Booking creation error:", error.errors);
1379
+ }
1380
+ throw error;
1381
+ }
1382
+ }
1383
+ ```
1384
+
1385
+ **Create Booking (Advanced):**
1386
+
1387
+ ```javascript
1388
+ import { randomUUID } from 'crypto';
1389
+
1390
+ async function createAdvancedBooking(bookingData) {
1391
+ try {
1392
+ const response = await client.bookings.create({
1393
+ idempotencyKey: randomUUID(),
1394
+ booking: {
1395
+ locationId: bookingData.locationId,
1396
+ customerId: bookingData.customerId,
1397
+ customerNote: bookingData.customerNote,
1398
+ sellerNote: bookingData.sellerNote,
1399
+ startAt: bookingData.startAt,
1400
+ appointmentSegments: bookingData.appointmentSegments.map(segment => ({
1401
+ durationMinutes: segment.durationMinutes,
1402
+ serviceVariationId: segment.serviceVariationId,
1403
+ teamMemberId: segment.teamMemberId,
1404
+ })),
1405
+ },
1406
+ });
1407
+
1408
+ return response.booking;
1409
+ } catch (error) {
1410
+ if (error instanceof SquareError) {
1411
+ console.error("Booking creation failed:", error.errors);
1412
+ }
1413
+ throw error;
1414
+ }
1415
+ }
1416
+ ```
1417
+
1418
+ **List Bookings:**
1419
+
1420
+ ```javascript
1421
+ async function listBookings(locationId, startAtMin, startAtMax) {
1422
+ try {
1423
+ const response = await client.bookings.list({
1424
+ locationId: locationId,
1425
+ startAtMin: startAtMin,
1426
+ startAtMax: startAtMax,
1427
+ limit: 100,
1428
+ });
1429
+
1430
+ return response.bookings;
1431
+ } catch (error) {
1432
+ if (error instanceof SquareError) {
1433
+ console.error("Error listing bookings:", error.errors);
1434
+ }
1435
+ throw error;
1436
+ }
1437
+ }
1438
+ ```
1439
+
1440
+ **Retrieve Booking:**
1441
+
1442
+ ```javascript
1443
+ async function retrieveBooking(bookingId) {
1444
+ try {
1445
+ const response = await client.bookings.retrieve(bookingId);
1446
+ return response.booking;
1447
+ } catch (error) {
1448
+ if (error instanceof SquareError) {
1449
+ console.error("Error retrieving booking:", error.errors);
1450
+ }
1451
+ throw error;
1452
+ }
1453
+ }
1454
+ ```
1455
+
1456
+ **Cancel Booking:**
1457
+
1458
+ ```javascript
1459
+ async function cancelBooking(bookingId) {
1460
+ try {
1461
+ const response = await client.bookings.cancel(bookingId, {
1462
+ idempotencyKey: randomUUID(),
1463
+ });
1464
+
1465
+ return response.booking;
1466
+ } catch (error) {
1467
+ if (error instanceof SquareError) {
1468
+ console.error("Error canceling booking:", error.errors);
1469
+ }
1470
+ throw error;
1471
+ }
1472
+ }
1473
+ ```
1474
+
1475
+ ### Terminal API
1476
+
1477
+ Create checkouts for Square Terminal devices.
1478
+
1479
+ **Create Terminal Checkout:**
1480
+
1481
+ ```javascript
1482
+ import { randomUUID } from 'crypto';
1483
+
1484
+ async function createTerminalCheckout(deviceId, amountMoney, locationId) {
1485
+ try {
1486
+ const response = await client.terminal.createTerminalCheckout({
1487
+ idempotencyKey: randomUUID(),
1488
+ checkout: {
1489
+ amountMoney: {
1490
+ amount: BigInt(amountMoney),
1491
+ currency: "USD",
1492
+ },
1493
+ deviceOptions: {
1494
+ deviceId: deviceId,
1495
+ },
1496
+ },
1497
+ });
1498
+
1499
+ return response.checkout;
1500
+ } catch (error) {
1501
+ if (error instanceof SquareError) {
1502
+ console.error("Terminal checkout error:", error.errors);
1503
+ }
1504
+ throw error;
1505
+ }
1506
+ }
1507
+ ```
1508
+
1509
+ **Get Terminal Checkout:**
1510
+
1511
+ ```javascript
1512
+ async function getTerminalCheckout(checkoutId) {
1513
+ try {
1514
+ const response = await client.terminal.getTerminalCheckout(checkoutId);
1515
+ return response.checkout;
1516
+ } catch (error) {
1517
+ if (error instanceof SquareError) {
1518
+ console.error("Error retrieving terminal checkout:", error.errors);
1519
+ }
1520
+ throw error;
1521
+ }
1522
+ }
1523
+ ```
1524
+
1525
+ **Cancel Terminal Checkout:**
1526
+
1527
+ ```javascript
1528
+ async function cancelTerminalCheckout(checkoutId) {
1529
+ try {
1530
+ const response = await client.terminal.cancelTerminalCheckout(checkoutId);
1531
+ return response.checkout;
1532
+ } catch (error) {
1533
+ if (error instanceof SquareError) {
1534
+ console.error("Error canceling terminal checkout:", error.errors);
1535
+ }
1536
+ throw error;
1537
+ }
1538
+ }
1539
+ ```
1540
+
1541
+ ### Webhooks
1542
+
1543
+ Handle webhook notifications from Square.
1544
+
1545
+ **Create Webhook Subscription:**
1546
+
1547
+ ```javascript
1548
+ async function createWebhookSubscription(notificationUrl, eventTypes) {
1549
+ try {
1550
+ const response = await client.webhookSubscriptions.create({
1551
+ subscription: {
1552
+ name: "My Webhook",
1553
+ notificationUrl: notificationUrl,
1554
+ eventTypes: eventTypes,
1555
+ },
1556
+ });
1557
+
1558
+ return response.subscription;
1559
+ } catch (error) {
1560
+ if (error instanceof SquareError) {
1561
+ console.error("Webhook creation error:", error.errors);
1562
+ }
1563
+ throw error;
1564
+ }
1565
+ }
1566
+ ```
1567
+
1568
+ **List Webhook Subscriptions:**
1569
+
1570
+ ```javascript
1571
+ async function listWebhookSubscriptions() {
1572
+ try {
1573
+ const response = await client.webhookSubscriptions.list();
1574
+ return response.subscriptions;
1575
+ } catch (error) {
1576
+ if (error instanceof SquareError) {
1577
+ console.error("Error listing webhooks:", error.errors);
1578
+ }
1579
+ throw error;
1580
+ }
1581
+ }
1582
+ ```
1583
+
1584
+ **Verify Webhook Signature:**
1585
+
1586
+ ```javascript
1587
+ const crypto = require('crypto');
1588
+
1589
+ function verifyWebhookSignature(body, signature, signatureKey, notificationUrl) {
1590
+ const hmac = crypto.createHmac('sha256', signatureKey);
1591
+ hmac.update(notificationUrl + body);
1592
+ const hash = hmac.digest('base64');
1593
+
1594
+ return hash === signature;
1595
+ }
1596
+ ```
1597
+
1598
+ **Handle Webhook (Express):**
1599
+
1600
+ ```javascript
1601
+ const express = require('express');
1602
+ const app = express();
1603
+
1604
+ app.post('/webhooks/square', express.raw({ type: 'application/json' }), (req, res) => {
1605
+ const signature = req.headers['x-square-hmacsha256-signature'];
1606
+ const body = req.body.toString('utf8');
1607
+
1608
+ const isValid = verifyWebhookSignature(
1609
+ body,
1610
+ signature,
1611
+ process.env.SQUARE_WEBHOOK_SECRET,
1612
+ 'https://yourdomain.com/webhooks/square'
1613
+ );
1614
+
1615
+ if (!isValid) {
1616
+ return res.status(400).send('Invalid signature');
1617
+ }
1618
+
1619
+ const event = JSON.parse(body);
1620
+
1621
+ switch (event.type) {
1622
+ case 'payment.created':
1623
+ console.log('Payment created:', event.data.object.payment);
1624
+ break;
1625
+ case 'order.created':
1626
+ console.log('Order created:', event.data.object.order);
1627
+ break;
1628
+ case 'customer.created':
1629
+ console.log('Customer created:', event.data.object.customer);
1630
+ break;
1631
+ default:
1632
+ console.log('Unhandled event type:', event.type);
1633
+ }
1634
+
1635
+ res.status(200).send('OK');
1636
+ });
1637
+ ```
1638
+
1639
+ ### Common Webhook Events
1640
+
1641
+ ```javascript
1642
+ // Payment events
1643
+ "payment.created"
1644
+ "payment.updated"
1645
+
1646
+ // Order events
1647
+ "order.created"
1648
+ "order.updated"
1649
+ "order.fulfillment.updated"
1650
+
1651
+ // Customer events
1652
+ "customer.created"
1653
+ "customer.updated"
1654
+ "customer.deleted"
1655
+
1656
+ // Invoice events
1657
+ "invoice.created"
1658
+ "invoice.published"
1659
+ "invoice.payment_made"
1660
+
1661
+ // Subscription events
1662
+ "subscription.created"
1663
+ "subscription.started"
1664
+ "subscription.canceled"
1665
+
1666
+ // Booking events
1667
+ "booking.created"
1668
+ "booking.updated"
1669
+
1670
+ // Inventory events
1671
+ "inventory.count.updated"
1672
+
1673
+ // Catalog events
1674
+ "catalog.version.updated"
1675
+ ```
1676
+
1677
+ ### Pagination
1678
+
1679
+ Handle paginated results with cursor-based pagination.
1680
+
1681
+ ```javascript
1682
+ async function getAllCustomers() {
1683
+ const allCustomers = [];
1684
+ let cursor = null;
1685
+
1686
+ do {
1687
+ const response = await client.customers.list({
1688
+ cursor: cursor,
1689
+ limit: 100,
1690
+ });
1691
+
1692
+ if (response.customers) {
1693
+ allCustomers.push(...response.customers);
1694
+ }
1695
+
1696
+ cursor = response.cursor;
1697
+ } while (cursor);
1698
+
1699
+ return allCustomers;
1700
+ }
1701
+ ```
1702
+
1703
+ ### Idempotency
1704
+
1705
+ Use idempotency keys to prevent duplicate operations.
1706
+
1707
+ ```javascript
1708
+ import { randomUUID } from 'crypto';
1709
+
1710
+ async function idempotentPayment(sourceId, amount, locationId) {
1711
+ const idempotencyKey = randomUUID();
1712
+
1713
+ try {
1714
+ const response = await client.payments.create({
1715
+ sourceId: sourceId,
1716
+ idempotencyKey: idempotencyKey,
1717
+ amountMoney: {
1718
+ amount: BigInt(amount),
1719
+ currency: "USD",
1720
+ },
1721
+ locationId: locationId,
1722
+ });
1723
+
1724
+ return response.payment;
1725
+ } catch (error) {
1726
+ if (error instanceof SquareError) {
1727
+ console.error("Payment failed:", error.errors);
1728
+ }
1729
+ throw error;
1730
+ }
1731
+ }
1732
+ ```
1733
+
1734
+ ### Error Categories
1735
+
1736
+ ```javascript
1737
+ // Common Square error categories:
1738
+ // - API_ERROR: API-level error
1739
+ // - AUTHENTICATION_ERROR: Authentication failure
1740
+ // - INVALID_REQUEST_ERROR: Invalid request parameters
1741
+ // - RATE_LIMIT_ERROR: Too many requests
1742
+ // - PAYMENT_METHOD_ERROR: Payment method issue
1743
+ // - REFUND_ERROR: Refund processing error
1744
+ ```
1745
+
1746
+ ### Testing with Sandbox
1747
+
1748
+ ```javascript
1749
+ const { SquareClient, SquareEnvironment } = require("square");
1750
+
1751
+ // Always use sandbox for development
1752
+ const client = new SquareClient({
1753
+ token: process.env.SQUARE_SANDBOX_TOKEN,
1754
+ environment: SquareEnvironment.Sandbox,
1755
+ });
1756
+
1757
+ // Test payment source IDs for sandbox:
1758
+ // cnon:card-nonce-ok - successful charge
1759
+ // cnon:card-nonce-declined - declined charge
1760
+ // cnon:card-nonce-dishonoured - card verification failed
1761
+ ```
1762
+
1763
+ ### Complete Example: Process Payment with Customer
1764
+
1765
+ ```javascript
1766
+ const { SquareClient, SquareEnvironment, SquareError } = require("square");
1767
+ const { randomUUID } = require('crypto');
1768
+
1769
+ const client = new SquareClient({
1770
+ token: process.env.SQUARE_ACCESS_TOKEN,
1771
+ environment: SquareEnvironment.Sandbox,
1772
+ });
1773
+
1774
+ async function processPaymentWithCustomer(paymentDetails) {
1775
+ try {
1776
+ // 1. Create or retrieve customer
1777
+ let customer;
1778
+ try {
1779
+ const customerResponse = await client.customers.create({
1780
+ idempotencyKey: randomUUID(),
1781
+ givenName: paymentDetails.givenName,
1782
+ familyName: paymentDetails.familyName,
1783
+ emailAddress: paymentDetails.emailAddress,
1784
+ });
1785
+ customer = customerResponse.customer;
1786
+ } catch (error) {
1787
+ console.log("Customer already exists, using existing");
1788
+ }
1789
+
1790
+ // 2. Create order
1791
+ const orderResponse = await client.orders.create({
1792
+ idempotencyKey: randomUUID(),
1793
+ order: {
1794
+ locationId: paymentDetails.locationId,
1795
+ customerId: customer.id,
1796
+ lineItems: [
1797
+ {
1798
+ name: paymentDetails.itemName,
1799
+ quantity: "1",
1800
+ basePriceMoney: {
1801
+ amount: BigInt(paymentDetails.amount),
1802
+ currency: "USD",
1803
+ },
1804
+ },
1805
+ ],
1806
+ },
1807
+ });
1808
+
1809
+ // 3. Create payment
1810
+ const paymentResponse = await client.payments.create({
1811
+ sourceId: paymentDetails.sourceId,
1812
+ idempotencyKey: randomUUID(),
1813
+ amountMoney: {
1814
+ amount: BigInt(paymentDetails.amount),
1815
+ currency: "USD",
1816
+ },
1817
+ orderId: orderResponse.order.id,
1818
+ customerId: customer.id,
1819
+ locationId: paymentDetails.locationId,
1820
+ autocomplete: true,
1821
+ });
1822
+
1823
+ return {
1824
+ payment: paymentResponse.payment,
1825
+ order: orderResponse.order,
1826
+ customer: customer,
1827
+ };
1828
+ } catch (error) {
1829
+ if (error instanceof SquareError) {
1830
+ console.error("Transaction failed:");
1831
+ error.errors.forEach(e => {
1832
+ console.log(` ${e.category}: ${e.code}`);
1833
+ console.log(` ${e.detail}`);
1834
+ });
1835
+ }
1836
+ throw error;
1837
+ }
1838
+ }
1839
+
1840
+ // Usage
1841
+ processPaymentWithCustomer({
1842
+ sourceId: "cnon:card-nonce-ok",
1843
+ amount: 1000,
1844
+ locationId: "L88917AVBK2S5",
1845
+ givenName: "John",
1846
+ familyName: "Doe",
1847
+ emailAddress: "john.doe@example.com",
1848
+ itemName: "Premium Service",
1849
+ }).then(result => {
1850
+ console.log("Payment successful!");
1851
+ console.log("Payment ID:", result.payment.id);
1852
+ console.log("Order ID:", result.order.id);
1853
+ console.log("Customer ID:", result.customer.id);
1854
+ });
1855
+ ```