Add Item
addItem is used to add to an item to your cart order. Note that cart and order tend to be used interchangeably depending on if you’re looking at it from a developer perspective or a buyer perspective. order is actually an object on the cart resource. For consistency in documentation, it will be referred to as an order for the most part.
Usage
addItem takes in the following object:
interface AddItemRequest {
lineItem: AddLineItem;
fulfillment: CartFulfillment;
locationId: string;
}
lineItemrepresents the item that you want to add to the order. If you use the SDK item helpers,validateItemwill provide the starting basis for theAddLineItemobject which is shown below.interface AddLineItem { itemId: string; variationId: string; quantity?: number; modifiers?: AddItemModifier[]; priceOverride?: { amount: number; currency: CurrencyTypeEnum; }; }itemIdis theidon your item resource.variationIdis theidof one of the variations on the item (e.g. one of the variations in theitem.variationsarray).quantityis the quantity of the item you want to add to the order. If excluded, defaults to1.modifiersis an array of modifier selections which is covered in the SDK’s item helpers’ modifier validation.priceOverrideis only applicable if your item is adonation(item.square_online_typeisDONATION) and your selected variation is the custom amount donation (must be toggled on in the Square Online dashboard) which is indicated by the variation fromitem.variationshaving apricing_typeofVARIABLE_PRICING.amountis the numeric currency subunits. For example, in USD, $7.25 would be725.currencyis one of theCurrencyTypes listed below.CurrencyType = { AUD: 'AUD', CAD: 'CAD', JPY: 'JPY', GBP: 'GBP', USD: 'USD', EUR: 'EUR' };
fulfillmentrepresents how you want the item/order to get to the buyer. Changing the fulfillment on subsequent add item requests will update the fulfillment on an existing order. This means you can’t have mixed fullfillment items in an order. Otherwise when a buyer goes to their cart they may see some items be invalid depending if they have fulfillment restrictions which don’t match the order’s fulfillment. For example, originally having an order with a food item that’s only available forPICKUP, then adding a shirt withSHIPMENT. The order now has aSHIPMENTfulfillment, and going to cart the food item would show as being invalid because it only supportsPICKUP. TheCartFulfillmentobject is shown below.interface CartFulfillment { fulfillmentType: FulfillmentTypeEnum; pickupDetails?: { scheduleType?: ScheduleTypeEnum; curbsidePickupRequested?: boolean; curbsidePickupDetails?: { curbsideDetails: string; }; pickupAt?: string; }, deliveryDetails?: { scheduleType?: ScheduleTypeEnum; noContactDelivery?: boolean; note?: string; recipient: DeliveryRecipient; deliverAt?: string; }, setPastTimeToCurrent?: boolean; }scheduleTypefor eitherpickupDetailsordeliveryDetails. Note that adding an item (including buy now) with ASAP will automatically update the cart time to the earliest available time.const ScheduleType = { ASAP: 'ASAP', SCHEDULED: 'SCHEDULED' }fulfillmentTypecan be any of the types below.const FulfillmentType = { SHIPMENT: 'SHIPMENT', PICKUP: 'PICKUP', DELIVERY: 'DELIVERY', MANUAL: 'MANUAL', };SHIPMENT,PICKUP, andDELIVERYavailability are determined by your individual item fulfillment settings.MANUALmust be used if thesquare_online_typeon your item isDONATION,EVENT,OTHER, orSIMPLE_DIGITAL.
pickupDetailsis only required if yourfulfillmentTypeisPICKUP. If not provided withPICKUP, the SDK will populate it with the defaults listed below.scheduleTypecan be set toASAPorSCHEDULED. The SDK will automatically populate it toASAPif not provided.curbsidePickupRequestedshould be set totrueif the buyer requested curbside pickup. Otherwise defaults tofalseif not provided.curbsidePickupDetailsis required ifcurbsidePickupRequestedistrue.curbsideDetailsis a message from the buyer on how they wish to have their curbside pickup completed. You can just set this to an empty string if no message is provided.
pickupAtreflects the time the order should be picked up at in RFC 3339 format. ForscheduleTypeASAPthis property does not need to be set.
deliveryDetailsis only required if yourfulfillmentTypeisDELIVERY.scheduleTypecan be set toASAPorSCHEDULED. The SDK will automatically populate it toASAPif not provided.noContactDeliverydenotes whether the delivery should done with no contact. The SDK will default tofalseif not provided.noteis the order note information provided to the seller.deliverAtreflects the delivery start window time for the order in RFC 3339 format. ForscheduleTypeASAPthis property does not need to be set.recipientrepresents the delivery address informationinterface DeliveryRecipient { address : { /** * e.g. "New York" */ locality: string; /** * e.g. "US" */ country: string; /** * e.g. "10013" */ postalCode: string; /** * e.g. "New York" */ administrativeDistrictLevel1: string; /** * e.g. "New York County" */ administrativeDistrictLevel2?: string; /** * e.g. "Town of New York" */ administrativeDistrictLevel3?: string; /** * e.g. "District 7" */ subLocality?: string; /** * e.g. "Neighborhood" */ subLocality2?: string; /** * e.g. "Housing colony" */ subLocality3?: string; /** * e.g. "100 6th avenue" */ addressLine1: string; addressLine2?: string; addressLine3?: string; } }
setPastTimeToCurrentindicates whether you want to update the fulfillment time toASAPwhen the requested fulfillment time is in the past. The default value is true if not provided.
locationIdis the ID of the location resource that you want the order fulfilled at (e.g. forPICKUPwhich store location you’d want the buyer to pickup from). ForfulfillmentTypes that are eitherSHIPMENTorMANUAL, you must set thelocationIdto your shipping location (configured in the Square Online dashboard).
Examples
// With the most basic request
const addItemRequest = {
lineItem: {
itemId: '47HCEE6ZQUFFY3Y7X52CRVCO',
variationId: '6YOTMYGOFTJR4PTTYRCLE7BH'
},
fulfillment: {
fulfillmentType: 'SHIPMENT',
setPastTimeToCurrent: true,
},
locationId: 'L36RW9ABXQTEE'
}
// With all the different modifiers
const addItemRequest = {
lineItem: {
itemId: '47HCEE6ZQUFFY3Y7X52CRVCO',
variationId: '6YOTMYGOFTJR4PTTYRCLE7BH',
modifiers: [
{
id: '6WVGAE3PKEHRWZHF54KR2PIN',
type: 'CHOICE',
choiceSelections: ['E3MWZ3PJ3VZDQWGW4G3KFZGW', 'GKCUYTB7ARN25J7BTRTOSVHO']
},
{
id: '11ede91fbff63a3ab4dbde667deefb9b',
type: 'TEXT',
textEntry: 'my t-shirt-text'
},
{
id: '11ee185ca1cd3e98a25c9e3d692ffefb',
type: 'GIFT_WRAP',
choiceSelections: ['11ee185ca1cd7daebd029e3d692ffefb']
},
{
id: '11ee185ca17973e490449e3d692ffefb',
type: 'GIFT_MESSAGE',
textEntry: 'happy bday'
}
]
},
fulfillment: {
fulfillmentType: 'SHIPMENT',
setPastTimeToCurrent: true,
},
locationId: 'L36RW9ABXQTEE'
};
// With curbside pickup and quantity
const addItemRequest = {
lineItem: {
itemId: '47HCEE6ZQUFFY3Y7X52CRVCO',
variationId: '6YOTMYGOFTJR4PTTYRCLE7BH',
quantity: 5
},
fulfillment: {
fulfillmentType: 'PICKUP',
curbsidePickupRequested: true,
curbsidePickupDetails: {
curbsideDetails: 'I will be driving a blue SUV.'
},
setPastTimeToCurrent: true,
},
locationId: 'L36RW9ABXQTEE'
}
// With a custom amount donation
const addItemRequest = {
lineItem: {
itemId: '47HCEE6ZQUFFY3Y7X52CRVCO',
variationId: '6YOTMYGOFTJR4PTTYRCLE7BH',
priceOverride: {
amount: 1000, // $10.00
currency: 'USD'
}
},
fulfillment: {
fulfillmentType: 'MANUAL',
setPastTimeToCurrent: true,
},
locationId: 'L36RW9ABXQTEE'
}
// Using the 'addItem' function
try {
const response = await sdk.cart.addItem(addItemRequest);
} catch (error) {
// Handle errors
}
Return Value
On success the following object is returned.
interface CartResponse {
data: {
cart: string;
cart_data: Cart;
validation: {
scheduled?: {
valid: boolean;
error?: string;
next?: ScheduledValidationNext;
}
};
cart_errors: CartError[]
};
response: Response;
}
interface CartError {
translated: string;
next?: ScheduledValidationNext;
}
Note: ScheduledValidationNext object can be found here
data.cartis theorderIdof the order the item was added to (equivalent toidon the cart resource).data.cart_datais the latest cart. This will include the item that was just added, and an updated and validated fulfillment time if applicable. See Cart Resource for details.is an empty object if the fulfillment is not schedulable (i.e. pickup or delivery), otherwise provides the scheduled validation. We recommend usingdata.validationdata.cart_errorsover this as validation is deprecated.is whether or not the pickup or delivery schedule update was valid.data.validation.scheduled.validis provided if there’s an error reason why valid is false. Not included for a simple SCHEDULED validation check.data.validation.scheduled.erroris the next valid fulfillment time if available.data.validation.scheduled.nextdata.cart_errorsis an array of errors that are applicable to the cart for this request. We recommend using this overdata.validationas validation is deprecated. Can be empty if there are no errors.data.cart_errors.[].translatedis a translated string you can use for buyer facing error handling. This is based off the site language set in the Square Online dashboard.data.cart_errors.[].nextis the next valid fulfillment time if applicable to the error and available.responseis the raw response from theFetch APIused under the hood.
Error Handling
As you may have noticed in the last example above, the SDK Cart APIs will throw if any error occurs. The error thrown is in the object format below.
interface CartError extends Error {
status?: number;
fields?: string[];
errors?: CartValidationErrors;
cart_errors: CartError[];
}
messagecomes from theErrorinterface and will include the error message itself. This message will always be inen_USand may include a specific issue that went wrong (e.g.'Unfortunately the item requested only has 5 item(s) left in stock. Please adjust the quantity and try again.').statusis populated if an error status was received on the response (e.g.500).fieldsis populated if there are any invalid ids passed (e.g.['invalidId1', 'invalidId2']). This is only set if themessageis'Invalid IDs passed in payload'.errorsis populated if there are any properties that fail the initial validation.CartValidationErrorsis an object with a key for each failed validation field and a value of an array of validation errors for that respective field.interface CartValidationErrors { [key: string]: string[]; }An example:
message: 'fulfillment is required (and 1 more error)', errors: { 'fulfillment': [ 'fulfillment is required' ], 'fulfillment.fulfillmentType': [ 'fulfillment.fulfillment type is required' ] }cart_errorsare the errors you can use for buyer facing error handling. This is the same format described further above, but you would use thetranslatedvalue for the potential cart errors. Will always be populated for a thrown error.
try {
const response = await sdk.cart.addItem(addItemRequest);
} catch (error) {
// Use `cart_errors` to display a buyer facing error message
}