Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Sdk Laravel Package

commercetools/php-sdk

Deprecated PHP SDK for commercetools Composable Commerce. Provides native PHP models/helpers, IDE autocompletion, object mapping, i18n, and an OAuth2 client with caching and async/concurrent request support. Requires PHP 5.6+ (Guzzle).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require commercetools/php-sdk
    

    (Note: Only use this for legacy projects; migrate to PHP SDK V2 for new projects.)

  2. Configure Client Create a client instance in config/services.php:

    'commercetools' => [
        'client_id' => env('CT_CLIENT_ID'),
        'client_secret' => env('CT_CLIENT_SECRET'),
        'token_url' => env('CT_TOKEN_URL'),
        'api_url' => env('CT_API_URL'),
        'project_key' => env('CT_PROJECT_KEY'),
        'cache' => [
            'enabled' => env('CT_CACHE_ENABLED', false),
            'ttl' => env('CT_CACHE_TTL', 300),
        ],
    ],
    

    Register a service provider in config/app.php:

    Commercetools\Client\Provider::class,
    
  3. First Use Case: Fetch a Product

    use Commercetools\Client\ClientBuilder;
    use Commercetools\Client\Http\GuzzleHttpClient;
    
    $client = ClientBuilder::withClientCredentialsFlow(
        env('CT_CLIENT_ID'),
        env('CT_CLIENT_SECRET'),
        env('CT_TOKEN_URL')
    )->withProjectKey(env('CT_PROJECT_KEY'))
    ->withHttpClient(new GuzzleHttpClient())
    ->build();
    
    $product = $client->getById('products', '12345678-1234-1234-1234-123456789012');
    

Implementation Patterns

Core Workflows

  1. CRUD Operations Use fluent methods for common actions:

    // Create
    $product = $client->create('products', $productData);
    
    // Update
    $updatedProduct = $client->update('products', $product->getId(), $updateActions);
    
    // Delete
    $client->delete('products', $product->getId());
    
  2. Querying with Search Leverage the Search class for complex queries:

    $search = new \Commercetools\Client\Search();
    $search->addQuery('name:test-product');
    $search->addSort('name asc');
    $results = $client->search('products', $search);
    
  3. Handling Responses Use Response objects for metadata (e.g., pagination, warnings):

    $response = $client->search('products', $search);
    $totalPages = $response->getTotalPages();
    
  4. Bulk Operations

    $bulkOperation = new \Commercetools\Client\BulkOperation();
    $bulkOperation->addAction('products', '123', 'setPrice', ['value' => ['centAmount' => 1000]]);
    $results = $client->executeBulk($bulkOperation);
    

Integration Tips

  • Laravel Service Container Bind the client to the container for dependency injection:

    $this->app->singleton('commercetools.client', function ($app) {
        return ClientBuilder::withClientCredentialsFlow(
            $app['config']['commercetools.client_id'],
            $app['config']['commercetools.client_secret'],
            $app['config']['commercetools.token_url']
        )->withProjectKey($app['config']['commercetools.project_key'])
         ->withHttpClient(new GuzzleHttpClient())
         ->build();
    });
    
  • Middleware for Auth Extend the ClientBuilder to add custom middleware (e.g., logging):

    $clientBuilder->withMiddleware(function ($request, $next) {
        $request->getHeaders()->add('X-Custom-Header', 'value');
        return $next($request);
    });
    
  • Model Validation Use Validation helpers for request payloads:

    use Commercetools\Client\Validation\Validation;
    
    $errors = Validation::validateProduct($productData);
    if (!empty($errors)) {
        throw new \InvalidArgumentException(implode(', ', $errors));
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning

    • The SDK is deprecated as of September 1, 2022. Avoid using it in new projects.
    • Migration Path: Use PHP SDK V2 with its improved type safety and async support.
  2. Token Management

    • Tokens expire; handle 401 Unauthorized errors by refreshing the client:
      try {
          $client->getById('products', $id);
      } catch (\Commercetools\Client\Exception\UnauthorizedException $e) {
          $client->refreshToken();
          retry logic...
      }
      
  3. Pagination Quirks

    • Always check Response::getTotalPages() and Response::getTotalResults() to avoid missing data:
      $page = 1;
      do {
          $results = $client->search('products', $search->withPage($page));
          $page++;
      } while ($page <= $response->getTotalPages());
      
  4. Case Sensitivity

    • API keys (e.g., projectKey) are case-sensitive in requests. Ensure consistency:
      $client->withProjectKey(strtoupper(env('CT_PROJECT_KEY'))); // if needed
      
  5. Cache Invalidation

    • The built-in cache (CacheMiddleware) does not auto-invalidate. Clear it manually after writes:
      $client->getCache()->clear();
      

Debugging Tips

  1. Enable Verbose Logging Add a middleware to log requests/responses:

    $clientBuilder->withMiddleware(function ($request, $next) {
        \Log::debug('Request:', [
            'url' => (string) $request->getUri(),
            'method' => $request->getMethod(),
            'headers' => $request->getHeaders(),
            'body' => $request->getBody(),
        ]);
        $response = $next($request);
        \Log::debug('Response:', [
            'status' => $response->getStatusCode(),
            'body' => (string) $response->getBody(),
        ]);
        return $response;
    });
    
  2. Validate API Responses Use Response::isSuccessful() to check for errors:

    $response = $client->search('products', $search);
    if (!$response->isSuccessful()) {
        throw new \RuntimeException('API Error: ' . $response->getReasonPhrase());
    }
    
  3. Handle Rate Limits Implement exponential backoff for 429 Too Many Requests:

    use Symfony\Component\Stopwatch\Stopwatch;
    
    $stopwatch = new Stopwatch();
    $event = $stopwatch->start('api_call');
    
    try {
        $response = $client->getById('products', $id);
    } catch (\Commercetools\Client\Exception\TooManyRequestsException $e) {
        $retryAfter = $e->getRetryAfter();
        $event->stop();
        sleep($retryAfter);
        $event->start('retry');
        $response = $client->getById('products', $id);
    }
    

Extension Points

  1. Custom Models Extend base models (e.g., Product) to add business logic:

    class CustomProduct extends \Commercetools\Client\Model\Product
    {
        public function getFormattedPrice()
        {
            return '$' . ($this->getPrice()->getValue()->getCentAmount() / 100);
        }
    }
    
  2. Event Subscriptions Use the Eventing module to listen for Composable Commerce events:

    $client->getEventing()->subscribe('OrderCreated', function ($event) {
        \Log::info('New order:', $event->getPayload());
    });
    
  3. Custom HTTP Clients Replace the default GuzzleHttpClient with a custom implementation (e.g., for signing requests):

    $clientBuilder->withHttpClient(new class extends \Commercetools\Client\Http\HttpClient {
        public function send(RequestInterface $request)
        {
            // Custom logic (e.g., add signature)
            return parent::send($request);
        }
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names