Get started with the PHP SDK

This step-by-step guide leads you through setting up and making API calls using the PHP SDK.

Objectives of the get started guide

By the end of this guide you will have:

Requirements

Placeholder values

Example code in this getting started guide uses placeholders that should be replaced with the following values:

PlaceholderReplace withFrom
{projectKey}project_keyyour API Client
{clientID}client_idyour API Client
{clientSecret}secretyour API Client
{scope}scopeyour API Client
{region}your RegionHosts

Install the PHP SDK

Use the following command to install the PHP SDK:

composer require commercetools/commercetools-sdk

Create the Client class

Create a file called Client.php and insert the following code:

<?php
namespace Commercetools;
// Required imports
use Commercetools\Api\Client\ApiRequestBuilder;
use Commercetools\Api\Client\ClientCredentialsConfig;
use Commercetools\Api\Client\Config;
use Commercetools\Client\ClientCredentials;
use Commercetools\Client\ClientFactory;
use GuzzleHttp\ClientInterface;
require_once __DIR__ . '/vendor/autoload.php';
class Client{
function createApiClient(){
/** @var string $clientId */
/** @var string $clientSecret */
$authConfig = new ClientCredentialsConfig(
new ClientCredentials("{clientID}", "{clientSecret}"),[],
"https://auth.{region}.commercetools.com/oauth/token");
$client = ClientFactory::of()
->createGuzzleClient(new Config([],"https://api.{region}.commercetools.com"),$authConfig);
/** @var ClientInterface $client */
$builder = new ApiRequestBuilder($client);
// Include the Project key with the returned Client
return $builder->withProjectKey("{projectKey}");
}
}
?>

Test the Client

In your PHP program, add the following code:

<?php
// namespace
namespace Commercetools;
// Include the Client
require_once("Client.php");
// Create the apiRoot with your Client
$apiRoot = (new Client())->createApiClient();
// Make a get call to the Project
$myProject = $apiRoot
->get()
->execute();
// Output the Project name
echo $myProject->getName();
?>

$apiRoot can now be used to build requests to the Composable Commerce API.

This code includes an example API call that gets your Project to $myProject and outputs the Project's name using getName().

Using the PHP SDK

Imports

Without importing resource-specific classes you will be unable to use/access specific objects and methods.

For example, to create a Customer you must import:

use Commercetools\Api\Models\Customer\CustomerDraftBuilder;
require_once __DIR__ . '/vendor/autoload.php';

If not imported, a "Class not found" fatal error is returned with the name of the required class.

Using builders

The PHP SDK follows a builder pattern when constructing drafts, update actions, and other objects/types that contain multiple fields.

// Imports
use Commercetools\Api\Models\Common\LocalizedStringBuilder;
use Commercetools\Api\Models\Common\MoneyBuilder;
use Commercetools\Api\Models\Category\CategoryDraftBuilder;
require_once __DIR__ . '/vendor/autoload.php';
// Create a LocalizedString
$localizedString = LocalizedStringBuilder::of()
->put("en","English value")
->put("de","German value")
->build();
// Create US$100.00
$money = MoneyBuilder::of()
->withCurrencyCode("USD")
->withCentAmount(10000)
->build();
// Create a Category
$categoryDraft = CategoryDraftBuilder::of()
->withName(LocalizedStringBuilder::of()
->put("en","English name")
->build())
->withSlug(LocalizedStringBuilder::of()
->put("en","english-slug")
->build())
->withKey("category-key")
->build();

Consult the HTTP API reference to ensure that all required fields are included.

Once the fields/values are added, build() finishes building the object.

How to structure your API call

Add an endpoint

An endpoint should be added to $apiRoot. The following targets the Customers endpoint:

$customerInfo = $apiRoot
->customers()
// ...

If your IDE supports auto-complete, the full list of endpoints can be viewed.

Screenshot of autocomplete for endpoint

If no endpoint is specified, the Project is referenced.

Retrieving data

Get a single resource

When targeting a specific resource, you should include its ID or key followed by get() and execute().

// Get a specific Customer by ID
$customerInfo = $apiRoot
->customers()
->withId("a-customer-id")
->get()
->execute();
// Get a specific Customer by key
$customerInfo = $apiRoot
->customers()
->withKey("a-customer-key")
->get()
->execute();

If you query a resource with an id or key that does not exist, the API returns a 404 Not Found error.

In this example, $customerInfo now contains the data of the specified Customer. Individual information can be accessed from the fields within that object:

Screenshot of autocomplete for Customer object

Get multiple resources

If no ID or key is included, then the endpoint returns a PagedQueryResponse, which is identical to the PagedQueryResults in the HTTP API.

// Return a CustomerPagedQueryResponse
$customersQuery = $apiRoot
->customers()
->get()
->execute();

