-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathClient.ts
826 lines (793 loc) · 33.9 KB
/
Client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
/**
* This file was auto-generated by Fern from our API Definition.
*/
import * as environments from "../../../../environments";
import * as core from "../../../../core";
import * as Square from "../../../index";
import * as serializers from "../../../../serialization/index";
import urlJoin from "url-join";
import * as errors from "../../../../errors/index";
import { CustomAttributeDefinitions } from "../resources/customAttributeDefinitions/client/Client";
import { CustomAttributes } from "../resources/customAttributes/client/Client";
export declare namespace Orders {
export interface Options {
environment?: core.Supplier<environments.SquareEnvironment | string>;
/** Specify a custom URL to connect the client to. */
baseUrl?: core.Supplier<string>;
token?: core.Supplier<core.BearerToken | undefined>;
/** Override the Square-Version header */
version?: "2025-03-19";
fetcher?: core.FetchFunction;
}
export interface RequestOptions {
/** The maximum time to wait for a response in seconds. */
timeoutInSeconds?: number;
/** The number of times to retry the request. Defaults to 2. */
maxRetries?: number;
/** A hook to abort the request. */
abortSignal?: AbortSignal;
/** Override the Square-Version header */
version?: "2025-03-19";
/** Additional headers to include in the request. */
headers?: Record<string, string>;
}
}
export class Orders {
protected _customAttributeDefinitions: CustomAttributeDefinitions | undefined;
protected _customAttributes: CustomAttributes | undefined;
constructor(protected readonly _options: Orders.Options = {}) {}
public get customAttributeDefinitions(): CustomAttributeDefinitions {
return (this._customAttributeDefinitions ??= new CustomAttributeDefinitions(this._options));
}
public get customAttributes(): CustomAttributes {
return (this._customAttributes ??= new CustomAttributes(this._options));
}
/**
* Creates a new [order](entity:Order) that can include information about products for
* purchase and settings to apply to the purchase.
*
* To pay for a created order, see
* [Pay for Orders](https://developer.squareup.com/docs/orders-api/pay-for-orders).
*
* You can modify open orders using the [UpdateOrder](api-endpoint:Orders-UpdateOrder) endpoint.
*
* @param {Square.CreateOrderRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* await client.orders.create({
* order: {
* locationId: "057P5VYJ4A5X1",
* referenceId: "my-order-001",
* lineItems: [{
* name: "New York Strip Steak",
* quantity: "1",
* basePriceMoney: {
* amount: 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: 100,
* currency: "USD"
* },
* scope: "LINE_ITEM"
* }]
* },
* idempotencyKey: "8193148c-9586-11e6-99f9-28cfe92138cf"
* })
*/
public async create(
request: Square.CreateOrderRequest,
requestOptions?: Orders.RequestOptions,
): Promise<Square.CreateOrderResponse> {
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
"v2/orders",
),
method: "POST",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
body: serializers.CreateOrderRequest.jsonOrThrow(request, {
unrecognizedObjectKeys: "strip",
omitUndefined: true,
}),
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.CreateOrderResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
/**
* Retrieves a set of [orders](entity:Order) by their IDs.
*
* If a given order ID does not exist, the ID is ignored instead of generating an error.
*
* @param {Square.BatchGetOrdersRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* await client.orders.batchGet({
* locationId: "057P5VYJ4A5X1",
* orderIds: ["CAISEM82RcpmcFBM0TfOyiHV3es", "CAISENgvlJ6jLWAzERDzjyHVybY"]
* })
*/
public async batchGet(
request: Square.BatchGetOrdersRequest,
requestOptions?: Orders.RequestOptions,
): Promise<Square.BatchGetOrdersResponse> {
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
"v2/orders/batch-retrieve",
),
method: "POST",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
body: serializers.BatchGetOrdersRequest.jsonOrThrow(request, {
unrecognizedObjectKeys: "strip",
omitUndefined: true,
}),
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.BatchGetOrdersResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/batch-retrieve.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
/**
* Enables applications to preview order pricing without creating an order.
*
* @param {Square.CalculateOrderRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* await client.orders.calculate({
* order: {
* locationId: "D7AVYMEAPJ3A3",
* lineItems: [{
* name: "Item 1",
* quantity: "1",
* basePriceMoney: {
* amount: 500,
* currency: "USD"
* }
* }, {
* name: "Item 2",
* quantity: "2",
* basePriceMoney: {
* amount: 300,
* currency: "USD"
* }
* }],
* discounts: [{
* name: "50% Off",
* percentage: "50",
* scope: "ORDER"
* }]
* }
* })
*/
public async calculate(
request: Square.CalculateOrderRequest,
requestOptions?: Orders.RequestOptions,
): Promise<Square.CalculateOrderResponse> {
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
"v2/orders/calculate",
),
method: "POST",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
body: serializers.CalculateOrderRequest.jsonOrThrow(request, {
unrecognizedObjectKeys: "strip",
omitUndefined: true,
}),
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.CalculateOrderResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/calculate.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
/**
* Creates a new order, in the `DRAFT` state, by duplicating an existing order. The newly created order has
* only the core fields (such as line items, taxes, and discounts) copied from the original order.
*
* @param {Square.CloneOrderRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* await client.orders.clone({
* orderId: "ZAISEM52YcpmcWAzERDOyiWS123",
* version: 3,
* idempotencyKey: "UNIQUE_STRING"
* })
*/
public async clone(
request: Square.CloneOrderRequest,
requestOptions?: Orders.RequestOptions,
): Promise<Square.CloneOrderResponse> {
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
"v2/orders/clone",
),
method: "POST",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
body: serializers.CloneOrderRequest.jsonOrThrow(request, {
unrecognizedObjectKeys: "strip",
omitUndefined: true,
}),
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.CloneOrderResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/clone.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
/**
* Search all orders for one or more locations. Orders include all sales,
* returns, and exchanges regardless of how or when they entered the Square
* ecosystem (such as Point of Sale, Invoices, and Connect APIs).
*
* `SearchOrders` requests need to specify which locations to search and define a
* [SearchOrdersQuery](entity:SearchOrdersQuery) object that controls
* how to sort or filter the results. Your `SearchOrdersQuery` can:
*
* Set filter criteria.
* Set the sort order.
* Determine whether to return results as complete `Order` objects or as
* [OrderEntry](entity:OrderEntry) objects.
*
* Note that details for orders processed with Square Point of Sale while in
* offline mode might not be transmitted to Square for up to 72 hours. Offline
* orders have a `created_at` value that reflects the time the order was created,
* not the time it was subsequently transmitted to Square.
*
* @param {Square.SearchOrdersRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* 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
* })
*/
public async search(
request: Square.SearchOrdersRequest = {},
requestOptions?: Orders.RequestOptions,
): Promise<Square.SearchOrdersResponse> {
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
"v2/orders/search",
),
method: "POST",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
body: serializers.SearchOrdersRequest.jsonOrThrow(request, {
unrecognizedObjectKeys: "strip",
omitUndefined: true,
}),
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.SearchOrdersResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/search.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
/**
* Retrieves an [Order](entity:Order) by ID.
*
* @param {Square.GetOrdersRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* await client.orders.get({
* orderId: "order_id"
* })
*/
public async get(
request: Square.GetOrdersRequest,
requestOptions?: Orders.RequestOptions,
): Promise<Square.GetOrderResponse> {
const { orderId } = request;
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
`v2/orders/${encodeURIComponent(orderId)}`,
),
method: "GET",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.GetOrderResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/orders/{order_id}.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
/**
* Updates an open [order](entity:Order) by adding, replacing, or deleting
* fields. Orders with a `COMPLETED` or `CANCELED` state cannot be updated.
*
* An `UpdateOrder` request requires the following:
*
* - The `order_id` in the endpoint path, identifying the order to update.
* - The latest `version` of the order to update.
* - The [sparse order](https://developer.squareup.com/docs/orders-api/manage-orders/update-orders#sparse-order-objects)
* containing only the fields to update and the version to which the update is
* being applied.
* - If deleting fields, the [dot notation paths](https://developer.squareup.com/docs/orders-api/manage-orders/update-orders#identifying-fields-to-delete)
* identifying the fields to clear.
*
* To pay for an order, see
* [Pay for Orders](https://developer.squareup.com/docs/orders-api/pay-for-orders).
*
* @param {Square.UpdateOrderRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* await client.orders.update({
* orderId: "order_id",
* order: {
* locationId: "location_id",
* lineItems: [{
* uid: "cookie_uid",
* name: "COOKIE",
* quantity: "2",
* basePriceMoney: {
* amount: 200,
* currency: "USD"
* }
* }],
* version: 1
* },
* fieldsToClear: ["discounts"],
* idempotencyKey: "UNIQUE_STRING"
* })
*/
public async update(
request: Square.UpdateOrderRequest,
requestOptions?: Orders.RequestOptions,
): Promise<Square.UpdateOrderResponse> {
const { orderId, ..._body } = request;
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
`v2/orders/${encodeURIComponent(orderId)}`,
),
method: "PUT",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
body: serializers.UpdateOrderRequest.jsonOrThrow(_body, {
unrecognizedObjectKeys: "strip",
omitUndefined: true,
}),
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.UpdateOrderResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/orders/{order_id}.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
/**
* Pay for an [order](entity:Order) using one or more approved [payments](entity:Payment)
* or settle an order with a total of `0`.
*
* The total of the `payment_ids` listed in the request must be equal to the order
* total. Orders with a total amount of `0` can be marked as paid by specifying an empty
* array of `payment_ids` in the request.
*
* To be used with `PayOrder`, a payment must:
*
* - Reference the order by specifying the `order_id` when [creating the payment](api-endpoint:Payments-CreatePayment).
* Any approved payments that reference the same `order_id` not specified in the
* `payment_ids` is canceled.
* - Be approved with [delayed capture](https://developer.squareup.com/docs/payments-api/take-payments/card-payments/delayed-capture).
* Using a delayed capture payment with `PayOrder` completes the approved payment.
*
* @param {Square.PayOrderRequest} request
* @param {Orders.RequestOptions} requestOptions - Request-specific configuration.
*
* @example
* await client.orders.pay({
* orderId: "order_id",
* idempotencyKey: "c043a359-7ad9-4136-82a9-c3f1d66dcbff",
* paymentIds: ["EnZdNAlWCmfh6Mt5FMNST1o7taB", "0LRiVlbXVwe8ozu4KbZxd12mvaB"]
* })
*/
public async pay(
request: Square.PayOrderRequest,
requestOptions?: Orders.RequestOptions,
): Promise<Square.PayOrderResponse> {
const { orderId, ..._body } = request;
const _response = await (this._options.fetcher ?? core.fetcher)({
url: urlJoin(
(await core.Supplier.get(this._options.baseUrl)) ??
(await core.Supplier.get(this._options.environment)) ??
environments.SquareEnvironment.Production,
`v2/orders/${encodeURIComponent(orderId)}/pay`,
),
method: "POST",
headers: {
Authorization: await this._getAuthorizationHeader(),
"Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-03-19",
"X-Fern-Language": "JavaScript",
"X-Fern-SDK-Name": "square",
"X-Fern-SDK-Version": "42.0.0",
"User-Agent": "square/42.0.0",
"X-Fern-Runtime": core.RUNTIME.type,
"X-Fern-Runtime-Version": core.RUNTIME.version,
...requestOptions?.headers,
},
contentType: "application/json",
requestType: "json",
body: serializers.PayOrderRequest.jsonOrThrow(_body, {
unrecognizedObjectKeys: "strip",
omitUndefined: true,
}),
timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000,
maxRetries: requestOptions?.maxRetries,
abortSignal: requestOptions?.abortSignal,
});
if (_response.ok) {
return serializers.PayOrderResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
});
}
if (_response.error.reason === "status-code") {
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.body,
});
}
switch (_response.error.reason) {
case "non-json":
throw new errors.SquareError({
statusCode: _response.error.statusCode,
body: _response.error.rawBody,
});
case "timeout":
throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/{order_id}/pay.");
case "unknown":
throw new errors.SquareError({
message: _response.error.errorMessage,
});
}
}
protected async _getAuthorizationHeader(): Promise<string | undefined> {
const bearer = (await core.Supplier.get(this._options.token)) ?? process?.env["SQUARE_TOKEN"];
if (bearer != null) {
return `Bearer ${bearer}`;
}
return undefined;
}
}