PHP code example of commercetools / spec-sdks
1. Go to this page and download the library: Download commercetools/spec-sdks library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once ('vendor/autoload.php' );
commercetools / spec-sdks example snippets
namespace Commercetools ;
use Commercetools \Api \Client \ClientCredentialsConfig ;
use Commercetools \Api \Client \Config ;
use Commercetools \Client \ClientCredentials ;
use Commercetools \Client \ClientFactory ;
pes of the oauth client.
* Format: `<the scope name>:<the project key>`.
* Example: `manage_products:project1`. $authConfig
*/
$authConfig = new ClientCredentialsConfig(
new ClientCredentials('{clientID}' , '{clientSecret}' , '{scope}' ),
[],
'https://auth.{region}.commercetools.com/oauth/token'
);
$client = ClientFactory::of()->createGuzzleClient(
new Config([], 'https://api.{region}.commercetools.com' ),
$authConfig
);
$authConfig = new ClientCredentialsConfig(
new ClientCredentials('{clientId}' , '{clientSecret}' ),
[],
'https://auth.us-central1.gcp.commercetools.com/oauth/token'
);
$config = new Config([], 'https://api.us-central1.gcp.commercetools.com' );
$client = ClientFactory::of()->createGuzzleClient(
$config,
$authConfig,
);
use Commercetools \Api \Client \ApiRequestBuilder ;
use GuzzleHttp \ClientInterface ;
$builder = new ApiRequestBuilder($client);
$request = $builder->withProjectKey('{projectKey}' )->get();
use Commercetools \Client \ApiRequestBuilder ;
use Commercetools \Client \ImportRequestBuilder ;
use GuzzleHttp \ClientInterface ;
$builder = new ApiRequestBuilder('{projectKey}' , $client);
$request = $builder->categories()->get();
$importBuilder = new ImportRequestBuilder('{projectKey}' , $client);
$request = $importBuilder->importSinks()->get();
use Commercetools \Client \ApiRequestBuilder ;
use GuzzleHttp \ClientInterface ;
$builder = new ApiRequestBuilder('{projectKey}' , $client);
$request = $builder->with()->get();
$project = $request->execute();
$response = $request->send();
$project = $request->mapFromResponse($response);
$promise = $request->sendAsync();
$project = $request->mapFromResponse($promise->wait());
$response = $client->send($request);
$project = $request->mapFromResponse($response);
$authHandler = HandlerStack::create();
$authHandler->push(
MiddlewareFactory::createLoggerMiddleware(new Logger('auth' , [new StreamHandler('./logs/requests.log' )]))
);
$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret), [
'handler' => $authHandler,
]);
$logger = new Logger('client' , [new StreamHandler('./logs/requests.log' )]);
$client = ClientFactory::of()->createGuzzleClientForHandler(
new Config(['maxRetries' => 3 ]),
OAuthHandlerFactory::ofAuthConfig($authConfig),
$logger
);
use Symfony \Component \Cache \Adapter \FilesystemAdapter ;
$filesystemCache = new FilesystemAdapter();
$config = new Config(['timeout' => 30 ]);
$client = ClientFactory->createGuzzleClientForHandler(
$config,
OAuthHandlerFactory::ofAuthConfig($authConfig, $cache)
);
$request = $client->with()->categories()->withId($category->getId())->get()->withExpand('parent' );
$result = $request->execute();
$request = new \GuzzleHttp\Psr7\Request('GET' , '{projectKey}/categories/{ID}' );
$response = $client->send($request);
use Symfony \Component \Cache \Simple \FilesystemCache ;
use Symfony \Component \Cache \Psr16Cache ;
$filesystemCache = new FilesystemAdapter();
$cache = new Psr16Cache($filesystemCache);
$config = new Config(['timeout' => 30 ]);
$client = ClientFactory->createGuzzleClientForHandler(
$config,
OAuthHandlerFactory::ofAuthConfig($authConfig, $cache)
);
if ($e->getCode() >= 500 ) {
throw ExceptionFactory::createServerException($e, $apiRequest, $response, $result);
} else {
throw ExceptionFactory::createClientException($e, $apiRequest, $response, $result);
}
$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret), [
'handler' => $authHandler,
]);
$oauthHandler = OAuthHandlerFactory::ofAuthConfig($authConfig),
$logger = new Logger('client' , [new StreamHandler('./logs/requests.log' )]);
$maxRetries = 3 ;
$correlationIdProvider = new DefaultCorrelationIdProvider();
$middlewares = MiddlewareFactory::createDefaultMiddlewares(
$oauthHandler,
$logger,
$maxRetries,
$correlationIdProvider
);
$correlationIdProvider = new DefaultCorrelationIdProvider();
$correlationIdMiddleware = MiddlewareFactory::createCorrelationIdMiddleware(
$correlationIdProvider
);
$maxRetries = 3 ;
$retryMiddleware = MiddlewareFactory::createRetryNAMiddleware($maxRetries);
$tokenProvider = new YourTokenProvider();
$oauthHandler = OAuthHandlerFactory::ofProvider($tokenProvider),
$oauthMiddleware = MiddlewareFactory::createMiddlewareForOAuthHandler($oauthHandler);
$logger = new Logger('auth' );
$logger->pushHandler(new StreamHandler('./logs/requests.log' , Logger::DEBUG));
$loggerMiddleware = MiddlewareFactory::createLoggerMiddleware($logger);
$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret), [
'handler' => $authHandler,
]);
$oauthHandler = OAuthHandlerFactory::ofAuthConfig($authConfig),
$reauthMiddleware = MiddlewareFactory::createReauthenticateMiddleware($oauthHandler);
use Commercetools \Client \ApiRequestBuilder ;
use GuzzleHttp \ClientInterface ;
$builder = new ApiRequestBuilder('{projectKey}' , $client);
$builder
->customers()
->get()
->withWhere('lastName=:lastName' )
->withPredicateVar("lastName" , $customerSignIn->getCustomer()->getLastName());
$builder
->productProjections()
->get()
->withWhere('masterVariant(sku in :skus)' )
->withPredicateVar("skus" , ["foo" , "bar" ]);
$builder
->productProjections()
->withId('test_id' )
->get();
$builder
->productProjections()
->withKey('test_key' )
->get();
$builder
->products()
->get()
->withSort("masterData.current.name.en asc" );
$builder
->products()
->get()
->withSort(["masterData.current.name.en asc" , "id asc" ]);
$builder
->products()
->get()
->withLimit(4 )
->withOffset(4 );
$isbn = AttributeDefinitionBuilder::of()
->withType(AttributeTextTypeBuilder::of()->build())
->withName(self ::ISBN_ATTR_NAME)
->withLabel(LocalizedStringBuilder::of("ISBN" )->build())
->withIsRequired(false )
->build();
$productType = ProductTypeBuilder::of()
->withName(self ::BOOK_PRODUCT_TYPE_NAME)
->withDescription("books" )
->withAttributes(AttributeDefinitionCollection::of()->add($isbn))
->build();
$builder = new ApiRequestBuilder('{projectKey}' , $client);
$request = $builder
->productTypes()
->withId($productType->getId())
->get();
$productTypeQueryResponse = $request->execute();
$green = AttributeLocalizedEnumValueBuilder::of()
->withKey("green" )
->withLabel(LocalizedStringBuilder::fromArray(["en" => "green" , "de" => "grün" ])->build())
->build();
$red = AttributeLocalizedEnumValueBuilder::of()
->withKey("red" )
->withLabel(LocalizedStringBuilder::fromArray(["en" => "red" , "de" => "rot" ])->build())
->build();
$color = AttributeDefinitionDraftBuilder::of()
->withName(self ::COLOR_ATTR_NAME)
->withLabel(LocalizedStringBuilder::fromArray(["en" => "color" ])->build())
->withType(AttributeLocalizedEnumTypeBuilder::of()
->withValues(AttributeLocalizedEnumValueCollection::fromArray([$green, $red]))
->build())
->withIsRequired(true )
->build();
$small = AttributePlainEnumValueBuilder::of()
->withKey("S" )
->withLabel("S" )
->build();
$medium = AttributePlainEnumValueBuilder::of()
->withKey("M" )
->withLabel("M" )
->build();
$sizeX = AttributePlainEnumValueBuilder::of()
->withKey("X" )
->withLabel("X" )
->build();
$size = AttributeDefinitionDraftBuilder::of()
->withName(self ::SIZE_ATTR_NAME)
->withLabel(LocalizedStringBuilder::fromArray(["en" => "Size" ])->build())
->withType(AttributeEnumTypeBuilder::of()
->withValues(AttributePlainEnumValueCollection::fromArray([$small, $medium, $sizeX]))
->build())
->withIsRequired(true )
->build();
$cold = AttributeLocalizedEnumValueBuilder::of()
->withKey("cold" )
->withLabel(LocalizedStringBuilder::fromArray(["en" => "Wash at or below 30°C " , "de" => "30°C" ])->build())
->build();
$hot = AttributeLocalizedEnumValueBuilder::of()
->withKey("hot" )
->withLabel(LocalizedStringBuilder::fromArray(["en" => "Wash at or below 60°C" , "de" => "60°C" ])->build())
->build();
$tumbleDrying = AttributeLocalizedEnumValueBuilder::of()
->withKey("tumbleDrying" )
->withLabel(LocalizedStringBuilder::fromArray(["en" => "Tumble Drying" , "de" => "Trommeltrocknen" ])->build())
->build();
$noTumbleDrying = AttributeLocalizedEnumValueBuilder::of()
->withKey("noTumbleDrying" )
->withLabel(LocalizedStringBuilder::fromArray(["en" => "no tumble drying" , "de" => "Nicht im Trommeltrockner trocknen" ])->build())
->build();
$laundryLabelType = AttributeSetTypeBuilder::of()
->withElementType(AttributeLocalizedEnumTypeBuilder::of()
->withValues(AttributeLocalizedEnumValueCollection::fromArray([$cold, $hot, $tumbleDrying, $noTumbleDrying]))
->build())
->build();
$laundrySymbols = AttributeDefinitionDraftBuilder::of()
->withType($laundryLabelType)
->withName(self ::LAUNDRY_SYMBOLS_ATTR_NAME)
->withLabel(LocalizedStringBuilder::fromArray(["en" => "washing labels" ])->build())
->withIsRequired(false )
->build();
$matchingProducts = AttributeDefinitionDraftBuilder::of()
->withName(self ::MATCHING_PRODUCTS_ATTR_NAME)
->withLabel(LocalizedStringBuilder::fromArray(["en" => "matching products" ])->build())
->withType(AttributeSetTypeBuilder::of()
->withElementType(AttributeReferenceTypeBuilder::of()
->withReferenceTypeId("product" )
->build())
->build())
->withIsRequired(false )
->build();
$rrp = AttributeDefinitionDraftBuilder::of()
->withName(self ::RRP_ATTR_NAME)
->withLabel(LocalizedStringBuilder::fromArray(["en" => "recommended retail price" ])->build())
->withType(AttributeMoneyTypeBuilder::of()->build())
->withIsRequired(false )
->build();
$availableSince = AttributeDefinitionDraftBuilder::of()
->withName(self ::AVAILABLE_SINCE_ATTR_NAME)
->withLabel(LocalizedStringBuilder::fromArray(["en" => "available since" ])->build())
->withType(AttributeDateTimeTypeBuilder::of()->build())
->withIsRequired(false )
->build();
$attributes = AttributeDefinitionDraftCollection::fromArray([$color, $size, $laundrySymbols, $matchingProducts, $rrp, $availableSince]);
$productTypeDraft = ProductTypeDraftBuilder::of()
->withKey(ProductTypeFixture::uniqueProductTypeString())
->withName(self ::PRODUCT_TYPE_NAME)
->withDescription("a 'T' shaped cloth" )
->withAttributes($attributes)
->build();
$productType = $builder
->with()
->productTypes()
->post($productTypeDraft)
->execute();
$productType = $builder
->with()
->productTypes()
->get()
->withQueryParam('where' , 'name="' . $name . '"' )
->execute();
return $productType->getResults()->current() ?: null ;
ProductVariantDraftBuilder::of()->withAttributes($attributes)
$attributes = AttributeCollection::of()
->add(
AttributeBuilder::of()
->withName(self ::ISBN_ATTR_NAME)
->withValue("978-3-86680-192-9" )
->build());
$productVariantDraft = ProductVariantDraftBuilder::of()
->withAttributes($attributes)
->build();
$productTypeResourceIdentifier = ProductTypeResourceIdentifierBuilder::of()
->withId($productType->getId())
->build();
$productDraft = ProductDraftBuilder::of()
->withProductType($productTypeResourceIdentifier)
->withName(LocalizedStringBuilder::of()->put("en" , "a book" )->build())
->withSlug(LocalizedStringBuilder::of()->put("en" , ProductTypeFixture::uniqueProductTypeString())->build())
->withMasterVariant($productVariantDraft)
->build();
$product = $builder->products()
->post($productDraft)
->execute();
$referenceableProduct = ProductFixture::referenceableProduct($builder);
$productType = ProductTypeFixture::fetchProductTypeByName($builder, self ::PRODUCT_TYPE_NAME);
if (!$productType) {
$productType = ProductTypeFixture::createProductType($builder, self ::PRODUCT_TYPE_NAME);
}
$productReference = ProductReferenceBuilder::of()->withId($referenceableProduct->getId())->build();
$datetime = new \DateTime('2015-02-02' );
$datetime = $datetime->format(\DateTime::ATOM);
$attributes = AttributeCollection::of()
->add(AttributeBuilder::of()->withName(self ::COLOR_ATTR_NAME)->withValue("green" )->build())
->add(AttributeBuilder::of()->withName(self ::SIZE_ATTR_NAME)->withValue("S" )->build())
->add(AttributeBuilder::of()->withName(self ::LAUNDRY_SYMBOLS_ATTR_NAME)->withValue(["cold" , "tumbleDrying" ])->build())
->add(AttributeBuilder::of()->withName(self ::RRP_ATTR_NAME)->withValue(MoneyBuilder::of()->withCentAmount(300 )->withCurrencyCode("EUR" )->build())->build())
->add(AttributeBuilder::of()->withName(self ::AVAILABLE_SINCE_ATTR_NAME)->withValue($datetime)->build())
->add(AttributeBuilder::of()->withName(self ::MATCHING_PRODUCTS_ATTR_NAME)->withValue([$productReference])->build());
$productVariantDraft = ProductVariantDraftBuilder::of()
->withAttributes($attributes)
->build();
$productTypeResourceIdentifier = ProductTypeResourceIdentifierBuilder::of()
->withId($productType->getId())
->build();
$productDraft = ProductDraftBuilder::of()
->withProductType($productTypeResourceIdentifier)
->withKey(ProductFixture::uniqueProductString())
->withName(LocalizedStringBuilder::of()->put('en' , 'basic shirt' )->build())
->withSlug(LocalizedStringBuilder::of()->put('en' , ProductFixture::uniqueProductString())->build())
->withMasterVariant($productVariantDraft)
->build();
$product = $builder->products()
->post($productDraft)
->execute();
$productType = $builder->productTypes()
->post($productTypeDraft)
->execute();
$productVariantDraft = ProductVariantDraftBuilder::of()
->withAttributes(AttributeCollection::of()
->add(AttributeBuilder::of()
->withName(self ::COLOR_ATTR_NAME)
->withValue(1 )
->build()))
->build();
$productTypeResourceIdentifier = ProductTypeResourceIdentifierBuilder::of()
->withId($productType->getId())
->build();
$productDraft = ProductDraftBuilder::of()
->withProductType($productTypeResourceIdentifier)
->withName(LocalizedStringBuilder::of()->put("en" , "basic shirt" )->build())
->withSlug(LocalizedStringBuilder::of()->put("en" , ProductTypeFixture::uniqueProductTypeString())->build())
->withMasterVariant($productVariantDraft)
$green = AttributeLocalizedEnumValueBuilder::of()
->withKey("green" )
->withLabel(LocalizedStringBuilder::of()->put("en" , "green " )->put("de" , "grün" )->build())
->build();
$cold = AttributeLocalizedEnumValueBuilder::of()
->withKey("cold" )
->withLabel(LocalizedStringBuilder::of()->put("en" , "Wash at or below 30°C " )->put("de" , "30°C" )->build())
->build();
$tumbleDrying = AttributeLocalizedEnumValueBuilder::of()
->withKey("tumbleDrying" )
->withLabel(LocalizedStringBuilder::of()->put("en" , "tumble drying" )->put("de" , "Trommeltrocknen" )->build())
->build();
$productReference = ProductReferenceBuilder::of()->withId($referenceableProduct->getId())->build();
$attributes = AttributeCollection::of()
->add(AttributeBuilder::of()->withName(self ::COLOR_ATTR_NAME)->withValue("green" )->build())
->add(AttributeBuilder::of()->withName(self ::SIZE_ATTR_NAME)->withValue("S" )->build())
->add(AttributeBuilder::of()->withName(self ::LAUNDRY_SYMBOLS_ATTR_NAME)->withValue(["cold" , "tumbleDrying" ])->build())
->add(AttributeBuilder::of()->withName(self ::RRP_ATTR_NAME)->withValue(MoneyBuilder::of()->withCentAmount(300 )->withCurrencyCode("EUR" )->build())->build())
->add(AttributeBuilder::of()->withName(self ::AVAILABLE_SINCE_ATTR_NAME)->withValue($datetime)->build())
->add(AttributeBuilder::of()->withName(self ::MATCHING_PRODUCTS_ATTR_NAME)->withValue([$productReference])->build());
$productVariantDraft = ProductVariantDraftBuilder::of()
->withAttributes($attributes)
->build();
$productTypeResourceIdentifier = ProductTypeResourceIdentifierBuilder::of()
->withId($productType->getId())
->build();
$productDraft = ProductDraftBuilder::of()
->withProductType($productTypeResourceIdentifier)
->withKey(ProductFixture::uniqueProductString())
->withName(LocalizedStringBuilder::of()->put('en' , 'basic shirt' )->build())
->withSlug(LocalizedStringBuilder::of()->put('en' , ProductFixture::uniqueProductString())->build())
->withMasterVariant($productVariantDraft)
->build();
$product = $builder->products()
->post($productDraft)
->execute();
$masterVariant = $product->getMasterData()->getStaged()->getMasterVariant();
foreach ($masterVariant->getAttributes() as $attribute) {
if ($attribute->getName() === self ::COLOR_ATTR_NAME) {
assertEquals($attribute->getValue()->key, "green" );
}
if ($attribute->getName() === self ::SIZE_ATTR_NAME) {
assertEquals($attribute->getValue()->key, "S" );
}
$attribute->getValue()
$product = $this ->createProduct();
$masterVariant = $product->getMasterData()->getStaged()->getMasterVariant();
foreach ($masterVariant->getAttributes() as $attribute) {
if ($attribute->getName() === self ::SIZE_ATTR_NAME) {
assertEquals($attribute->getValue()->key, "S" );
}
}
getValueAs()
$product = $builder->products()->post($productDraft)->execute();
$masterVariant = $product->getMasterData()->getStaged()->getMasterVariant();
$result = null ;
foreach ($masterVariant->getAttributes() as $attribute) {
if ($attribute->getName() === self ::SIZE_ATTR_NAME) {
$attrAccessor = $attribute->with(AttributeAccessor::of());
$result = $attrAccessor->getValueAsBool();
}
}
$this ->assertIsBool($result);
$product = $this ->createBookProduct();
$masterVariantId = 1 ;
$productUpdate = ProductUpdateBuilder::of()
->withVersion($product->getVersion())
->withActions(
ProductUpdateActionCollection::fromArray([
ProductSetAttributeActionBuilder::of()
->withVariantId($masterVariantId)
->withName(self ::ISBN_ATTR_NAME)
->withValue("978-3-86680-192-8" )
->build()
])
)->build();
$productUpdated = $builder
->products()
->withId($product->getId())
->post($productUpdate)
->execute();
$masterVariant = $productUpdated->getMasterData()->getStaged()->getMasterVariant();
$attribute = ProductTypeFixture::findAttributes($masterVariant->getAttributes(), self ::ISBN_ATTR_NAME);
assertEquals($attribute->getValue(), "978-3-86680-192-8" );
$masterVariantId = 1 ;
$productUpdatedAction = ProductUpdateBuilder::of()
->withVersion($product->getVersion())
->withActions(
ProductUpdateActionCollection::fromArray([
ProductSetAttributeActionBuilder::of()
->withVariantId($masterVariantId)
->withName(self ::COLOR_ATTR_NAME)
->withValue("red" )
->build(),
ProductSetAttributeActionBuilder::of()
->withVariantId($masterVariantId)
->withName(self ::SIZE_ATTR_NAME)
->withValue("M" )
->build(),
ProductSetAttributeActionBuilder::of()
->withVariantId($masterVariantId)
->withName(self ::LAUNDRY_SYMBOLS_ATTR_NAME)
->withValue(["cold" ])
->build(),
ProductSetAttributeActionBuilder::of()
->withVariantId($masterVariantId)
->withName(self ::RRP_ATTR_NAME)
->withValue(MoneyBuilder::of()->withCurrencyCode("EUR" )->withCentAmount(2000 )->build())
->build(),
])
)->build();
$productUpdated = $builder
->with()
->products()
->withId($product->getId())
->post($productUpdatedAction)
->execute();
$attributesUpdatedProduct = $productUpdated->getMasterData()->getStaged()->getMasterVariant()->getAttributes();
self ::assertEquals(ProductTypeFixture::findAttribute($attributesUpdatedProduct, self ::SIZE_ATTR_NAME)->getValue()->key, "M" );
self ::assertEquals(ProductTypeFixture::findAttribute($attributesUpdatedProduct, self ::COLOR_ATTR_NAME)->getValue()->key, "red" );
self ::assertEquals(ProductTypeFixture::findAttribute($attributesUpdatedProduct, self ::LAUNDRY_SYMBOLS_ATTR_NAME)->getValue()[0 ]->key, "cold" );
self ::assertEquals(ProductTypeFixture::findAttribute($attributesUpdatedProduct, self ::RRP_ATTR_NAME)->getValue()->centAmount, 2000 );
$product = $this ->createProduct($builder);
$attributes = AttributeCollection::of()
->add(AttributeBuilder::of()->withName(self ::COLOR_ATTR_NAME)->withValue("yellow" )->build())
->add(AttributeBuilder::of()->withName(self ::RRP_ATTR_NAME)->withValue(MoneyBuilder::of()->withCurrencyCode("EUR" )->withCentAmount(30 )->build())->build());
$productVariantImportDraft = ProductVariantImportDraftBuilder::of()
->withId(1 )
->withAttributes($attributes)
->build();
$lineItemImportDraft = LineItemImportDraftBuilder::of()
->withProductId($product->getId())
->withVariant($productVariantImportDraft)
->withQuantity(1 )
->withPrice(ProductFixture::priceDraft())
->withName(LocalizedStringBuilder::of()->put("en" , "product name" )->build())
->build();
$orderImportDraft = OrderImportDraftBuilder::of()
->withLineItems(LineItemImportDraftCollection::of()->add($lineItemImportDraft))
->withTotalPrice(MoneyBuilder::of()->withCentAmount(20 )->withCurrencyCode("EUR" )->build())
->withOrderState(OrderState::COMPLETE)
->build();
$order = $builder->orders()
->importOrder()
->post($orderImportDraft)
->execute();
$productVariant = $order->getLineItems()->current()->getVariant();
$colorAttribute = ProductTypeFixture::findAttribute($productVariant->getAttributes(), self ::COLOR_ATTR_NAME);
assertEquals("yellow" , $colorAttribute->getValue());
$rrpAttribute = ProductTypeFixture::findAttribute($productVariant->getAttributes(), self ::RRP_ATTR_NAME);
assertEquals(30 , $rrpAttribute->getValue()->centAmount);
$messagePayload = new MessageDeliveryPayloadModel(
"{projectKey}" ,
null ,
null ,
"uniqueId456" ,
1 ,
new DateTimeImmutable("2024-08-06T12:34:56+00:00" ),
new DateTimeImmutable("2024-08-06T12:34:56+00:00" ),
42 ,
1 ,
null ,
"Message"
);
$messagePayloadJSON = json_encode($messagePayload);