Weave Code
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

Commercetools Api Reference Laravel Package

commercetools/commercetools-api-reference

Official API reference for the commercetools platform. Includes models, endpoints, schemas, and examples to help you explore and integrate commercetools services, keeping your client implementations aligned with the latest API definitions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Clone or include the package via Composer (if available) or use the official commercetools API reference docs as a standalone guide. Since this is a documentation package, no direct Composer installation exists—focus on integrating the API reference into your workflow:

    # No direct install, but reference the docs:
    composer require --dev commercetools/commercetools-api-reference  # Hypothetical (check for updates)
    
  2. First Use Case

    • Scenario: Fetch product data via the commercetools API.
    • Steps:
      1. Navigate to the Products API reference in the package/docs.
      2. Identify the endpoint: GET /{projectKey}/products.
      3. Use Laravel’s HTTP client (e.g., Http::get()) to call the API with your auth token:
        $response = Http::withToken($commercetoolsAuthToken)
            ->get("https://api.europe-west1.gcp.commercetools.com/{projectKey}/products");
        
  3. Where to Look First


Implementation Patterns

Workflows

  1. CRUD Operations

    • Create: Use the Products: Create endpoint.
      $productData = [
          'name' => ['en' => 'Laravel Hoodie'],
          'masterVariant' => ['sku' => 'LARAVEL-001', 'prices' => [...]],
      ];
      $response = Http::post("/{projectKey}/products", $productData);
      
    • Update: Patch via Products: Update.
      $patchOps = [
          ['op' => 'replace', 'path' => '/name/en', 'value' => 'Updated Hoodie']
      ];
      $response = Http::patch("/{projectKey}/products/{productId}", $patchOps);
      
  2. Pagination & Filtering

    • Leverage query params like ?limit=100&where=name=en%22Laravel%22 in your Laravel requests.
    • Example:
      $products = Http::get("/{projectKey}/products", [
          'limit' => 50,
          'where' => 'categories.id=some-category-id'
      ]);
      
  3. Webhooks for Real-Time Updates

    • Use the Webhooks API to trigger Laravel events.
    • Laravel Example:
      // In a service class
      public function handleWebhook($payload) {
          event(new \App\Events\CommercetoolsWebhookReceived($payload));
      }
      

Integration Tips

  • Laravel Service Providers: Centralize API calls in a provider:
    // app/Providers/CommercetoolsServiceProvider.php
    public function register() {
        $this->app->singleton('commercetools', function () {
            return new CommercetoolsClient(config('commercetools'));
        });
    }
    
  • Caching Responses: Cache frequent API calls (e.g., product lists) with Laravel’s cache:
    $products = Cache::remember("commercetools_products_{$projectKey}", now()->addHours(1), function () {
        return Http::get("/{projectKey}/products")->json();
    });
    
  • Error Handling: Normalize API errors into Laravel exceptions:
    try {
        $response = Http::get('/products')->throw();
    } catch (\Illuminate\Http\Client\ConnectionException $e) {
        throw new \App\Exceptions\CommercetoolsApiException('Connection failed', $e);
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication Quirks

    • Token Expiry: commercetools tokens expire (typically 1 hour). Implement token refresh logic:
      // Refresh token if expired
      if (Carbon::parse($token['expires_at'])->isPast()) {
          $token = $this->refreshCommercetoolsToken();
      }
      
    • Project Key Mismatch: Double-check {projectKey} in endpoints—404 errors often stem from this.
  2. Rate Limiting

    • commercetools enforces rate limits. Handle 429 Too Many Requests:
      $response = Http::retry(3, 100)->get('/products'); // Retry with delay
      
  3. Localization Pitfalls

    • Language Codes: Ensure locale codes (e.g., en-US) match your data model. Use setlocale() or constants:
      const LOCALE_EN_US = 'en-US';
      

Debugging

  • API Explorer: Use the API Explorer to validate requests before coding.
  • Logging: Log raw requests/responses for debugging:
    Http::withOptions(['debug' => true])->get('/products');
    
  • Postman Collections: Import commercetools’ Postman collection for local testing.

Extension Points

  1. Custom API Clients

    • Extend Laravel’s HTTP client with middleware for:
      • Automatic token attachment.
      • Request/response logging.
      • Custom headers (e.g., X-Commercetools-Api-Version: 2023-05).
    // app/Http/Middleware/CommercetoolsAuth.php
    public function handle($request, Closure $next) {
        $request->headers->set('Authorization', 'Bearer '.$this->getToken());
        return $next($request);
    }
    
  2. Local Development

    • Use commercetools/sdk for local testing:
      composer require commercetools/sdk
      
    • Mock responses with Laravel’s Http::fake():
      Http::fake([
          'api.commercetools.com/*' => Http::response(['data' => [...]], 200),
      ]);
      
  3. Webhook Validation

    • Validate webhook signatures using the HMAC secret:
      use Illuminate\Support\Facades\Http;
      use Illuminate\Support\Str;
      
      $signature = $request->header('X-Commercetools-Signature');
      $expected = hash_hmac('sha256', $request->getContent(), config('commercetools.webhook_secret'));
      if (!hash_equals($signature, $expected)) {
          abort(401);
      }
      
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.
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin