Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Typescript client library for the Square API

License

NotificationsYou must be signed in to change notification settings

square/square-nodejs-sdk

Repository files navigation

fern shieldnpm shield

The Square TypeScript library provides convenient access to the Square API from TypeScript.

Installation

npm i -s square

Reference

A full reference for this library is availablehere.

Versioning

By default, the SDK is pinned to the latest version. If you would liketo override this version you can simply pass in a request option.

awaitclient.payments.create(...,{version:"2024-05-04"// override the version used})

Usage

Instantiate and use the client with the following:

import{SquareClient}from"square";constclient=newSquareClient({token:"YOUR_TOKEN"});awaitclient.payments.create({sourceId:"ccof:GaJGNaZa8x4OgDJn4GB",idempotencyKey:"7b0f3ec5-086a-4871-8f13-3c81b3875218",amountMoney:{amount:BigInt(1000),currency:"USD",},appFeeMoney:{amount:BigInt(10),currency:"USD",},autocomplete:true,customerId:"W92WH6P11H4Z77CTET0RNTGFW8",locationId:"L88917AVBK2S5",referenceId:"123456",note:"Brief description",});

Legacy SDK

If you're using TypeScript, make sure that themoduleResolution setting in yourtsconfig.json is equal tonode16,nodenext,orbundler to consume the legacy SDK.

While the new SDK has a lot of improvements, we at Square understand that it takes time to upgrade when there are breaking changes.To make the migration easier, the new SDK also exports the legacy SDK assquare/legacy. Here's an example of how you can use thelegacy SDK alongside the new SDK inside a single file:

import{randomUUID}from"crypto";import{Square,SquareClient}from"square";import{Client}from"square/legacy";constclient=newSquareClient({token:process.env.SQUARE_ACCESS_TOKEN,});constlegacyClient=newClient({bearerAuthCredentials:{accessToken:process.env.SQUARE_ACCESS_TOKEN!,},});asyncfunctiongetLocation():Promise<Square.Location>{return(awaitclient.locations.get({locationId:"YOUR_LOCATION_ID",})).location!;}asyncfunctioncreateOrder(){constlocation=awaitgetLocation();awaitlegacyClient.ordersApi.createOrder({idempotencyKey:randomUUID(),order:{locationId:location.id!,lineItems:[{name:"New Item",quantity:"1",basePriceMoney:{amount:BigInt(100),currency:"USD",},},],},});}createOrder();

We recommend migrating to the new SDK using the following steps:

  1. Upgrade the NPM module to^40.0.0
  2. Search and replace all requires and imports from"square" to"square/legacy"
  • For required, replacerequire("square") withrequire("square/legacy")
  • For imports, replacefrom "square" withfrom "square/legacy"
  • For dynamic imports, replaceimport("square") withimport("square/legacy")
  1. Gradually move over to use the new SDK by importing it from the"square" import.

Request And Response Types

The SDK exports all request and response types as TypeScript interfaces. Simply import them with thefollowing namespace:

import{Square}from"square";constrequest:Square.CreateMobileAuthorizationCodeRequest={    ...};

Exception Handling

When the API returns a non-success status code (4xx or 5xx response), a subclass of the following errorwill be thrown.

import{SquareError}from"square";try{awaitclient.payments.create(...);}catch(err){if(errinstanceofSquareError){console.log(err.statusCode);console.log(err.message);console.log(err.body);}}

Pagination

List endpoints are paginated. The SDK provides an iterator so that you can simply loop over the items:

import{SquareClient}from"square";constclient=newSquareClient({token:"YOUR_TOKEN"});constresponse=awaitclient.bankAccounts.list();forawait(constitemofresponse){console.log(item);}// Or you can manually iterate page-by-pageconstpage=awaitclient.bankAccounts.list();while(page.hasNextPage()){page=page.getNextPage();}

Webhook Signature Verification

The SDK provides utility methods that allow you to verify webhook signatures and ensure that allwebhook events originate from Square. TheWebhooks.verifySignature method will verify the signature.

import{WebhooksHelper}from"square";constisValid=WebhooksHelper.verifySignature({  requestBody,signatureHeader:request.headers['x-square-hmacsha256-signature'],signatureKey:"YOUR_SIGNATURE_KEY",notificationUrl:"https://example.com/webhook",// The URL where event notifications are sent.});

Advanced

Additional Headers

If you would like to send additional headers as part of the request, use theheaders request option.

constresponse=awaitclient.payments.create(...,{headers:{'X-Custom-Header':'custom value'}});

Receive extra properties

Every response includes any extra properties in the JSON response that were not specified in the type.This can be useful for API features not present in the SDK yet.

You can receive and interact with the extra properties by accessing each one directly like so:

constresponse=awaitclient.locations.create(...);// Cast the response type into an `any`.constlocation=response.locationasany;// Then access the extra property by its name.constundocumentedProperty=location.undocumentedProperty;

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as longas the request is deemed retriable and the number of retry attempts has not grown larger than the configuredretry limit (default: 2).

A request is deemed retriable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use themaxRetries request option to configure this behavior.

constresponse=awaitclient.payments.create(...,{maxRetries:0// override maxRetries at the request level});

Timeouts

The SDK defaults to a 60 second timeout. Use thetimeoutInSeconds option to configure this behavior.

constresponse=awaitclient.payments.create(...,{timeoutInSeconds:30// override timeout to 30s});

Aborting Requests

The SDK allows users to abort requests at any point by passing in an abort signal.

constcontroller=newAbortController();constresponse=awaitclient.payments.create(...,{abortSignal:controller.signal});controller.abort();// aborts the request

Runtime Compatibility

The SDK defaults tonode-fetch but will use the global fetch client if present. The SDK works in the followingruntimes:

  • Node.js 18+
  • Vercel
  • Cloudflare Workers
  • Deno v1.25+
  • Bun 1.0+
  • React Native

Customizing Fetch Client

The SDK provides a way for your to customize the underlying HTTP client / Fetch function. If you're running in anunsupported environment, this provides a way for you to break glass and ensure the SDK works.

import{SquareClient}from"square";constclient=newSquareClient({    ...fetcher:// provide your implementation here});

Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.Additions made directly to this library would have to be moved over to our generation code,otherwise they would be overwritten upon the next generated release. Feel free to open a PR asa proof of concept, but know that we will not be able to merge it as-is. We suggest openingan issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!


[8]ページ先頭

©2009-2025 Movatter.jp