An introduction to using the Square PHP SDK features.
SDKs and Samples

Using the Square PHP SDK

Learn about the Square PHP SDK features.

PHP requires you to specify the fully qualified name of each class that you want to use. For example:

However, this can be unwieldy. The PHP use directive can help make your code more readable and less error-prone. For example:

To use the Square PHP SDK, instantiate a SquareClient object and initialize it with the appropriate environment and corresponding access token, as shown:

  • For testing, Square provides a Sandbox environment.

  • To access production resources, set the environment to PRODUCTION.

  • To set a custom environment, provide a CustomUrl and set the environment to Square.Environment.Custom.

The following example shows how to call a Square API:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
use Square\SquareClient;
use Square\Environment;
use Square\Exceptions\ApiException;

$client = new SquareClient([
  'accessToken' => getenv('SQUARE_ACCESS_TOKEN'),
  'environment' => Environment::SANDBOX,
]);

try {

    $apiResponse = $client->getLocationsApi()->listLocations();

    if ($apiResponse->isSuccess()) {
        $result = $apiResponse->getResult();
        # Your business logic here

    } else {
        $errors = $apiResponse->getErrors();
        # Your error-handling code here
    }

} catch (ApiException $e) {
    echo "ApiException occurred: <b/>";
    echo $e->getMessage() . "<p/>";
}

In the Square namespace, every object is a model. For example, complex types Address, Customer, and Order are all models defined in the namespace. You pass these models, with values, as parameters as shown in the following example. The example passes the Address model as a parameter to create a new customer.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
use Square\Models\Address;
use Square\Models\CreateCustomerRequest;
use Square\Exceptions\ApiException;

$address = new Address();
$address->setAddressLine1("1455 Market St");
$address->setAddressLine2("San Francisco, CA 94103");

$body = new CreateCustomerRequest();
$body->setGivenName("John");
$body->setFamilyName("Doe");
$body->setAddress($address);
$body->setIdempotencyKey(uniqid());

try {

    $apiResponse = $client->getCustomersApi()->createCustomer($body);

    if ($apiResponse->isSuccess()) {
        $result = $apiResponse->getResult();        
        echo "New customer created with customer ID " , 
            $result->getCustomer()->getId();

    } else {
        $errors = $apiResponse->getErrors();
        foreach ($errors as $error) {
            printf(
                "%s: %s, %s, %s<p/>", 
                $error->getCategory(),
                $error->getCode(),
                $error->getDetail()
            );
        }
    }

} catch (ApiException $e) {
    echo "ApiException occurred: <b/>";
    echo $e->getMessage() . "<p/>";
}

The Square API endpoints can have path parameters, query parameters, and a request body. When you make corresponding method calls using the Square PHP SDK, you provide the values as follows:

  • Request body - In the Square PHP SDK, a request body is represented by an array. To populate the request body, use setter methods. Depending on the method being called, the parameter values are represented as scalars or as embedded arrays.

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    use Square\Models\Address;
    use Square\Models\CreateCustomerRequest;
    use Square\Exceptions\ApiException;
    
    $address = new Address();
    $address->setAddressLine1('1455 Market St');
    $address->setAddressLine2('San Francisco, CA 94103');
    
    $body = new CreateCustomerRequest();
    $body->setGivenName('Mary');
    $body->setFamilyName('Smith');
    $body->setAddress($address);
    $body->setIdempotencyKey(uniqid());
    
    try {
    
        $apiResponse = $client->getCustomersApi()->createCustomer($body);
    
        if ($apiResponse->isSuccess()) {
            $result = $apiResponse->getResult();
            // Your business logic here
        } else {
            $errors = $apiResponse->getErrors();
            // Your error-handling code here
        }
    
    } catch (ApiException $e) {
        echo "ApiException occurred: <b/>";
        echo $e->getMessage() , "<p/>";
    }
    
  • Path and query parameters - For example:

    • The RetrieveCustomer endpoint has a customer_id path parameter (GET /v2/customers/{customer_id}).

    • The ListCustomers endpoint has several query parameters such as cursor and limit.

    You provide these as parameters to the method calls. The following example passes the customer_id path parameter as a parameter to the updateCustomer method:

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    use Square\Models\Address;
    use Square\Models\UpdateCustomerRequest;
    
    $address = new Address();
    $address->setAddressLine1('1455 Market St');
    $address->setAddressLine2('San Francisco, CA 94103');
    
    $body = new UpdateCustomerRequest();
    $body->setGivenName('Fred');
    $body->setFamilyName('Jones');
    $body->setAddress($address);
    $body->setVersion(0);
    
    $customerId = 'GZ48C4P2CWVXV7F7K2ZH795RSG';
    
    try {
        $apiResponse = 
            $client->getCustomersApi()->updateCustomer($customerId, $body); 
    
        if ($apiResponse->isSuccess()) {
    
            $result = $apiResponse->getResult();
            // Your business logic here
    
        } else {
            $errors = $apiResponse->getErrors();
            // Your error handling code
        } 
    
    } catch (ApiException $e) {
        echo "ApiException occurred: <b/>";
        echo $e->getMessage() . "<p/>";
    }
    

    For an example of query parameters, see Pagination.

You can configure the number of retries and the timeout values for HTTP requests when using the Square PHP SDK:

  • Retries - By default, the Square SDK doesn't retry a failed request. When your application starts, the SDK sets the number of retries to 0. You have the option to configure a different value when you create a client. Retries can help improve application stability by allowing applications to handle momentary failures in connecting to a service by transparently retrying a failed request.

  • Timeout - Timeout is the time period that a client waits for a server response. The Square SDK sets the default timeout to 60 seconds. On timeout, the SDK throws an exception. You have the option to configure a timeout value at the client level.

The following code creates a client, setting the number of retries to 2 and the timeout to 60 seconds.

Configuring a client with long timeout values and a high number of retries can cause some SDK operations to appear unresponsive. There are several considerations that apply when configuring the timeout and retries. These include:

  • For network issues (decrease in network connectivity and response speed), how should the application respond? Do you want the call to fail fast, or do you want the application to retry the failed call?

  • Buyer-facing applications might need to be responsive compared to a background job that can tolerate increased latency due increased timeout values and retries.

The response object contains properties that let you view the underlying HTTP traffic for the API call. In addition, the response object provides helper methods so you can determine whether the API call succeeded or failed:

  • If an API call succeeds, the isSuccess() method returns true. The request property describes the request that was sent to the endpoint, and the result property describes the response.

  • If an API call fails, the isSuccess() method returns false. The request property describes the request, but the result property is null.

For more information, see Square API errors.