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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package spec-sdks

Composable Commerce PHP SDK

Index of Topics

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 Latest Stable Version Total Downloads

Technical Overview

The SDK consists of the following projects:

In addition, the SDK has the following directories:

The PHP SDK utilizes various standard interfaces and components to ensure consistency and interoperability:

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:

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

PHP Build Version
Package Version
Requires php Version >=7.2
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
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package commercetools/spec-sdks contains the following files

Loading the files please wait ....