Download the PHP package commercetools/spec-sdks without Composer
On this page you can find all versions of the php package commercetools/spec-sdks. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download commercetools/spec-sdks
More information about commercetools/spec-sdks
Files in commercetools/spec-sdks
Package spec-sdks
Short Description The official PHP SDK for the commercetools Composable Commerce APIs
License MIT
Informations about the package spec-sdks
Composable Commerce PHP SDK
Index of Topics
- Introduction
- Package and Installation
- Technical Overview
- Placeholder values
- Getting Started
- Client Creation
- Customize Endpoint for different regions
- Performing Requests
- Configuration
- Applying PSRs
- Error Handling
- Authentication
- Token Storage Creation
- Password Flow
- Anonymous Flow
- Refresh Flow
- Middlewares
- DefaultMiddleware
- CorrelationIdMiddleware
- RetryNAMiddleware
- OAuthHandlerMiddleware
- LoggerMiddleware
- ReauthenticateMiddleware
- Querying
- Predicates
- Get By Id/Key
- Sorting
- Pagination
- Products and ProductTypes
- ProductType Creation
- Product Creation
- Reading Attributes
- Update attribute values of a product
- Serialization
- Migration Guidelines From SDK v1
- Observability
- Documentation
- License
Introduction
This repository contains the PHP SDK generated from the Composable Commerce API reference.
Client and Request Builder for making API requests against Commercetools.
Package and Installation
Package | Version |
---|---|
commercetools SDK |
Technical Overview
The SDK consists of the following projects:
lib/commercetools-base/src
: Contains Client which communicate with Composable Commerce to execute requests, it contains also the classes related to the client like tokens, middlewares and handlers, and mappers and exceptions.lib/commercetools-api/src
: Contains all generated models and request builders to communicate with Composable Commerce HTTP API.lib/commercetools-import/src
: Contains all generated models and request builders to communicate with the Import API.lib/commercetools-history/src
: Contains all generated models and request builders to communicate with the Change History API.
In addition, the SDK has the following directories:
examples/symfony-app
: it shows how the PHP SDK can be used in a Symfony application for a Docker environment with NewRelic monitoring enabled.test/integration
: Integration Tests for the SDK. A good way for anyone using the PHP SDK to understand it further.test/unit
: Unit Tests forlib/commercetools-api-tests
: generated unit test for each class for the api folderlib/commercetools-history-tests
: generated unit test for each class for the history folderlib/commercetools-import-tests
: generated unit test for each class for the import folder
The PHP SDK utilizes various standard interfaces and components to ensure consistency and interoperability:
- JSON serializer
- PSR-3 - LoggerInterface
- PSR-4 - Autoloader
- PSR-6 - CachingInterface
- PSR-7 - HTTP Message Interface
- PSR-16 - Common Interface for Caching Libraries
- PSR-18 - HTTP Client
- PHP Date API:
Placeholder values
Example code in this guide uses placeholders that should be replaced with the following values.
If you do not have an API Client, follow our Get your API Client guide.
Placeholder | Replace with | From |
---|---|---|
{projectKey} |
project_key | your API Client |
{clientID} |
client_id | your API Client |
{clientSecret} |
secret | your API Client |
{scope} |
scope | your API Client |
{region} |
your Region | Hosts |
Getting Started
Client Creation
The example below shows how to create a client with customized URIs passed in the creation of the Client itself. You will find the same classes in the Import API folder.
Customize Endpoint for different regions
By default, the library uses api.europe-west1.gcp.commercetools.com
endpoint. If you use a different region, you can configure the client to use a custom endpoint. Here is an example for the us-central1
region:
Note that the auth endpoint should contain the /oauth/token
suffix, but the API endpoint - don't.
Performing Requests
Detailed information of all available methods for the product API can be found here
Information for the Import API can be found here.
Examples to retrieve project information
To avoid specifying the project key for every request built it's possible to use the ones in the Commercetools\Client
namespace instead
These are some examples about how to execute a request:
Configuration
Applying PSRs
The PHP SDK utilizes various standard interfaces and components to ensure consistency and interoperability:
Error Handling
The error handle is already provided with the ExceptionFactory class. The methods contained in this class encapsulate the logic for converting Guzzle exceptions into your custom exceptions based on the HTTP response status codes. Which can be called directly in the request or can be called by a dedicated middleware for the error handling. Direct invocation in a request handling or directly handled in a middleware:
Authentication
The factory class ProviderFactory is for managing authentication and token handling.
Token Storage Creation
To generate a TokenStorageProvider that manages tokens using different flows: Refresh Flow and Anonymous Flow, you can use ProviderFactory::createTokenStorageProvider($anonTokenUrl, $refreshTokenUrl, $clientCredentials, $client, $tokenStorage, $anonymousIdProvider);
.
Password Flow
The ProviderFactory::createPasswordFlowProvider($passwordTokenUrl, $clientCredentials, $client, $tokenStorage);
method, creates a PasswordFlowTokenProvider for authenticating users with username and password, acquiring tokens securely.
Anonymous Flow
The createAnonymousFlowProvider($anonTokenUrl, $clientCredentials, $client, $refreshFlowTokenProvider, $anonymousIdProvider);
method builds an AnonymousFlowTokenProvider to manage tokens for anonymous users, integrating with the API's anonymous token endpoint.
Refresh Flow
The createRefreshFlowProvider($refreshTokenUrl, $clientCredentials, $client, $tokenStorage)
method sets up a RefreshFlowTokenProvider to handle token refresh operations seamlessly, ensuring continuous access to API resources.
Middlewares
We introduced middleware to add functionalities to the requests and the responses in the PHP SDK.
You can add middleware when creating the PHP SDK client. Multiple middlewares can be added using the array of middlewares.
The scope of the MiddlewareFactory which is a Factory pattern is to handle all the available middleware and have the chance to have them customized.
The methods that are contained in this class, are meant to create an array of middlewares.
DefaultMiddleware
The method createDefaultMiddlewares creates an array with default values of OAuth Handler, Authentication, Logger, Retry and Correlation ID.
CorrelationIdMiddleware
The method createCorrelationIdMiddleware creates a middleware that adds a correlation ID to the headers of HTTP requests.
RetryNAMiddleware
The method createRetryNAMiddleware is designed to create middleware that retries HTTP requests under certain conditions are met. This middleware is particularly useful in scenarios where transient errors, such as temporary server unavailability, may occur.
OAuthHandlerMiddleware
The method createMiddlewareForOAuthHandler creates a middleware for handling OAuth2 authentication ensuring to include the necessary OAuth credentials.
LoggerMiddleware
The method createLoggerMiddleware creates a middleware for logging HTTP requests and responses.
ReauthenticateMiddleware
The method createReauthenticateMiddleware creates a middleware that automatically reauthenticates HTTP requests when an invalid token error (HTTP 401) is encountered. It uses an OAuth2Handler to refresh the token and retry the request up to a specified number of times.
Querying
For the examples that we are mentioning below we are setting the $builder
like here:
Since the most of the variables to pass in the with()
method are scalars, this means that we can pass arrays in the related parameter of the method like in the examples below.
Predicates
The system allows the use of predicates when querying the API. Predicates are added as query parameter string to the request itself. The following example shows the usage of input variables:
It's also possible to use array values in predicates in case of a varying number of parameters.
Get By Id/Key
Sorting
See Sort for details.
Sorting using one parameter:
Sorting using multiple parameters:
Pagination
Limiting the number of the returned documents or page size:
Products and ProductTypes
ProductType Creation
A ProductType is like a schema that defines how the product attributes are structured.
ProductType
contains a list of AttributeDefinition which corresponds to the name and type of each attribute, along with some additional information. Each name/type pair must be unique across a Project, so if you create an attribute "foo" of type String, you cannot create another ProductType where "foo" has another type (e.g. LocalizedString). If you do it anyway you get an error message like:
"The attribute with name 'foo' has a different type on product type 'exampleproducttype'."
In this scenario we provide two ProductTypes
book and t-shirt.
The book product type contains the following attributes:
$isbn as String, International Standard Book Number The t-shirt product type contains the following attributes:
$color as AttributeLocalizedEnumValue with the colors green and red and their translations in German and English. $size as AttributePlainEnumValue with S, M and X. $laundrySymbols as set of AttributeLocalizedEnumValue with temperature and tumble drying. $matchingProducts as set of ProductReference, which can point to products that are similar to the current product. $rrp as Money containing the recommended retail price. $availableSince as DateTime which contains the date since when the product is available for the customer in the shop. All available attribute types you can find here: AttributeType in "All Known Implementing Classes".
The code for the creation of the book ProductType:
See the Test Code
The code for the creation of the t-shirt ProductType:
See the Test Code
ProductTypes have a key (String) which can be used as key to logically identify ProductTypes. The key has an unique constraint.
Product Creation
To create a product you need to reference the product type. Since the ProductType ID of the development system will not be the ID of the production system it is necessary to find the product type by name:
See the Test Code
The simplest way of adding attributes to a ProductVariant is to use which enables you to directly put the value of the attribute to the draft. But it cannot check if you put the right objects and types in it.
A book example:
See the Test Code
A T-shirt example:
See the Test Code
A wrong value for a field or an invalid type will cause a BadRequestException with an error code of "InvalidField".
See the Test Code
As alternative, you could declare your attributes at the same place and use these to read and write attribute values:
See the Test Code
Reading Attributes
The simplest way to get the value of the attribute is to use getValue() methods of Attribute, like :
See the Test Code
You might also use the method as a conversion for the attribute, like you have a EnumValue but extract it as boolean because these methods cast the values passed:
See the Test Code
Update attribute values of a product
Here below some examples about setting attribute values is like a product creation:
Example for books:
See the Test Code
Example for T-shirts:
See the Test Code
Create attributes for importing orders
Importing attribute values for orders works different from updating products. In orders you provide the full value for enum-like types instead of just the key as done for all other types. This makes it possible to create a new enum value on the fly. The other attributes behave as expected.
Example:
See the Test Code
Serialization
In the PHP SDK some classes implement the JsonSerializable interface, and they have a customized jsonSerialize()
method to convert the instance of the class to a JSON string easily.
This mean that when the method json_encode()
will be called, the object will be correctly converted and formatted to a JSON string.
See the example below:
Migration Guidelines from SDK v1
To migrate from the 1.x to the 2.x, there is a guideline below:
- Migration guidelines from v1 to v2
Observability
To monitor and observe the SDK, see the official documentation Observability, there is a Demo application which shows how to monitor the PHP SDK with New Relic and Datadog.
Documentation
License
MIT
All versions of spec-sdks with dependencies
ext-json Version *
guzzlehttp/psr7 Version ^1.7 || ^2.0.0
guzzlehttp/guzzle Version ^6.0 || ^7.0
psr/cache Version ^1.0 || ^2.0 || 3.0
psr/simple-cache Version ^1.0 || ^2.0 || 3.0
psr/log Version ^1.0 || ^2.0 || 3.0
psr/http-client Version ^1.0
psr/http-message Version ^1.0 || ^2.0
ramsey/uuid Version ^4.0
symfony/cache Version ^3.0 || ^4.0 || ^5.0 || ^6.0