The results of these calls can be altered by including withWhere(), withSort(), withExpand(), withLimit(), or withOffset() after get().

These are identical to the parameters you can add to standard HTTP API calls. If your IDE supports autocomplete you can view a full list of methods available:

Screenshot of autocomplete for parameters

Viewing results

A list of resources within a PagedQueryResponse can be accessed using getResults():

// Return a CustomerPagedQueryResponse
$customersQuery = $apiRoot
->customers()
->get()
->execute();
// Put the returned Customers in a collection
$collectionOfCustomers = $customersQuery->getResults();
// Output the first Customer's email address
echo $collectionOfCustomers[0]->getEmail();

Writing a resource

Creating a new resource

Creating a new resource requires a draft of the resource to create. For Customers this would be a CustomerDraft, for Products a ProductDraft. These drafts are created using builders.

// Required import
use Commercetools\Api\Models\Customer\CustomerDraftBuilder;
require_once __DIR__ . '/vendor/autoload.php';
// Build a CustomerDraft with the required fields (email address and password)
$newCustomerDetails = (new CustomerDraftBuilder())
->withEmail("php-sdk@example.com")
->withPassword("password")
->build();

$newCustomerDetails should be included within post() and followed by execute().

// Post the CustomerDraft and get the new Customer
$newCustomer = $apiRoot
->customers()
->post($newCustomerDetails)
->execute() // As creating a Customer returns a CustomerSignInResult, getCustomer() is required to get the new Customer object
->getCustomer();

Updating an existing resource

Updating an existing resource requires posting an update payload. This payload (in the case of Customers, a CustomerUpdate) contains a collection of update actions and the last seen version of the resource.

Update actions and payloads are created using builders.

// Required imports
use Commercetools\Api\Models\Customer\CustomerUpdateBuilder;
use Commercetools\Api\Models\Customer\CustomerUpdateActionCollection;
use Commercetools\Api\Models\Customer\CustomerSetKeyActionBuilder;
require_once __DIR__ . '/vendor/autoload.php';
// Build a CustomerUpdate with the required fields (version and CustomerUpdateActionCollection)
$customerUpdate = (new CustomerUpdateBuilder())
->withVersion(1)
->withActions((new CustomerUpdateActionCollection())
->add((new CustomerSetKeyActionBuilder())
->withKey("a-unique-customer-key")
->build()))
->build();

This payload must then be posted to a single resource (using withId() or withKey()).

// Post the CustomerUpdate and return the updated Customer
$updatedCustomer = $apiRoot
->customers()
->withId("{customerID}")
->post($customerUpdate)
->execute();

Retrieving the raw API response

The above examples use execute() to return the resource as an instance of an object.

To retrieve the raw API response, use send().

// Return a CustomerPagedQueryResponse
$customersQuery = $apiRoot
->customers()
->get()
->send()
->getBody();
// Output the raw API response
echo $customersQuery;

Try our example code

The following example code covers some basic operations and is intended to provide you with an insight into how to create, query, and modify entities.

This code can be easily adapted and built upon to help you learn how to use the PHP SDK to interact with your commercetools Project.

Manage Customers

Create a Customer

PHP code for creating a CustomerPHP
// Create a CustomerDraft with the required fields (email address and password)
$newCustomerDetails = (new CustomerDraftBuilder())
->withEmail("php-sdk@example.com")
->withPassword("password")
->build();
// Post the CustomerDraft and get the new Customer
$customer = $apiRoot
->customers()
->post($newCustomerDetails)
->execute()
->getCustomer();
// Output the Customer ID
$customerID = $customer->getId();
echo $customerID;

This example code outputs the ID of the new Customer. Take note of this Customer ID and use it in place of {customerID} in following examples.

Query a Customer

Your new Customer can be queried by adding withId("{customerID}") after the customers() endpoint:

PHP code for querying a CustomerPHP
// Query a Customer by their ID
$queryCustomer = $apiRoot
->customers()
->withId("{customerID}")
->get()
->execute();
// Output the Customer's email address
$customerEmail = $queryCustomer->getEmail();
echo $customerEmail;

Add a Customer name

The required update actions for changing a Customer's name are Set First Name and Set Last Name.

The current version of the Customer is also required.

The version of a new Customer is 1. This value is incremented every time an update action is applied to the Customer.

If the specified version does not match the current version, the request returns an error.

