Profiles·Public

square

semver>=40.0.0postconditions47functions23last verified2026-06-24coverage score82%

Postconditions: what we check

  • payments.create · square-payments-create-auth-error
    error
    WhenAccess token is missing, expired (ACCESS_TOKEN_EXPIRED), revoked (ACCESS_TOKEN_REVOKED), or lacks required permissions (INSUFFICIENT_SCOPES).
    ThrowsSquareError with errors[0].category === AUTHENTICATION_ERROR. Codes: UNAUTHORIZED, ACCESS_TOKEN_EXPIRED, ACCESS_TOKEN_REVOKED, CLIENT_DISABLED, FORBIDDEN, INSUFFICIENT_SCOPES.
    Required handlingCaller MUST wrap in try-catch. Check errors[0].code to distinguish expired (rotate token) from revoked (alert ops). Do NOT retry without resolving auth.
    costcriticalin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[1][2]
  • payments.create · square-payments-create-card-declined
    error
    WhenCard is declined by the issuer during payment processing.
    ThrowsSquareError with errors[0].category === PAYMENT_METHOD_ERROR. Codes: GENERIC_DECLINE, INSUFFICIENT_FUNDS, CVV_FAILURE, CARD_EXPIRED, EXPIRATION_FAILURE, INVALID_CARD, PAN_FAILURE, ADDRESS_VERIFICATION_FAILURE, TRANSACTION_LIMIT, CARD_DECLINED_VERIFICATION_REQUIRED, CARDHOLDER_INSUFFICIENT_PERMISSIONS, VOICE_FAILURE.
    Required handlingCaller MUST wrap in try-catch and read errors[0].code to show appropriate user message. GENERIC_DECLINE means try another card. INSUFFICIENT_FUNDS means notify user. CARD_DECLINED_VERIFICATION_REQUIRED triggers 3DS flow. Do NOT show raw error codes to users.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[3][2]
  • payments.create · square-payments-create-invalid-request
    error
    WhenRequired fields missing (sourceId or amountMoney), nonce expired (5 min TTL), nonce already used (single-use only), appFeeMoney exceeds payment amount, or locationId not found or inactive.
    ThrowsSquareError with errors[0].category === INVALID_REQUEST_ERROR. Codes: MISSING_REQUIRED_PARAMETER, CARD_TOKEN_EXPIRED, CARD_TOKEN_USED, INVALID_FEES, INVALID_LOCATION.
    Required handlingCaller MUST wrap in try-catch. CARD_TOKEN_USED is critical: nonces are single-use. On network error, do NOT retry with same nonce — generate fresh nonce. Check errors[0].code to distinguish token issues from missing fields.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[3][4]
  • payments.create · square-payments-create-rate-limit
    warning
    WhenRequest rate exceeds Square API rate limits for the payments endpoint.
    ThrowsSquareError with errors[0].category === RATE_LIMIT_ERROR. SDK does NOT auto-retry. Caller must implement backoff.
    Required handlingCaller MUST implement exponential backoff with jitter before retrying. MUST use idempotency_key on all retries to prevent duplicate charges.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[1][4]
  • payments.create · square-payments-create-timeout
    warning
    WhenNetwork connection times out before receiving a response from Square servers.
    ThrowsSquareTimeoutError — a distinct class from SquareError. Catching only SquareError does NOT catch SquareTimeoutError. Payment status is UNKNOWN.
    Required handlingCaller MUST catch SquareTimeoutError separately from SquareError. On timeout, check payment status via payments.get() with the original idempotency_key before retrying. Retrying without checking risks double-charging the customer.
    costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[3]
  • refunds.refundPayment · square-refunds-refund-payment-error
    error
    WhenPayment is in non-refundable state (too old, fully refunded, or has active dispute), refund amount exceeds available balance, or card issuer declines refund.
    ThrowsSquareError with errors[0].category === REFUND_ERROR. Codes: PAYMENT_NOT_REFUNDABLE, PAYMENT_NOT_REFUNDABLE_DUE_TO_DISPUTE, REFUND_AMOUNT_INVALID, REFUND_DECLINED, INSUFFICIENT_PERMISSIONS_FOR_REFUND.
    Required handlingCaller MUST wrap in try-catch and read errors[0].code. Route differently: PAYMENT_NOT_REFUNDABLE_DUE_TO_DISPUTE requires escalation to dispute team. REFUND_AMOUNT_INVALID requires checking remaining refundable balance. Use idempotency_key to prevent duplicate refunds on retry.
    costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[5][1]
  • refunds.refundPayment · square-refunds-auth-or-rate-limit
    error
    WhenAccess token is invalid or expired, or refund rate exceeds Square limits (common in batch refund jobs processing many orders at once).
    ThrowsSquareError with category AUTHENTICATION_ERROR or RATE_LIMIT_ERROR.
    Required handlingCaller MUST implement exponential backoff for RATE_LIMIT_ERROR. Track per-refund status in batch jobs to resume correctly after interruption. Do NOT retry AUTHENTICATION_ERROR without fixing the token.
    costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[1][4]
  • payments.complete · square-payments-complete-error
    error
    WhenPayment is not in APPROVED state (already COMPLETED, CANCELED, or FAILED), authorization hold has expired (6 days card-present, 7 days card-not-present), or access token is invalid.
    ThrowsSquareError with INVALID_REQUEST_ERROR (wrong state or expired hold) or AUTHENTICATION_ERROR. Expired hold: new payment must be created, not retried.
    Required handlingCaller MUST wrap in try-catch. Monitor time between auth and capture to complete before hold expiry. On error, check errors[0].code to determine if a new payment is required vs a retryable transient error.
    costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[6][7]
  • payments.cancel · square-payments-cancel-error
    error
    WhenPayment is already COMPLETED (captured — must refund instead), in FAILED state, already CANCELED, or access token is invalid.
    ThrowsSquareError with INVALID_REQUEST_ERROR (non-cancellable state) or AUTHENTICATION_ERROR. COMPLETED payments cannot be voided.
    Required handlingCaller MUST wrap in try-catch. If payment is COMPLETED, route to refunds.refundPayment() instead of retrying cancel(). Do not assume cancellation succeeded without confirming the API response.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[8]
  • subscriptions.create · square-subscriptions-create-customer-error
    error
    WhenCustomer ID does not exist in merchant directory, customer has no email (required for invoice delivery), or customer has no recorded name.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400 Bad Request). Confirmed codes: CUSTOMER_NOT_FOUND, CUSTOMER_MISSING_EMAIL, CUSTOMER_MISSING_NAME.
    Required handlingCaller MUST wrap in try-catch. CUSTOMER_NOT_FOUND: create customer first. CUSTOMER_MISSING_EMAIL: update customer profile before enrolling. Do NOT show subscribed state until API confirms status === ACTIVE.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilitysilent
    Sources[9][2]
  • subscriptions.create · square-subscriptions-create-card-error
    error
    Whencard_id is invalid or declined, or location is not configured for credit card processing (CARD_PROCESSING_NOT_ENABLED, 403 Forbidden). Subscription may be created in PENDING state when card payment fails at enrollment.
    ThrowsSquareError with INVALID_REQUEST_ERROR or PAYMENT_METHOD_ERROR, or 403 with CARD_PROCESSING_NOT_ENABLED. Subscription may exist in PENDING state.
    Required handlingCaller MUST wrap in try-catch and check response.subscription.status === ACTIVE before granting access. PENDING means Square will invoice but has NOT confirmed payment. Do NOT grant paid-feature access until status is ACTIVE.
    costhighin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[9][10]
  • subscriptions.cancel · square-subscriptions-cancel-error
    error
    WhenSubscription ID does not exist, subscription is already CANCELLED or DEACTIVATED, or access token is invalid.
    ThrowsSquareError with INVALID_REQUEST_ERROR (not found or not cancellable) or AUTHENTICATION_ERROR.
    Required handlingCaller MUST wrap in try-catch. Swallowing this error leaves the subscription active while the app assumes it was cancelled — customer continues to be billed. Log and alert on all cancellation failures. Verify by checking subscription status after the call. Treat NOT_FOUND as possible soft success (already cancelled) but log for audit trail.
    costhighin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[11]
  • orders.create · square-orders-create-error
    error
    WhenLocation ID not found or inactive, required order fields missing, line item price or quantity invalid, or currency not supported for merchant location.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400) or 403 for INVALID_LOCATION. Codes: INVALID_LOCATION, MISSING_REQUIRED_PARAMETER, INVALID_VALUE, UNSUPPORTED_CURRENCY. Also AUTHENTICATION_ERROR for bad token.
    Required handlingCaller MUST wrap in try-catch. INVALID_LOCATION surfaces when merchants deactivate locations — app must refresh cached location_id. Use idempotency_key to safely retry failed order creation without creating duplicates.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[12][2]
  • customers.create · square-customers-create-error
    error
    WhenNo identifying field provided (givenName, familyName, companyName, emailAddress, or phoneNumber — at least one required), or email/phone format is malformed.
    ThrowsSquareError with INVALID_REQUEST_ERROR. Codes: MISSING_REQUIRED_PARAMETER, INVALID_EMAIL_ADDRESS, INVALID_PHONE_NUMBER. Also AUTHENTICATION_ERROR for bad token.
    Required handlingCaller MUST wrap in try-catch. Validate email/phone formats client-side before calling. Customer creation failure blocks downstream card-on-file and subscription enrollment. Log repeated INVALID_REQUEST_ERROR — may indicate malformed data pipeline.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[13][2]
  • customers.delete · square-customers-delete-error
    error
    WhenCustomer ID does not exist in merchant directory, or access token is invalid.
    ThrowsSquareError with INVALID_REQUEST_ERROR (CUSTOMER_NOT_FOUND) or AUTHENTICATION_ERROR.
    Required handlingCaller MUST wrap in try-catch and verify deletion completed. Operation is irreversible — swallowing errors causes app to assume deletion succeeded while Square customer data persists. GDPR/CCPA requires confirmed deletion. Treat CUSTOMER_NOT_FOUND as soft success (already deleted) but log for audit.
    costhighin prodsilent failureusers seelost datavisibilitysilent
    Sources[14]
  • checkout.paymentLinks.create · square-checkout-payment-links-create-error
    error
    WhenquickPay missing required fields (name and priceMoney both required), locationId inactive or not found, price data malformed, or access token invalid.
    ThrowsSquareError with INVALID_REQUEST_ERROR (missing fields, INVALID_LOCATION) or AUTHENTICATION_ERROR.
    Required handlingCaller MUST wrap in try-catch. Validate quickPay fields before calling. Do NOT cache link URLs long-term — payment links expire and redirect customers to Square error page without notifying the application. Regenerate on demand.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[15]
  • cards.create · square-cards-create-source-used
    error
    WhenThe sourceId (nonce) provided was already used in a previous cards.create() call. Card nonces are single-use. On network error or timeout, retrying with the same sourceId always fails with SOURCE_USED — even if the first call never reached Square.
    ThrowsSquareError with INVALID_REQUEST_ERROR and code SOURCE_USED. Code SOURCE_EXPIRED occurs if the nonce exceeded its 5-minute TTL.
    Required handlingCaller MUST wrap in try-catch. On SOURCE_USED or SOURCE_EXPIRED: discard the nonce and generate a fresh one from the Square Web Payments SDK. Do NOT retry with the same sourceId. Storing the nonce for later re-use causes permanent failure on all subsequent calls. This is the #1 mistake in card vaulting flows.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[16]
  • cards.create · square-cards-create-customer-not-found
    error
    WhenThe customerId provided in the card object does not exist in the merchant's customer directory. Common when customer creation fails silently and the card vaulting step is not gated on successful customer creation.
    ThrowsSquareError with INVALID_REQUEST_ERROR and code CUSTOMER_NOT_FOUND (HTTP 400).
    Required handlingCaller MUST wrap in try-catch and ensure customers.create() succeeded before calling cards.create(). Do NOT proceed to subscription enrollment without a valid stored card — caller should surface the failure to the user rather than silently continuing with no card on file.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilitysilent
    Sources[16]
  • cards.create · square-cards-create-processing-not-enabled
    error
    WhenThe locationId provided is not enabled for credit card processing. Occurs when a merchant's location is newly created or not activated for payments.
    ThrowsSquareError with HTTP 403 and code CARD_PROCESSING_NOT_ENABLED.
    Required handlingCaller MUST wrap in try-catch. CARD_PROCESSING_NOT_ENABLED is not a transient error — retrying will always fail. Alert ops team to activate card processing for the location in the Square Dashboard. Do NOT silently swallow this error.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[16]
  • invoices.create · square-invoices-create-error
    error
    WhenThe linked orderId does not exist or is in a non-invoiceable state (already PAID, CANCELED, or has another invoice), primaryRecipient customerId is invalid, paymentRequests fields are missing or malformed, or card-on-file specified is invalid (INVALID_CARD, PAYMENT_METHOD_ERROR).
    ThrowsSquareError with INVALID_REQUEST_ERROR (400 — missing order, invalid customer, malformed payment schedule) or PAYMENT_METHOD_ERROR with code INVALID_CARD.
    Required handlingCaller MUST wrap in try-catch. Verify the order is in OPEN state before creating invoice. Confirm the customer exists and has an email address (required for email delivery). A successfully created invoice is in DRAFT state — it will NOT charge the customer until invoices.publish() is called. Do NOT assume draft creation means the customer has been notified or charged.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[17]
  • invoices.publish · square-invoices-publish-card-declined
    error
    WhenThe invoice is configured for automatic card-on-file payment and the card is declined during publish. Occurs if the stored card expired, was reported stolen, or has insufficient funds at the moment of publishing.
    ThrowsSquareError with PAYMENT_METHOD_ERROR and code CARD_DECLINED (HTTP 402), or INVALID_CARD if the card data cannot be validated.
    Required handlingCaller MUST wrap in try-catch and check the invoice status after publish failure. On CARD_DECLINED: notify the customer to update payment method. The invoice may still be created and in an error state — do NOT consider it unpublished without confirming via invoices.get(). Do NOT silently swallow this error or show the customer a success message.
    costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[18]
  • invoices.publish · square-invoices-publish-wrong-version
    error
    WhenThe version field does not match the invoice's current version in Square's system. This is Square's optimistic concurrency control — two concurrent publish attempts for the same invoice, or a publish after an update, will cause a version mismatch.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). The version must exactly match the current invoice version returned by invoices.get() or invoices.create().
    Required handlingCaller MUST wrap in try-catch. On version mismatch: re-fetch the invoice with invoices.get() to get the latest version, then retry publish with the new version. Using idempotency_key ensures that if the first publish succeeded, the retry returns the same published invoice. Always pass version from the most recent fetch.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[18]
  • orders.update · square-orders-update-version-conflict
    error
    WhenThe version field in the request does not match the current version of the order in Square. Concurrent modifications (e.g., POS and API both updating the same order) or stale cached order data cause this error. Version is required for all updates.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). Must always include the latest version from a recent orders.get() call. Cannot be retried without re-fetching.
    Required handlingCaller MUST wrap in try-catch. On version conflict: re-fetch the order with orders.get() to get the current version and state, then re-apply changes and retry. Do NOT retry the same update request with the same version — it will always fail.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[19][20]
  • orders.update · square-orders-update-closed-order
    error
    WhenAttempting to update an order in COMPLETED or CANCELED state. These orders are immutable — all fields are read-only after the order reaches a terminal state.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). The order state cannot be reverted, and updates to completed/canceled orders are not permitted.
    Required handlingCaller MUST wrap in try-catch and check order state before calling update. On closed-order error: do NOT retry. If a refund or correction is needed, use refunds.refundPayment() for completed orders, not orders.update(). Log and alert — this often indicates a race condition or UI bug.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[19]
  • orders.pay · square-orders-pay-amount-mismatch
    error
    WhenThe sum of all payment_ids does not equal the order total_money. Any partial payment coverage or over-payment causes immediate failure. Also fails if a payment referenced by payment_id is not in APPROVED state (already COMPLETED, CANCELED, or FAILED).
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). Payments not referenced in payment_ids and previously approved for the same order_id are automatically CANCELED by Square.
    Required handlingCaller MUST wrap in try-catch. Before calling pay(), verify: (1) sum of payment amounts equals order total, (2) all referenced payments are in APPROVED state via payments.get(). On failure, check which payments were auto-canceled by Square — do NOT attempt to re-complete canceled payments without creating new payment authorizations.
    costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[21][22]
  • orders.pay · square-orders-pay-timeout
    warning
    WhenNetwork connection times out while Square is processing the pay-order request. Payment status is UNKNOWN — the order may or may not have been marked as COMPLETED.
    ThrowsSquareTimeoutError — a distinct class from SquareError. Catching only SquareError does NOT catch SquareTimeoutError.
    Required handlingCaller MUST catch SquareTimeoutError separately. On timeout: do NOT immediately retry pay(). First verify order state via orders.get() — if COMPLETED, the payment succeeded. Retrying with the same idempotency_key is safe (returns the same result), but retrying without checking may trigger duplicate captures on APPROVED payments.
    costhighin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[21]
  • catalog.batchUpsert · square-catalog-batch-upsert-concurrent-update
    error
    WhenAnother catalog update request (batch or non-batch) is already being processed for the same seller account. Square processes only one catalog update at a time per account. Common in sync jobs that fire concurrent batches.
    ThrowsSquareError with RATE_LIMIT_ERROR and HTTP 429. Code: RATE_LIMITED. The entire request is rejected — no objects from this request are inserted.
    Required handlingCaller MUST wrap in try-catch and implement sequential retry with backoff. Do NOT fire parallel catalog update requests for the same seller — serialize them. On RATE_LIMITED (429), wait and retry the full batch. Use idempotency_key to prevent duplicate insertions on retry.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[23]
  • catalog.batchUpsert · square-catalog-batch-upsert-idempotency-reuse
    error
    WhenThe same idempotency_key is reused with different request parameters (different objects or different batches). This is a developer error that occurs when a sync job generates idempotency keys from a non-unique seed (e.g., date only, not UUID).
    ThrowsSquareError with INVALID_REQUEST_ERROR (400) and code IDEMPOTENCY_KEY_REUSED. Detail: "The idempotency key can only be retried with the same request data."
    Required handlingCaller MUST wrap in try-catch. Generate idempotency keys from a content hash of the objects being upserted, or use UUID v4 per request. If IDEMPOTENCY_KEY_REUSED is returned, do NOT retry with the same key — generate a new key and retry. This is not retryable without changing the key.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[24]
  • catalog.batchUpsert · square-catalog-batch-upsert-partial-batch-failure
    error
    WhenOne or more batches within the request contain malformed objects (exceeds size limits, references non-existent modifier list, invalid is_deleted flag). Square processes each batch independently — some batches may succeed while others fail.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). The error response indicates which batch failed. Successful batches in the same request are committed; failed batches are not.
    Required handlingCaller MUST wrap in try-catch. After a partial failure, inspect errors to determine which batch failed and re-submit only the failed batch with a new idempotency_key. Do NOT re-submit the entire request — already-committed batches will be treated as updates (same IDs), not duplicates. Validate objects client-side to catch size limit violations (max 1,000 objects per batch, 10,000 per request).
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[23]
  • disputes.accept · square-disputes-accept-financial-debit
    error
    Whendisputes.accept() succeeds but the caller does not handle the response or swallows errors. Square IMMEDIATELY debits the disputed amount from the seller's Square balance. If the balance is insufficient, Square debits the linked bank account. This is not a queued or asynchronous operation — the debit happens at accept time.
    ThrowsNo exception on success. The risk is silent SUCCESS: the caller may not confirm the debit occurred or update internal state. On actual error (wrong dispute state, authentication): SquareError with INVALID_REQUEST_ERROR or AUTHENTICATION_ERROR.
    Required handlingCaller MUST wrap in try-catch. On success, update internal dispute state to ACCEPTED and trigger accounting entries for the debit. Do NOT accept disputes in batch loops without tracking which disputes were accepted — if the loop crashes mid-way, some disputes are accepted (debited) and some are not, causing accounting inconsistency. Verify dispute is in actionable state (not ACCEPTED, not COMPLETED, not past due_at).
    costhighin prodimmediate exceptionusers seelost transactionvisibilitysilent
    Sources[25][26]
  • disputes.accept · square-disputes-accept-deadline-missed
    error
    WhenAttempt to accept or challenge a dispute after the due_at deadline has passed. Square automatically challenges the dispute on the seller's behalf after the deadline, transitioning the dispute to a state where seller actions are no longer permitted.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). Dispute state will be in an auto-challenged terminal state. The seller loses control of the dispute response.
    Required handlingCaller MUST check dispute.due_at before calling accept() or submitEvidence(). Implement deadline monitoring: alert the operations team at due_at - 24h. Do NOT assume disputes can be accepted at any time — the window is typically 30 days from notification but varies per card network.
    costhighin prodimmediate exceptionusers seelost transactionvisibilitysilent
    Sources[26]
  • disputes.submitEvidence · square-disputes-submit-evidence-irrevocable
    error
    WhensubmitEvidence() succeeds but the caller swallows the response without confirming submission. Evidence submission is permanent — evidence cannot be removed after calling this endpoint. If called before all evidence files are uploaded, the submission is final with incomplete evidence.
    ThrowsNo exception on success. Risk is premature submission (no exception thrown). On actual error (dispute already submitted, authentication, wrong state): SquareError with INVALID_REQUEST_ERROR or AUTHENTICATION_ERROR.
    Required handlingCaller MUST wrap in try-catch. Verify all evidence is uploaded (createEvidenceFile/ createEvidenceText succeed) BEFORE calling submitEvidence(). Do NOT call submitEvidence() in the same request as evidence upload without confirming upload success. After successful submission, update internal state to prevent re-submission. Evidence submission is final — no retry recovers from incomplete evidence submission.
    costhighin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[27][26]
  • disputes.submitEvidence · square-disputes-submit-evidence-dashboard-exclusion
    warning
    WhenAfter calling any Disputes API endpoint for a specific dispute, the seller can no longer manage that dispute through the Square Dashboard. Evidence and dispute status in the Dashboard are not updated when using the API. If submitEvidence() fails and the seller tries to use the Dashboard as a fallback, the two systems are out of sync.
    ThrowsNo exception — this is an operational constraint, not a thrown error. If submitEvidence() fails, callers cannot advise sellers to complete the submission via Dashboard.
    Required handlingCaller MUST implement complete evidence submission flow with retry logic. Do NOT partially implement dispute management and expect sellers to fall back to the Dashboard. If the API flow fails, the seller is locked out of Dashboard management for that dispute. Alert ops team immediately on any submitEvidence() failure.
    costhighin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[26]
  • giftCards.activities.create · square-gift-card-activities-insufficient-funds
    error
    WhenAttempting a REDEEM activity when the gift card balance is insufficient for the requested redemption amount. GIFT_CARD_AVAILABLE_AMOUNT is thrown when the remaining balance is less than the redemption amount.
    ThrowsSquareError with PAYMENT_METHOD_ERROR (400) and code GIFT_CARD_AVAILABLE_AMOUNT (insufficient balance) or INSUFFICIENT_FUNDS (funding source insufficient). Also PAYMENT_LIMIT_EXCEEDED if the amount exceeds processing limits.
    Required handlingCaller MUST wrap in try-catch and check the gift card balance before redemption. On GIFT_CARD_AVAILABLE_AMOUNT: split payment (partial gift card + another tender) or reject transaction. Do NOT assume gift card balance equals the full purchase amount without checking first. Log GIFT_CARD_AVAILABLE_AMOUNT errors to detect fraudulent redemption attempts.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[28]
  • giftCards.activities.create · square-gift-card-activities-pending-state
    error
    WhenAttempting to LOAD or REDEEM a gift card that is still in PENDING state (created but never activated). A gift card created via giftCards.create() remains in PENDING state until an ACTIVATE activity is successfully processed.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). The gift card cannot be used for transactions until an ACTIVATE activity is processed via giftCards.activities.create().
    Required handlingCaller MUST wrap in try-catch. Do NOT assume a gift card is usable immediately after giftCards.create() — always create an ACTIVATE activity before issuing the gift card to a customer. Validate gift card state before any LOAD or REDEEM activity. On PENDING state error: call giftCards.activities.create() with type=ACTIVATE and the initial balance before retrying.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilitysilent
    Sources[29][28]
  • giftCards.activities.create · square-gift-card-activities-temporary-error
    warning
    WhenSquare's internal gift card service returns a transient 503 Service Unavailable during activity creation. Common during peak transaction periods. TEMPORARY_ERROR means the activity status is unknown — it may or may not have been recorded.
    ThrowsSquareError with PAYMENT_METHOD_ERROR and HTTP 503. Code: TEMPORARY_ERROR. Square confirms this is safe to retry with the same idempotency key.
    Required handlingCaller MUST wrap in try-catch and implement retry logic. Use the same idempotency_key on retry — Square guarantees idempotency for gift card activities. On TEMPORARY_ERROR: wait and retry (exponential backoff). Do NOT show a failure to the customer until all retries are exhausted — the activity may have succeeded.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilitysilent
    Sources[28]
  • giftCards.create · square-gift-cards-create-pending-state-trap
    error
    WhengiftCards.create() succeeds but the caller issues the gift card to the customer without first creating an ACTIVATE activity. The gift card is in PENDING state and any LOAD or REDEEM attempt will fail with INVALID_REQUEST_ERROR.
    ThrowsNo exception from giftCards.create() — the trap is silent SUCCESS. The error occurs later when the customer attempts to use the gift card, not at creation time.
    Required handlingCaller MUST wrap in try-catch. After successful giftCards.create(), always call giftCards.activities.create() with type=ACTIVATE and the initial balance BEFORE issuing the gift card to the customer. Do NOT return the gift card GAN to the customer until activation succeeds. If activation fails, the gift card must be re-activated before distribution.
    costhighin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[29]
  • giftCards.create · square-gift-cards-create-invalid-gan
    error
    WhenA custom GAN is provided that fails validation: not 8-20 alphanumeric characters, not unique for this seller, or starts with a major credit card BIN pattern (e.g., 4XXXXXXX for Visa, 5XXXXXXX for Mastercard). Predictable GANs (e.g., sequential numbers) create fraud risk.
    ThrowsSquareError with INVALID_REQUEST_ERROR (400). GAN validation failure prevents gift card creation entirely.
    Required handlingCaller MUST wrap in try-catch. Validate custom GANs before calling create(): 8-20 alphanumeric, no major BIN patterns, must be unique. Prefer letting Square auto-generate GANs (omit gan field) unless specific GAN format is required. On INVALID_REQUEST_ERROR: fix the GAN and retry with a new idempotency_key.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[29]
  • subscriptions.pause · square-subscriptions-pause-invalid-request
    error
    WhenThe pause request is rejected: pauseEffectiveDate is in the past, pauseCycleDuration exceeds the remaining duration of the current subscription phase (INVALID_PAUSE_LENGTH), the date format is invalid (INVALID_DATE), the location is not enabled for card processing (CARD_PROCESSING_NOT_ENABLED 403), or the customer linked to the subscription cannot be found (CUSTOMER_NOT_FOUND).
    ThrowsSquareError with INVALID_REQUEST_ERROR or PAYMENT_METHOD_ERROR. Specific codes: INVALID_PAUSE_LENGTH (400), INVALID_DATE (400), CARD_PROCESSING_NOT_ENABLED (403), CUSTOMER_NOT_FOUND (400).
    Required handlingCaller MUST wrap in try-catch. Silent failure leaves the subscription ACTIVE — the customer continues to be billed while the app's UI claims the subscription is paused. Surface the error to the user, revert any optimistic UI update, and log INVALID_PAUSE_LENGTH / INVALID_DATE separately so support can correct the requested pause window. CARD_PROCESSING_NOT_ENABLED indicates an environment-level configuration issue and should page on-call rather than be retried.
    costhighin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[30][2]
  • subscriptions.pause · square-subscriptions-pause-deferred-billing-trap
    warning
    WhenThe pause call succeeds but the pause action is SCHEDULED — when pauseEffectiveDate is omitted or falls within the current billing cycle, the subscription is paused at the START of the next billing cycle. The current billing cycle still completes and the customer is charged at least one more time after the "successful" pause.
    ThrowsNo exception — the trap is that the success response carries an ACTION object whose effective date is in the future. The subscription.status field returned reflects the CURRENT state, not the post-pause state.
    Required handlingCaller MUST wrap in try-catch. After a successful pause, inspect the returned action.effective_date (or pauseEffectiveDate echoed in the response) and surface it to the user as "Pause takes effect on <date>." Do not message "Subscription paused" without that qualifier. Do not assume the next invoice will be skipped — the subscription will bill normally until effective_date arrives. For immediate pause, the caller must compute the next billing-cycle start themselves and inform the customer accordingly.
    costmediumin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[30]
  • subscriptions.pause · square-subscriptions-pause-auth-and-throttling
    error
    WhenAuthentication token is invalid, expired, or revoked (AUTHENTICATION_ERROR), or the subscription pause endpoint is being called above the per-merchant rate cap (RATE_LIMIT_ERROR / 429). Background workers that bulk-pause subscriptions for an outage or plan migration commonly trip the rate cap.
    ThrowsSquareError with AUTHENTICATION_ERROR (401) or RATE_LIMIT_ERROR (429). RATE_LIMITED is the documented error code per Square's ErrorCode enum.
    Required handlingCaller MUST wrap in try-catch. AUTHENTICATION_ERROR halts ALL subscription pauses on the worker — page on-call to rotate the token. RATE_LIMIT_ERROR must be retried with exponential backoff; carry the original idempotency_key on retry so the same logical pause is not registered twice. Track partial-batch state (which subscription IDs successfully paused) so the worker can resume after a token rotation or rate-limit recovery without re-pausing already paused subscriptions.
    costhighin prodsilent failureusers seeservice unavailablevisibilitysilent
    Sources[30][2]
  • subscriptions.resume · square-subscriptions-resume-customer-card-error
    error
    WhenThe subscription's customer no longer has the data required to charge them on resume: their card on file has been deleted or has expired, their email or name is missing on the customer record, or the customer was deleted between pause and resume. Subscriptions paused for months commonly hit this on resume because cards captured at pause time have since expired.
    ThrowsSquareError with INVALID_REQUEST_ERROR or PAYMENT_METHOD_ERROR. Specific codes: CUSTOMER_MISSING_EMAIL (400), CUSTOMER_MISSING_NAME (400), CUSTOMER_NOT_FOUND (400), INVALID_CARD (400), CARD_PROCESSING_NOT_ENABLED (403).
    Required handlingCaller MUST wrap in try-catch. Treat as a customer-fixable issue: surface a "Please update your payment method to resume your subscription" CTA, do NOT just log and ignore. Do not retry blindly — the customer must update the card on file or customer record first. Track resume failures separately from pause failures because their root cause is fundamentally different (stale customer data vs bad pause window).
    costhighin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[31][2]
  • subscriptions.resume · square-subscriptions-resume-invalid-date
    error
    WhenresumeEffectiveDate is invalid: in the past, before the scheduled pauseEffectiveDate, or after the subscription's canonical end date. Common in admin tooling that allows operators to type free-form resume dates without server-side range validation.
    ThrowsSquareError with INVALID_REQUEST_ERROR. Specific code: INVALID_DATE (400).
    Required handlingCaller MUST wrap in try-catch. Validate resumeEffectiveDate client-side: must be in the future, must be on or after the subscription's current paused-until date. Surface the parsed reason to the operator so they can re-enter a valid date — do not swallow and assume the resume succeeded.
    costmediumin prodimmediate exceptionusers seelost transactionvisibilityvisible
    Sources[31]
  • subscriptions.resume · square-subscriptions-resume-auth-and-throttling
    error
    WhenAuthentication token is invalid, expired, or revoked (AUTHENTICATION_ERROR), or the resume endpoint is being called above the per-merchant rate cap (RATE_LIMIT_ERROR / 429). End-of-month batch resumes are a common trigger.
    ThrowsSquareError with AUTHENTICATION_ERROR (401) or RATE_LIMIT_ERROR (429). RATE_LIMITED is the documented error code per Square's ErrorCode enum.
    Required handlingCaller MUST wrap in try-catch. AUTHENTICATION_ERROR halts all resumes — page on-call. For RATE_LIMIT_ERROR, retry with exponential backoff and the same idempotency_key. Track per-subscription resume state so a partially-completed batch can be resumed without double-resuming already-resumed subscriptions.
    costhighin prodsilent failureusers seeservice unavailablevisibilitysilent
    Sources[31][2]
  • invoices.cancel · square-invoices-cancel-invalid-state
    error
    WhenThe invoice is in a state that cannot be canceled: DRAFT (must be published first or deleted), or in a terminal state (PAID, REFUNDED, CANCELED, FAILED). A common race is two operators each clicking "Cancel" — the second click hits an already-CANCELED invoice and the catch-less caller silently UI-confirms a double-cancel.
    ThrowsSquareError with INVALID_REQUEST_ERROR. The Square Invoices API explicitly prohibits canceling invoices in DRAFT or terminal states.
    Required handlingCaller MUST wrap in try-catch. Distinguish CANCELED-already from PAID-already in the error path — surface "Invoice was already canceled" as a soft success to the operator, but surface "Invoice has already been paid; issue a refund instead" as a hard error that routes them to the refund flow. Never silently swallow.
    costmediumin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[32]
  • invoices.cancel · square-invoices-cancel-version-mismatch
    error
    WhenThe version field passed does not match the invoice's current server-side version. Stale local cache after a webhook-driven update, a concurrent edit by another operator, or a missing GetInvoice round-trip before the cancel call all trigger this.
    ThrowsSquareError with INVALID_REQUEST_ERROR carrying a version-mismatch message. The Square Invoices API requires the current version on every PublishInvoice, UpdateInvoice, and CancelInvoice request.
    Required handlingCaller MUST wrap in try-catch. On a version-mismatch error, fetch the latest invoice via invoices.get(), recompute whether cancellation is still appropriate against the freshly-fetched status, and only then retry with the new version number. Do NOT loop blindly — the underlying change may have already moved the invoice to PAID or CANCELED, in which case the retry is wrong.
    costmediumin prodsilent failureusers seelost transactionvisibilitysilent
    Sources[32][33]
  • invoices.cancel · square-invoices-cancel-auth-and-throttling
    error
    WhenAuthentication token is invalid, expired, or revoked (AUTHENTICATION_ERROR), the caller lacks INVOICES_WRITE or ORDERS_WRITE scope, or the endpoint is being called above the per-merchant rate cap (RATE_LIMIT_ERROR / 429).
    ThrowsSquareError with AUTHENTICATION_ERROR (401) or RATE_LIMIT_ERROR (429). RATE_LIMITED is the documented error code per Square's ErrorCode enum.
    Required handlingCaller MUST wrap in try-catch. AUTHENTICATION_ERROR halts all cancellations on the worker — page on-call. For RATE_LIMIT_ERROR, retry with exponential backoff. Since cancellation is irreversible, do NOT use a fire-and-forget retry — confirm via invoices.get() that the invoice status is now CANCELED before marking the local record as canceled, even on retry success.
    costhighin prodsilent failureusers seeservice unavailablevisibilitysilent
    Sources[32][2]

