Learn how to quickly set up and test the Square PHP SDK.
Before you begin, you need a Square account and account credentials. You use the Square Sandbox for the Quickstart exercise.
Get a Sandbox access token from the Developer Console.
Install the following:
Note
If you prefer to skip the following setup steps, download the Square PHP SDK Quickstart sample and follow the instructions in the README.
Install the latest version by running the following command:
composer require square/square
Open a new terminal window. Create a new directory for your project, and then go to that directory.
mkdir quickstart cd ./quickstartSet your square credentials in an
.env
file. In your project directory, create a new file named.env
with the following content, replacingyourSandboxAccessToken
with your Square Sandbox access token:SQUARE_ACCESS_TOKEN=yourSandboxAccessToken
- In your project directory, create a new file named
quickstart.php
with the following content:
<?php
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\Environments;
use Square\Exceptions\SquareException;
use Dotenv\Dotenv;
// Load the .env file
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$square = new SquareClient(
token: $_ENV['SQUARE_ACCESS_TOKEN'],
options: ['baseUrl' => Environments::Sandbox->value // Used by default
]
);
try {
$response = $square->locations->list();
foreach ($response->getLocations() as $location) {
printf(
"%s: %s, %s, %s<p/>",
$location->getId(),
$location->getName(),
$location->getAddress()?->getAddressLine1(),
$location->getAddress()?->getLocality()
);
}
} catch (SquareException $e) {
echo 'Square API Exception occurred: ' . $e->getMessage() . "\n";
echo 'Status Code: ' . $e->getCode() . "\n";
}
?>
Save the quickstart.php file.
This code does the following:
- Loads the environment file containing your Square access token.
- Creates a new SquareClient object with your Square access token.
- Calls the $square->locations->list() method.
- If the request is successful, the code prints the location information on the terminal.
PHP ships with a built-in web server for testing purposes. Start the web server as follows:
php -S localhost:8000Open a web browser and navigate to http://localhost:8000/quickstart.php.
Verify the result. You should see at least one location (Square creates one Sandbox location when you create a Square account).
LHI1YXJ8YSV5Z: Default Test Account, 1600 Pennsylvania Ave NW, Washington