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.
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 Make your First API Call.
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.
Open a new terminal window. Create a new directory for your project, and then go to that directory.
mkdir quickstart cd ./quickstartInstall the Square PHP SDK.
composer require square/square
In your project directory, create a new file named quickstart.php with the following content:
<?php require 'vendor/autoload.php'; use Square\SquareClientBuilder; use Square\Authentication\BearerAuthCredentialsBuilder; use Square\Environment; use Square\Exceptions\ApiException; $client = SquareClientBuilder::init() ->bearerAuthCredentials( BearerAuthCredentialsBuilder::init( getenv('SQUARE_ACCESS_TOKEN') ) ) ->environment(Environment::SANDBOX) ->build(); try { $apiResponse = $client->getLocationsApi()->listLocations(); if ($apiResponse->isSuccess()) { $result = $apiResponse->getResult(); foreach ($result->getLocations() as $location) { printf( "%s: %s, %s, %s<p/>", $location->getId(), $location->getName(), $location->getAddress()->getAddressLine1(), $location->getAddress()->getLocality() ); } } else { $errors = $apiResponse->getErrors(); foreach ($errors as $error) { printf( "%s<br/> %s<br/> %s<p/>", $error->getCategory(), $error->getCode(), $error->getDetail() ); } } } catch (ApiException $e) { echo "ApiException occurred: <b/>"; echo $e->getMessage() . "<p/>"; }Save the quickstart.php file.
This code does the following:
- Creates a new SquareClient object with 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 PHP 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
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 location when you create a Square account).