Sources

Every postcondition cites at least one of these. Grouped by source type; numbered to match the footnotes above.

Official documentation

Research notes

Curator notes from SOURCES.md captured when the profile was written so you can verify the reasoning, not just the rules.

Sources: square

Package: square Version Range: >=8.0.0 Last Updated: 2026-02-25


Official Documentation

Primary Sources

  1. Square Node.js SDK Overview https://developer.squareup.com/docs/sdks/nodejs

    • SDK features and capabilities
    • Client initialization
    • Retry configuration
  2. Square Node.js SDK Quickstart https://developer.squareup.com/docs/sdks/nodejs/quick-start

    • Getting started guide
    • Error handling example with SquareError
    • Locations API example
  3. Using the Square Node.js SDK https://developer.squareup.com/docs/sdks/nodejs/using-nodejs-sdk

    • Detailed usage patterns
    • Client configuration
    • API examples
  4. GitHub Repository https://github.com/square/square-nodejs-sdk

    • Official TypeScript SDK source code
    • README with examples
    • API documentation

Error Handling Documentation

  1. Square Error Handling Guide https://developer.squareup.com/docs/build-basics/general-considerations/handling-errors

    • Error types and status codes
    • Recommended error handling patterns
    • Retry strategies
  2. Payments API Error Handling https://developer.squareup.com/docs/payments-api/error-handling

    • Payment-specific error scenarios
    • Decline codes and handling
    • Best practices for payment failures

