Learn how the Square PHP SDK supports the common Square API features.
Some of the Square API patterns are used across various APIs. These include the following:
- Pagination - Many Square API operations limit the size of the response. When the result of the API operation exceeds the limit, the API truncates the result. You must make a series of requests to retrieve all the data. This is referred to as pagination.
- Idempotency key - Most Square APIs that perform create, update, or delete operations require idempotency keys to protect against making duplicate calls that can have negative consequences (for example, charging a card on file twice).
- Object versioning - Some Square resources (for example, the
Customerobject) have versions assigned. The version numbers enable optimistic concurrency, which is the ability for multiple transactions to complete without interfering with each other. - Clear API object fields - Square API update endpoints that support sparse updates allow you to specify just the fields you want to add, change, or clear in the request. Note that
$client->orders->updaterequires anX-Clear-Null: trueHTTP header to indicate that the request contains anullfield update.
These Square API patterns are exposed in the Square PHP SDK.
The examples on this page assume the following client. For a complete walkthrough of installing the SDK and getting credentials, see the Square PHP SDK Quickstart.
use Square\SquareClient; use Square\Environments; $client = new SquareClient( token: getenv('SQUARE_TOKEN') ?: null, options: ['baseUrl' => Environments::Sandbox->value], );
Square API pagination support lets you split a full query result set into pages that are retrieved over a sequence of requests. For example, when you call $client->customers->list, you can limit the number of customers returned in the response.
To iterate over all customers, you can use a foreach loop and the SDK makes additional HTTP requests for you to retrieve additional pages of data.
use Square\Customers\Requests\ListCustomersRequest; $customers = $client->customers->list( new ListCustomersRequest([ 'limit' => 10, 'sortField' => 'DEFAULT', 'sortOrder' => 'DESC', ]), ); foreach ($customers as $customer) { echo sprintf( "customer: ID: %s Version: %s, Given name: %s, Family name: %s\n", $customer->getId(), $customer->getVersion(), $customer->getGivenName(), $customer->getFamilyName() ); }
When an application calls a Square API, it must be able to repeat an API operation when needed and get the same result each time. For example, if a network error occurs while updating a catalog item, the application might retry the same request and must ensure that the item updates only once.
This behavior is called idempotency. Most Square APIs that modify data (create, update, or delete) require you to provide an idempotency key that uniquely identifies the request. This allows you to retry the request if necessary, without duplicating work.
You can provide a custom unique key or simply generate one. There are language-specific functions that you can use to generate unique keys. For more information, see Idempotency.
The following example shows how the idempotencyKey is generated in a PHP application to create an order:
use Square\Types\CreateOrderRequest; use Square\Types\Order; $client->orders->create( new CreateOrderRequest([ 'idempotencyKey' => uniqid(), 'order' => new Order([ 'locationId' => 'M8AKAD8160XGR', ]), ]), );
Some Square API resources support versioning. For example, each Customer object has a version field. Initially, the version number is 0. Each update increases the version number. If you don't specify a version number in the request, the latest version is assumed.
This resource version number enables optimistic concurrency; multiple transactions can complete without interfering with each other. As a best practice, you should include the version field in your request. The value must be set to the current version. For more information, see Optimistic Concurrency.
The following example updates a customer name. The $client->customers->update method also includes a version number. The method succeeds only if the specified version number is the latest version of the customer object on the server.
use Square\Customers\Requests\UpdateCustomerRequest; use Square\Exceptions\SquareApiException; try { $response = $client->customers->update( new UpdateCustomerRequest([ 'customerId' => 'GZ48C4P2CWVXV7F7K2ZH795RSG', 'givenName' => 'Fred', 'familyName' => 'Jones', 'version' => 7, ]), ); $customer = $response->getCustomer(); printf("customer updated:<br/>Id: %s, %s, %s, %s<p/>", $customer->getId(), $customer->getVersion(), $customer->getGivenName(), $customer->getFamilyName() ); } catch (SquareApiException $e) { echo "SquareApiException occurred: <b/>"; echo $e->getMessage() . "<p/>"; }
If the version numbers on the client and server don't match, the call fails with the following:
- Category -
INVALID_REQUEST_ERROR - Code -
CONFLICT - Detail -
Version is not up to date.
SquareApiException is thrown for any non-2xx response. It exposes getStatusCode(), getErrors(), and getBody().
For update operations that support sparse updates, your request only needs to specify the fields you want to add, change, or clear, along with any fields required by the update operation. Square clears a field when you send an explicit null for it. For more information, see Clear field values.
Important
Passing null in a request object's array constructor does not clear the field — the constructor omits null values from the request entirely. To send an explicit null, you must use the property's setter method, which marks the field as explicitly set.
Serializing an explicitly set null requires Square PHP SDK version 45.0.0.20260122 or later.
The following example clears the twitterUsername field and sets the websiteUrl field:
use Square\Locations\Requests\UpdateLocationRequest; use Square\Types\Location; $location = new Location([]); $location->setWebsiteUrl('https://developer.squareup.com'); $location->setTwitterUsername(null); $client->locations->update( new UpdateLocationRequest([ 'locationId' => 'M8AKAD8160XGR', 'location' => $location, ]), );
If you're using null to clear fields in an order, you must add the X-Clear-Null: true HTTP header to signal your intention. Pass it on an individual call using the options parameter:
use Square\Orders\Requests\UpdateOrderRequest; use Square\Types\Order; $order = new Order([]); $order->setTicketName(null); $client->orders->update( request: new UpdateOrderRequest([ 'orderId' => 'A4BMDU4438ZLB', 'order' => $order, ]), options: ['headers' => ['X-Clear-Null' => 'true']], );
Don't combine null field clearing with the fieldsToClear field in the same update_order request. For more information, see Clear fields.