Learn how to quickly set up and test the Square Node.js SDK.
Before you begin, you need a Square account and account credentials. You use the Square Sandbox for the Quickstart exercise.
Create a Square account and an application. For more information, see Create an Account and Application.
Get a Sandbox access token from the Developer Console. For more information, see Get a personal access token.
Install Node.js. Square supports Node.js version 10 or later.
Note
If you prefer to skip the following setup steps, download the Square Node SDK Quickstart sample and follow the instructions in the README.
Open a new terminal window. Create a new directory for your project and then go to that directory.
mkdir quickstart cd ./quickstartUse the
npm
command to create a simple project definition file (package.json).npm init --yesInstall the Square Node.js SDK.
npm install square
In your project directory, create a file named quickstart.js with the following content:
const { Client, Environment, ApiError } = require("square"); const client = new Client({ bearerAuthCredentials: { accessToken: process.env.SQUARE_ACCESS_TOKEN }, environment: Environment.Sandbox, }); const { locationsApi } = client; async function getLocations() { try { let listLocationsResponse = await locationsApi.listLocations(); let locations = listLocationsResponse.result.locations; locations.forEach(function (location) { console.log( location.id + ": " + location.name +", " + location.address.addressLine1 + ", " + location.address.locality ); }); } catch (error) { if (error instanceof ApiError) { error.result.errors.forEach(function (e) { console.log(e.category); console.log(e.code); console.log(e.detail); }); } else { console.log("Unexpected error occurred: ", error); } } }; getLocations();Save the quickstart.js file.
This code does the following:
- Creates a new Client object using your Square access token. For more information, see Set your Square credentials.
- Calls the listLocations method.
- If the request is successful, the code prints the location information on the terminal.
The code steps introduce some of the Square developer tools. For an overview of the Square APIs and developer tools, see Using the Square Node.js SDK.
The Node.js code in this Quickstart reads your Square Sandbox access token from the SQUARE_ACCESS_TOKEN
environment variable. This helps avoid the use of hardcoded credentials in the code.
For the following commands, replace yourSandboxAccessToken
with your Square Sandbox access token:
export SQUARE_ACCESS_TOKEN=yourSandboxAccessToken
Set-item -Path Env:SQUARE_ACCESS_TOKEN -Value yourSandboxAccessToken
set SQUARE_ACCESS_TOKEN=yourSandboxAccessToken
Run the following command:
node quickstart.jsVerify the result. You should see at least one location (Square creates one location when you create a Square account).