API-Specific Documentation

  1. Common API Patterns - Rate Limiting https://developer.squareup.com/docs/build-basics/common-api-patterns/rate-limiting

    • Rate limit thresholds
    • 429 response handling
    • Retry strategies
  2. Common API Patterns - Idempotency https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency

    • Idempotency key usage
    • Conflict handling (409 responses)
    • Best practices for retries
  3. Orders API - Error Scenarios https://developer.squareup.com/docs/orders-api/error-scenarios

    • Order-specific validation errors
    • Version conflict handling
    • Missing order handling
  4. Orders API - Managing Orders https://developer.squareup.com/docs/orders-api/manage-orders

    • Order lifecycle
    • Version management
    • Update patterns
  5. Customers API - Use the API https://developer.squareup.com/docs/customers-api/use-the-api

    • Customer creation and retrieval
    • Duplicate customer handling
    • Customer data validation

Migration and Versioning

  1. Square Node.js SDK Migration Guide https://developer.squareup.com/docs/sdks/nodejs/migration
    • Version 40.0.0+ breaking changes
    • Parameter name changes
    • Client construction updates

Error Types

SquareError

Import: import { SquareError } from "square"

Thrown when: API returns non-success status code (4xx or 5xx)

Properties:

  • statusCode: HTTP status code (number)
  • message: Error message (string)
  • body: Response body (object)
  • errors: Array of error objects with:
    • category: Error category (string)
    • code: Specific error code (string)
    • detail: Detailed error message (string)
  • rawResponse: Full HTTP response object