PHP code for setting a Customer's first and last namesPHP
// Create an collection of update actions and add the setFirstName and setLastName actions
$updateCollection = (new CustomerUpdateActionCollection())
->add((new CustomerSetFirstNameActionBuilder())
->withFirstName("John")
->build())
->add((new CustomerSetLastNameActionBuilder())
->withLastName("Smith")
->build());
// Create the CustomerUpdate with the current version of the Customer and the actions
$customerUpdate = (new CustomerUpdateBuilder())
->withVersion(1)
->withActions($updateCollection)
->build();
// Post the CustomerUpdate and return the updated Customer
$customerToUpdate = $apiRoot
->customers()
->withId("{customerID}")
->post($customerUpdate)
->execute();
// Output the updated Customer's full name
$updatedCustomerName = $customerToUpdate->getFirstName()." ".$customerToUpdate->getLastName();
echo $updatedCustomerName;

Find a Customer by their email address

As the email of a Customer is unique, it is a dependable way to find a Customer.

Customers can be found by their email address by querying the Customers endpoint with a where parameter.

In the commercetools API, where uses a Query Predicate.

PHP code for finding a Customer by email addressPHP
// Search for Customers whose email address matches the Query Predicate
$customerToFind = $apiRoot
->customers()
->get()
->withWhere('email="php-sdk@example.com"')
->execute();
// Output the Customer's details. As email addresses must be unique, the first value of the results (0) should be accurate
$customerID = $customerToFind->getResults()[0]->getId();
echo $customerID;

If there is no Customer with the specified email address, then a null value is returned by getResults().

Manage Products

Creating Products requires more steps than creating Customers. This is due to how Products are modeled in commercetools.

Before a Product can be created, you must first create a ProductType.

Create a ProductType

When creating ProductTypes using the HTTP API, a ProductTypeDraft must be created and posted to the ProductTypes endpoint.

The ProductTypeDraft has two required fields: name and description.

PHP code for creating a ProductTypePHP
// Create a ProductTypeDraft with the required fields (name and description)
$newProductTypeDetails = (new ProductTypeDraftBuilder())
->withName("The name of your ProductType")
->withDescription("The description of your ProductType")
->build();
// Post the ProductTypeDraft
$productType = $apiRoot
->productTypes()
->post($newProductTypeDetails)
->execute();
// Output the ProductType ID
$productTypeID = $productType->getId();
echo $productTypeID;

This example code outputs the ID of the new Product Type. Take note of this Product Type ID and use it in place of {productType} in following examples.

Create a Product

When creating Products using the HTTP API, a ProductDraft must be created and posted to the Products endpoint.

The ProductDraft has three required fields: name, productType, and slug. All three fields must be built.

PHP code for creating a ProductPHP
//Create a ProductDraft with the required fields (name, slug, and productType)
$newProductDetails = (new ProductDraftBuilder())
->withName(LocalizedStringBuilder::of()
->put("en","English name for your Product")
->put("de","German name for your Product")
->build())
->withSlug(LocalizedStringBuilder::of()
->put("en","human-readable-url-for-english-product")
->put("de","human-readable-url-for-german-product")
->build())
->withProductType((new ProductTypeResourceIdentifierBuilder())
->withId("{productTypeID}")
->build())
->build();
// Post the ProductDraft and get the new Product
$product = $apiRoot
->products()
->post($newProductDetails)
->execute();
// Output the Product ID
$productID = $product->getId();
echo $productID;

Query your Product

Your new Product can be queried by adding withId("{productID}") after the products() endpoint:

PHP code for querying a ProductPHP
// Query a Product by its ID
$queryProduct = $apiRoot
->products()
->withId("{productID}")
->get()
->execute();
// Output the Product's version
$productVersion = $queryProduct->getVersion();
echo $productVersion;

Add a Product key

Adding a key to a Product requires the Set Product Key update action.

The current version of the Product is also required.

The version of a new Product is 1. This value is incremented every time an update action is applied to the Product.

If the specified version does not match the current version, the request returns an error.

PHP code for updating a ProductPHP
// Create an collection of update actions and add the setKey action
$updateCollection = (new ProductUpdateActionCollection())
->add((new ProductSetKeyActionBuilder())
->withKey("new-product-key")
->build());
// Create the ProductUpdate with the current version of the Product and the actions
$productUpdate = (new ProductUpdateBuilder())
->withVersion(1)
->withActions($updateCollection)
->build();
// Post the ProductUpdate and return the updated Product
$productToUpdate = $apiRoot
->products()
->withId("{productID}")
->post($productUpdate)
->execute();
// Output the updated Product's key
$updatedProductKey = $productToUpdate->getKey();
echo $updatedProductKey;

Return a Product by its Key

Your new Product key can be queried by adding withKey(productKey) after the products() endpoint:

PHP code for querying a Product by its keyPHP
// Query a Product by its Key
$findProductByKey = $apiRoot
->products()
->withKey("{productKey}")
->get()
->execute();
// Output the Product's English name
$productName = $findProductByKey->getMasterData()->getCurrent()->getName();
echo $productName["en"];
```