Shopware PHP SDK is a simple SDK implementation of Shopware 6 APIs

Overview

Shopware 6 PHP SDK

php

GitHub Release Latest Version on Packagist Software License

Shopware PHP SDK is a simple SDK implementation of Shopware 6 APIs. It helps to access the API in an object-oriented way.

If you're familiar with Shopware 6 DAL syntax and how to retrieve it you might see this example is predictable and straightforward

image

Installation

Install with Composer

composer require vin-sw/shopware-sdk

The SDK main features:

  • Admin API

    • CRUD API
    • Sync Api
    • Other services
    • ... (TODO)
  • Webhook helper

    • Webhook registration
    • Webhook authentication
    • Webhook receiver

Usage

More in the examples folder, for integrating the sdk in an App, have a look at this repository

Admin Authentication

  • Supported 3 grant types, you can create one of these 3 grant type for authentication:

Using Password grant type

$grantType = new PasswordGrantType($username, $password);

Using Client credential grant type

$grantType = new ClientCredentialsGrantType($clientId, $clientSecret);

Using Refresh token grant type

$grantType = new RefreshTokenGrantType($refreshToken);

Or dynamically via

$grantType = GrantType::createFromConfig($config);

Check the authentication example for the reference.

After having a GrantType object, you can fetch the admin's access token using the AdminAuthenticator

$adminClient = new AdminAuthenticator($grantType, $shopUrl);
$accessToken = $adminClient->fetchAccessToken();
$context = new Context($shopUrl, $accessToken);

Notice: You might want to store the access token object into the database so you can create the object without request for another access token for every Admin API request.

Working with Criteria and Repositories

It's pretty identical to what you expected when working with Shopware's core or repositories in the SW administration.

This is an example to retrieve a product that have free shipping

// Create the repository for the entity
$productRepository = RepositoryFactory::create(ProductDefinition::ENTITY_NAME);

// Create the criteria
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('shippingFree', true));

// Using this criteria and the context object that you create from authentication step, you can retrieving the result
$products = $productRepository->search($criteria, $context);

Each shopware's entity is mapped into Entity and Collection Classes which can be found in Data/Entity so you can easily access their properties when retrieving data from Admin API.

Support methods get, search, searchIds, create, update, delete, syncDeleted, createVersion, mergeVersion, deleteVersion, clone, schema. Each method requires a Context object

Check examples/entity-repository.php for some useful references.

Working with API Services

An ApiService requires a Context object as its first argument. Check examples/sync-service.php or examples/info-service.php for some references.

Change log

Please see CHANGELOG for more information on what has changed recently.

Working with Webhook

Contribution

Feels free to create an issue on Github issues page or contact me directly at [email protected]

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Requirements

  • ext-curl
  • PHP 7.4
  • SW >= 6.4

This SDK is mainly dedicated to Shopware 6.4 and onwards, earlier SW application may still be usable without test

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Don't cache entities

    Don't cache entities

    Right now hydrated entities are cached in \Vin\ShopwareSdk\Repository\Traits\EntityHydrator::hydrateEntity

    $cacheKey = $entityRaw['type'] . '-' . $entityRaw['id']; if (array_key_exists($cacheKey, $this->cache)) { return $this->cache[$cacheKey]; }

    This should imo get removed without replacement. I'd not expect the SDK to do caching for me. In case I want caching I could easily implement it on my own.

    There are some downsides of caching:

    • If you search for an entity without associations and later on search for the same entity with association, the "new" hydrated entity is actually the old one without the associations added -> this is what took me quite some time to figure out.

    • If you use some web server that doesn't end the PHP progress after the request has been finished this value will be cached forever. Even if the next request comes in after minutes/days/weeks the old value of that entity is still cached. I know common webservers like Apache or Nginx with PHP-FPM start a new process with each request - but new approaches are coming and get more and more popular (Swoole, Roadrunner).

    Like I said I don't think caching is necessary (the request to actually get the entity data from Shopware is probably much slower than hydrating the entity) so I'd remove it. In case you think caching should still be present it would be nice to be able to enable/disable it (via Context flag?) or at least to clear it (via method call).

    === Another proposal related: For now I'd like to replace the method hydrateEntity with my own. If hydrateEntity would be public, EntityHydrator would be a class that get's initialized by some factory and injected to the EntityRepository this would be quite easy. But as hydrateEntity is a private trait method inside a Trait which is hardly coupled to EntityRepository this is a bit tricky to do. In general I'd suggest - at least for a library - to avoid Traits and rely on DI instead.

    === PR: https://github.com/vienthuong/shopware-php-sdk/pull/47

    enhancement 
    opened by ckilb 5
  • Criteria Limit Improvement

    Criteria Limit Improvement

    Currently, it is not possible to set criteria limit to null.

    But this should be possible to allow lists without pagination: https://github.com/shopware/platform/blob/7ed33d9f1ba28888eec93b3ff4f9ba141790a32e/src/Core/Framework/DataAbstractionLayer/Dbal/EntityReader.php#L369

    Notice that you're no longer able to determinate this clause if null is an allowed value: https://github.com/vienthuong/shopware-php-sdk/blob/91d0686a8ef22ba56b31fc7c572bdb161a960ce8/src/Data/Criteria.php#L310


    Bonus: Currently, it is not possible to pass a custom Criteria instance to any association (It's possible to set dedicated limit rates to each association): https://github.com/vienthuong/shopware-php-sdk/blob/91d0686a8ef22ba56b31fc7c572bdb161a960ce8/src/Data/Criteria.php#L150

    Maybe we should change addAssociation(string $path) to addAssociation(string $path ?Criteria $criteria = null) (which creates a new one if not passed to keep BC)?

    enhancement 
    opened by solverat 4
  • Error when trying to get Customers

    Error when trying to get Customers

    When I try to get Customers I get the following error: Vin\ShopwareSdk\Data\Struct::addExtension(): Argument #2 ($extension) must be of type Vin\ShopwareSdk\Data\Struct, null given, called When I use other entities such as ProductDefinition, the code works fine. Here is the code I used: `

        $customerRepository = RepositoryFactory::create(CustomerDefinition::ENTITY_NAME);        
        $grantType = new ClientCredentialsGrantType(Configure::read('Shopware.ACCESS_KEY_ID'), Configure::read('Shopware.ACCESS_KEY_SECRET'));
        $adminClient = new AdminAuthenticator($grantType, Configure::read('Shopware.BASE_URL'));
        $accessToken = $adminClient->fetchAccessToken();
    
        $context = new Context(Configure::read('Shopware.BASE_URL'), $accessToken);        
        
        $criteria = new Criteria();
        $customers = $customerRepository->search($criteria, $context)->getEntities();
    

    `

    bug 
    opened by olivero86 4
  • EntityRepository::searchIds does not throw ShopwareSearchResponseException

    EntityRepository::searchIds does not throw ShopwareSearchResponseException

    I am implementing an exception handling regarding missing privileges.

    During this, I noticed that EntityRepository::search does throw a ShopwareSearchResponseException, in case Guzzle returns a BadResponseException. I would expect the same from EntityRepository::searchIds, as the exception could also occur there.

    In my example the missing privilege was a manufacturer filter for the product.

    image

    image

    Cheers!

    enhancement 
    opened by TobiasGraml11 3
  • Circular reference

    Circular reference

    when eitities have circular references, relationships hydratation enters in an infinite loop...

    The fiw was to reserve cache key before hydrating the relationships.

    For example : Entity A has association to B Entity B has association to C Entity C has association to B

    opened by raphael-homann 3
  • EntityHydrator does a schema call for each entity

    EntityHydrator does a schema call for each entity

    If a search call is done with a custom definition, there will be a schema call for each entity of the results.

    The reason for this is, that the InfoService is instantiated for each entity.

    https://github.com/vienthuong/shopware-php-sdk/blob/196268493addaaae52b20356641e622bf107bedd/src/Repository/Traits/EntityHydrator.php#L18-L22

    The InfoService has a internal cache, but that cache is non static.

    Either the InfoService needs to be a singleton or cached somewhere (RepositoryFactory?) or the cache inside InfoService needs to be static.

    enhancement 
    opened by attrib 3
  • Delete relations via syncDeleted()

    Delete relations via syncDeleted()

    Hi,

    I am trying to delete relations between products and categories via syncDeleted(). I didn't find any working way to do it other than to change some code in your class and make a pull request today :) You can find more information on this topic in the pull request itself.

    Have a nice day!

    Dag

    opened by dag-inbase 3
  • Update EntityRepository.php

    Update EntityRepository.php

    Wrong ID mapping on syncDeleted()

    Based on this documentation:

    https://shopware.stoplight.io/docs/admin-api/ZG9jOjEyMzA4NTUx-bulk-payloads#deleting-relations

    it is currently not possible to clear out relations because of the predefined id key mapping here: https://github.com/vienthuong/shopware-php-sdk/blob/78874d2ed9d74d6e4365b423d0284421bb7f1fa8/src/Repository/EntityRepository.php#L157-L159

    I guess this might be the correct way it is intended to work:

    $repository->syncDeleted([ [ 'productId' => $product->id, 'optionId' => $option->id ] ], $context);

    So I removed the use of the $data variable, as seen in my pull request.

    opened by dag-inbase 3
  • Error, when trying to receive SystemConfig Entity - $configurationValue is of wrong type.

    Error, when trying to receive SystemConfig Entity - $configurationValue is of wrong type.

    When try to read one entry in the system configuration, like that:

    
    
    $systemConfigRepository = RepositoryFactory::create(SystemConfigDefinition::ENTITY_NAME);
    				
    $criteria = new Criteria();
    $criteria->setLimit(1);
    $criteria->addFilter(new EqualsFilter('configurationKey', 'MyFavApiTest.config.receiver'));
    				
    $result = $systemConfigRepository->search($criteria, $context);
    

    I get an error:

    Cannot assign string to property Vin\ShopwareSdk\Data\Entity\SystemConfig\SystemConfigEntity::$configurationValue of type ?array

    I changed configurationValue in SystemConfigEntity to data-type of string, and it is working. Is this really an error, or am I doing something wrong?

    Setup: Shop: Shopware 6.4.8.1 on PHP 8 App: Symfony 6 on PHP 8

    The one that produces the error, is the app.

    Thanks for all the good work, so far. It's a pleasure to work with that library.

    bug 
    opened by sfxon 3
  • How to solve method not allowed issue when get token?

    How to solve method not allowed issue when get token?

    I am getting error like this

    [production.ERROR: {"errors":[{"code":"0","status":"405","title":"Method Not Allowed","detail":"No route found for \u0022GET https:\/\/shopware6.mystore.me\/api\/oauth\/token\u0022: Method Not Allowed (Allow: POST)"}]} {"exception":"[object] (Vin\\ShopwareSdk\\Exception\\AuthorizationFailedException(code: 405)](url)
    
    [previous exception] [object] (GuzzleHttp\\Exception\\ClientException(code: 405): Client error: `POST http://shopware6.mystore.me/api/oauth/token` resulted in a `405 Method Not Allowed` response:
    {\"errors\":[{\"code\":\"0\",\"status\":\"405\",\"title\":\"Method Not Allowed\",\"detail\":\"No route found for \\u0022GET https:\\/\\/shop (truncated...)
     at /var/www/tf/shared/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113)
    

    Shopware store version: v6.4.6.1

    It was working earlier. I don't know this error from shopware after getting upgraded 1.3.2 to 1.3.3 when composer updated. How to solve this issue? Thanks

    bug 
    opened by NGPrakash-Techshetra 3
  • EntityCollection is returned for empty results

    EntityCollection is returned for empty results

    When using the repositories, I can't have explicit typehints, as the general one is returned for empty results. Would be great, if the correct collection class would be returned for the corresponding repository.

    Code:

    $criteria1 = new Criteria();
    $criteria1->setIds(['ca9f2ea7166c4ff58f42c2e100ca3fd5']);
    
    $criteria2 = new Criteria();
    $criteria2->setIds(['0134e8fa91da44c7b5418806d7b95c21']);
    
    /** @var CategoryCollection $categories */
    $categories1 = $this->categoryRepository
        ->search($criteria1, $this->context)
        ->getEntities();
    
    $categories2 = $this->categoryRepository
        ->search($criteria2, $this->context)
        ->getEntities();
    

    Result: image

    bug 
    opened by TobiasGraml11 2
  • GET Requests are not validated correctly

    GET Requests are not validated correctly

    Currently Shopware is using GET URLs with the parameters location-id and privileges these parameters are missing in the validation funtion, therefore the calculates hashes are wrong. Following a proposed fix in the file WebhookAuthenticator

    public static function authenticateGetRequest(string $shopSecret): bool { $queryString = $_SERVER['QUERY_STRING']; $queries = [];

        parse_str($queryString, $queries);
        
        $shop = new Shop($queries['shop-id'], $queries['shop-url'], $shopSecret);
    
        $queryString = sprintf(
            'shop-id=%s&shop-url=%s&timestamp=%s&sw-version=%s',
            $shop->getShopId(),
            $shop->getShopUrl(),
            $queries['timestamp'],
            $queries['sw-version'],
        );
    
        if (array_key_exists('sw-context-language', $queries) && array_key_exists('sw-context-language', $queries)) {
            $queryString = sprintf(
                'shop-id=%s&shop-url=%s&timestamp=%s&sw-version=%s&sw-context-language=%s&sw-user-language=%s',
                $shop->getShopId(),
                $shop->getShopUrl(),
                $queries['timestamp'],
                $queries['sw-version'],
                $queries['sw-context-language'],
                $queries['sw-user-language'],
            );
        }
    
        if (array_key_exists('location-id', $queries) && array_key_exists('privileges', $queries)) {
            $queryString = sprintf(
                'location-id=%s&privileges=%s',
                $queries['location-id'],
                urlencode($queries['privileges'])
            ) . '&' . $queryString;
        }
    
        $hmac = \hash_hmac('sha256', htmlspecialchars_decode($queryString), $shopSecret);
    
        return hash_equals($hmac, $queries['shopware-shop-signature']);
    }
    
    opened by bilobait-lohrmann 0
  • Does this sdk work with custom entities?

    Does this sdk work with custom entities?

    I tried to import my products which uses custom entities but without success. Then I tried to get a created product with my custom association also without success. So my question is does this sdk support custom extensions at all? I didn't find any documentation about that topic. Thanks

    enhancement help wanted 
    opened by almare 1
  • Iterate to many entitys

    Iterate to many entitys

    What is the common way to iterate through many entities, for example a thousand products or more?

    Now i do it in this way, but it feels not good, what is your solution?

    
        private function getProducts(): \Generator
        {
            $criteria = new Criteria();
            $productRepository = RepositoryFactory::create(ProductDefinition::ENTITY_NAME);
    
            do {
                $result = $productRepository->search($criteria, $this->getContext());
    
                /** @var ProductEntity $product */
                foreach ($result->getEntities() as $product) {
                    yield $product;
                }
                $criteria->setPage($criteria->getPage() + 1);
            } while (($result->count()) === $criteria->getLimit());
        }
    
    

    if i remove the limit with $criteria->setLimit(null); i got the Allowed memory size error

    enhancement help wanted performance 
    opened by okuehne 2
  • New Feature/Enhancement requests/ideas

    New Feature/Enhancement requests/ideas

    We've released the SDK for a while and as Shopware core is growing really fast as well, the SDK might get a bit out of date APIs, or lack features, using deprecated APIs, etc...

    So with this thread, I want to gather the ideas/solutions from the community or even improve PR to make the SDK better. Any comments/suggestions are welcomed and highly appreciated 🤝

    For bug issues, please create a new one so I can keep the track of them :)

    help wanted 
    opened by vienthuong 7
Releases(1.7.3)
Owner
Thuong Le
Shopware Developer
Thuong Le
Doctrine-like fixtures integration for Shopware 6.

Shopware 6 Fixtures Did you ever want to create and load Doctrine-like fixtures in your Shopware 6 plugin? Look no further! This plugin provides an ul

Familiy Office 0 Oct 29, 2021
Shopware plugin to show a variant switch on the product listing and within the (checkout) cart.

Variant switch for Shopware 6 A plugin for Shopware 6 Features Show variant switch on product listing card Variant switch when hovering a variant prop

Shape & Shift 17 Aug 26, 2022
PHP SDK for Checkout RESTful APIs

REST API SDK for PHP V2 To consolidate support across various channels, we have currently turned off the feature of GitHub issues. Please visit https:

PayPal 400 Nov 29, 2022
PHP SDK for PayPal RESTful APIs

Deprecation Notice: This SDK is deprecated. You can continue to use it, but no new features or support requests will be accepted. For alternatives, pl

PayPal 2.1k Jan 5, 2023
PHP library/SDK for Crypto APIs 2.0 using Guzzle version 7

cryptoapis/sdk-guzzle7 Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain an

Crypto APIs 3 Oct 21, 2022
A PHP implementation of the GraphQL specification based on the JavaScript reference implementation

GraphQL This is a PHP implementation of the GraphQL specification based on the JavaScript reference implementation. Related projects DateTime scalar R

Digia 219 Nov 16, 2022
Pure PHP APIs with PostgreSQL database, with HTML, CSS & JS simple frontend

The root of the project is html/index.html The folder needs to be put in htdocs folder to run correctly // this link should open the main page if the

ZaydSK 3 Jul 22, 2022
A simple way of authenticating your RESTful APIs with API keys using Laravel

ApiGuard This package is no longer maintained This package is no longer maintained as Laravel already has a similar feature built-in since Laravel 5.8

Chris Bautista 691 Nov 29, 2022
A php library for coinex exchange apis .

Coinex API PHP Coinex digital coin exchange API for PHP Requirements PHP>=7.1 CURL PHP module Install composer require roozbeh/coinex_php Acquire acce

Roozbeh Baabakaan 3 Nov 12, 2022
Create REST and GraphQL APIs, scaffold Jamstack webapps, stream changes in real-time.

API Platform is a next-generation web framework designed to easily create API-first projects without compromising extensibility and flexibility: Desig

API Platform 7.7k Jan 7, 2023
Behat extension for those who want to write acceptances tests for apis

Behapi Behat extension to help write describe features related to HTTP APIs. PHP 7.3, Behat 3.7 and a discoverable php-http client are required to mak

Baptiste Clavié 32 Nov 25, 2022
Laravel cryptocurrency trading APIs.

Lypto API Laravel cryptocurrency trading APIs. Installation Requirements Minimum Laravel version 7.0 Use the following command to install: composer re

Md Obydullah 4 Jan 27, 2022
A collective list of free APIs

Public APIs A collective list of free APIs for use in software and web development Status The Project Contributing Guide • API for this project • Issu

null 222.8k Jan 4, 2023
The NelmioApiDocBundle bundle allows you to generate a decent documentation for your APIs

NelmioApiDocBundle The NelmioApiDocBundle bundle allows you to generate a decent documentation for your APIs. Migrate from 3.x to 4.0 To migrate from

Nelmio 2.1k Jan 6, 2023
The server component of API Platform: hypermedia and GraphQL APIs in minutes

API Platform Core API Platform Core is an easy to use and powerful system to create hypermedia-driven REST and GraphQL APIs. It is a component of the

API Platform 2.2k Dec 27, 2022
Proposed REST and GraphQL APIs for Concrete CMS 9.2+

Concrete CMS API Proposal 2022 Hello there! This is a package for Concrete CMS (9.1.1+) that adds a proposed REST API. This API is reasonably comprehe

Concrete CMS 5 Aug 11, 2022
Simple, extensible and powerful enumeration implementation for Laravel.

About Laravel Enum Simple, extensible and powerful enumeration implementation for Laravel. Enum key value pairs as class constants Full featured suite

Ben Sampson 1.8k Dec 23, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
Facebook SDK for PHP (v6) - allows you to access the Facebook Platform from your PHP app

Facebook SDK for PHP (v6) This repository contains the open source PHP SDK that allows you to access the Facebook Platform from your PHP app. Installa

null 0 Aug 10, 2022