Usage Example:

import { Client, SquareError } from "square";

try {
  const response = await client.payments.create({
    sourceId: "cnon:card-nonce-ok",
    amountMoney: { amount: BigInt(100), currency: "USD" },
    idempotencyKey: "unique-key-123"
  });
} catch (err) {
  if (err instanceof SquareError) {
    console.log(`Status: ${err.statusCode}`);
    console.log(`Message: ${err.message}`);
    err.errors?.forEach(e => {
      console.log(`${e.category}: ${e.code} - ${e.detail}`);
    });
  }
}

Common Error Scenarios

1. Authentication Errors (401)

Cause: Invalid or expired access token

Handling:

  • DO NOT retry
  • Check API credentials
  • Alert operations team

Source: https://developer.squareup.com/docs/sdks/nodejs


2. Rate Limiting (429)

Cause: Too many API requests

Handling:

  • SDK automatically retries (default: 2 attempts)
  • Implement exponential backoff for extended rate limiting
  • Monitor rate limit headers

Source: https://developer.squareup.com/docs/build-basics/common-api-patterns/rate-limiting


3. Validation Errors (400, 422)

Cause: Invalid request parameters or payment declined

Handling:

  • Check err.errors array for specific issues
  • Validate required fields
  • For payment declines, display user-friendly message
  • DO NOT retry without fixing validation issues

Source: https://developer.squareup.com/docs/payments-api/error-handling


4. Idempotency Conflicts (409)

Cause: Idempotency key reused with different parameters

Handling:

  • Generate new idempotency key
  • Or retrieve the original result
  • DO NOT retry with same key and different data

Source: https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency


5. Resource Not Found (404)

Cause: Customer ID, Order ID, or other resource doesn't exist

Handling:

  • Handle missing resource gracefully
  • DO NOT retry
  • Update application state to reflect missing resource

Source: https://developer.squareup.com/docs/customers-api/use-the-api


6. Server Errors (5xx)

Cause: Square server error or temporary outage

Handling:

  • SDK automatically retries (default: 2 attempts)
  • Implement exponential backoff
  • Log errors and monitor for persistent issues
  • Use idempotency keys to prevent duplicate operations

Source: https://developer.squareup.com/docs/sdks/nodejs


7. Network Errors (408, Connection Errors)

Cause: Network connectivity issues or timeouts

Handling:

  • SDK automatically retries 408 errors (default: 2 attempts)
  • Implement exponential backoff for connection errors
  • Always use idempotency keys for non-idempotent operations

Source: https://developer.squareup.com/docs/sdks/nodejs


SDK Configuration

Retry Configuration

The SDK supports configuring retry behavior:

const client = new Client({
  accessToken: "YOUR_ACCESS_TOKEN",
  environment: Environment.Production,
  // Global retry configuration
  timeout: 60000,
  maxRetries: 3  // Default: 2
});

// Per-request retry override
const response = await client.payments.create(
  requestBody,
  { maxRetries: 5 }
);

Default Retry Behavior:

  • Retries on: 408 (Timeout), 429 (Rate Limit), 5xx (Server Errors)
  • Default attempts: 2 retries
  • Strategy: Exponential backoff

Source: https://developer.squareup.com/docs/sdks/nodejs


Main API Areas

Payments API

  • client.payments.create() - Create payment
  • client.paymentsApi.createPayment() - Legacy method
  • Error handling: Payment declines, validation errors, rate limits

Orders API

  • client.ordersApi.createOrder() - Create order
  • client.ordersApi.updateOrder() - Update order
  • Error handling: Version conflicts, validation errors

Customers API

  • client.customersApi.createCustomer() - Create customer
  • client.customersApi.retrieveCustomer() - Get customer by ID
  • Error handling: Duplicate customers, missing customers

Locations API

  • client.locations.list() - List all locations
  • Error handling: Authentication errors, rate limits

Additional Resources

Community Examples

  1. Square API with Node.js Guide https://www.w3tutorials.net/blog/square-api-nodejs/

    • Community examples and patterns
  2. Getting Started with Square Node.js SDK (LogRocket) https://blog.logrocket.com/getting-started-square-node-js-sdk/

    • Tutorial with error handling examples
  3. Web Payments SDK Exception Handling https://developer.squareup.com/docs/web-payments/exception-handling

    • Browser-side error handling patterns

Security Considerations

No Known CVEs

As of 2026-02-25, no CVEs found for the square npm package.

Searched:

  • CVE databases (cvedetails.com, nvd.nist.gov)
  • npm security advisories
  • GitHub security advisories
  • Snyk vulnerability database

Best Practices

  1. Always use idempotency keys for payment operations
  2. Implement exponential backoff for retries
  3. Validate request data before API calls
  4. Handle payment declines gracefully with user-friendly messages
  5. Monitor rate limits and implement backoff strategies
  6. Use environment variables for access tokens (never hardcode)

Package Information

  • npm: https://www.npmjs.com/package/square
  • Current version: 44.0.0+ (as of Feb 2025)
  • Breaking changes: Version 40.0.0 introduced breaking changes
  • Deprecated: square-connect (use square instead)

Verification Status

Verified: 2026-02-25 ✅ Sources: All links verified and accessible ✅ Contract Version: 1.0.0 ✅ Package Version Range: >=8.0.0

Need a different package?
Request a profile