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

Shopware Sdk Laravel Package

vin-sw/shopware-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require vin-sw/shopware-sdk
    

    For Laravel 8+, use the Laravel Shopware SDK Adapter for seamless integration.

  2. Initialize the Client

    use VinSw\ShopwareSdk\Client;
    
    $client = new Client(
        'https://your-shopware-store.com/api/v3',
        'api-key',
        'api-secret'
    );
    
  3. First Use Case: Fetch Products

    $products = $client->product()->getList();
    foreach ($products as $product) {
        echo $product->getName();
    }
    

Where to Look First

  • Examples Folder: The repository includes practical examples in the examples directory.
  • API Documentation: The SDK mirrors Shopware 6’s DAL syntax, so refer to Shopware’s official API docs for entity structures.
  • Laravel Adapter: If using Laravel, the adapter simplifies dependency injection and configuration.

Implementation Patterns

CRUD Operations

Create/Update/Delete Entities

// Create a product
$product = $client->product()->create([
    'name' => 'Test Product',
    'price' => ['gross' => 19.99],
]);

// Update a product
$product->setName('Updated Product')->save();

// Delete a product
$client->product()->delete($product->getId());

Sync API for Bulk Operations

// Sync products (e.g., import/export)
$client->product()->sync([
    'updates' => [
        ['id' => 1, 'name' => 'Updated Name'],
    ],
    'deletes' => [2, 3],
]);

Admin Search

// Search products with filters
$results = $client->search()->execute([
    'entity' => 'product',
    'criteria' => [
        'filters' => [
            ['type' => 'equals', 'field' => 'name', 'value' => 'Test'],
        ],
    ],
]);

Webhooks

Register a Webhook

$webhook = $client->webhook()->create([
    'name' => 'Order Webhook',
    'url' => 'https://your-app.com/webhook',
    'events' => ['OrderStateChangedEvent'],
]);

// Handle incoming webhooks (use the `WebhookReceiver` class)
$receiver = new \VinSw\ShopwareSdk\Webhook\WebhookReceiver($client);
$receiver->handle($request); // Laravel route handler

Integration with Laravel

Service Provider Setup

// config/services.php
'shopware' => [
    'api_url' => env('SHOPWARE_API_URL'),
    'api_key' => env('SHOPWARE_API_KEY'),
    'api_secret' => env('SHOPWARE_API_SECRET'),
],

// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->singleton(\VinSw\ShopwareSdk\Client::class, function ($app) {
        return new Client(
            config('services.shopware.api_url'),
            config('services.shopware.api_key'),
            config('services.shopware.api_secret')
        );
    });
}

Usage in Controllers

use VinSw\ShopwareSdk\Client;

class ShopwareController extends Controller
{
    public function __construct(private Client $client) {}

    public function fetchProducts()
    {
        $products = $this->client->product()->getList();
        return view('products.index', compact('products'));
    }
}

Gotchas and Tips

Pitfalls

  1. API Version Mismatch

    • The SDK supports Shopware 6.4 (1.x) and 6.5+ (2.x). Ensure you use the correct version to avoid schema errors.
    • Example: If using 2.x with Shopware 6.4, some endpoints may fail.
  2. Authentication Issues

    • Always verify your API key and secret. Use the AdminApi class for admin operations:
      $adminApi = $client->adminApi('sales_channel_id');
      
    • For webhooks, ensure the url and events are correctly configured in Shopware’s backend.
  3. Rate Limiting

    • Shopware’s API may throttle requests. Implement retries with exponential backoff:
      try {
          $response = $client->product()->getList();
      } catch (\VinSw\ShopwareSdk\Exception\RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  4. Nested Entity Handling

    • Some entities (e.g., product) have nested associations (e.g., price, cover). Ensure you load them explicitly:
      $product = $client->product()->get(1, ['associations' => ['cover']]);
      

Debugging Tips

  1. Enable Debug Mode Add this to your Client initialization to log requests:

    $client = new Client(..., ..., true); // Enable debug
    

    Check logs in storage/logs/laravel.log.

  2. Validate Responses Use getErrors() to inspect API errors:

    try {
        $client->product()->create([...]);
    } catch (\VinSw\ShopwareSdk\Exception\ApiException $e) {
        dd($e->getErrors()); // Debug validation errors
    }
    
  3. Webhook Testing

    • Use Shopware’s Webhook Tester in the admin panel to simulate events.
    • Verify payloads match Shopware’s event documentation.

Extension Points

  1. Custom Entities Extend the SDK for unsupported entities by creating a custom service:

    class CustomEntityService extends \VinSw\ShopwareSdk\Service\AbstractService
    {
        protected $entityName = 'custom_entity';
        protected $associationMappings = [...];
    }
    
  2. Middleware for Requests Add custom logic to requests/responses by extending the Client:

    class CustomClient extends Client
    {
        public function getHttpClient()
        {
            $client = parent::getHttpClient();
            $client->getMiddleware()->push(
                \GuzzleHttp\Middleware::tap(function ($request) {
                    // Modify request (e.g., add headers)
                })
            );
            return $client;
        }
    }
    
  3. Laravel Service Container Bind the SDK to Laravel’s container for dependency injection:

    $this->app->bind(\VinSw\ShopwareSdk\Client::class, function ($app) {
        return new CustomClient(
            config('services.shopware.api_url'),
            config('services.shopware.api_key'),
            config('services.shopware.api_secret')
        );
    });
    

Performance Tips

  1. Batch Operations Use sync() for bulk updates/deletes instead of individual CRUD calls.

  2. Criteria Optimization Limit loaded associations to reduce payload size:

    $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Criteria();
    $criteria->addAssociation('cover');
    $criteria->addAssociation('price');
    $products = $client->product()->getList($criteria);
    
  3. Caching Cache frequent API calls (e.g., product lists) using Laravel’s cache:

    $products = Cache::remember('shopware_products', now()->addHours(1), function () {
        return $client->product()->getList();
    });
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager