Shopware 6: Services in the admin

We are currently implementing a payment plugin, and one of the things we want to have is a button to test the configuration. So we need to make an AJAX call to the PHP “backend”, which is all API driven in Shopware 6. Shopware is offering a nice way to do this: The ApiService implemented in JS.

Shopware has a documentation for services, but not for HTTP calls.

Webkul wrote an awesome blogpost about it, so have a look there. Although the problem is that, at least in Shopware 6.5, the code doesn’t work as explained, because 'src/core/service/api.service' can not be found.

So here is another nice example by us, which works in Shopware 6.5.6.0:

First, we need a service which does the actual work.

// src/Resources/app/administration/src/core/service/api/testApi.service.js

const {ApiService} = Shopware.Classes;

export default class TestApiService extends ApiService {
    constructor(httpClient, loginService, apiEndpoint = 'example/test-api') { // <=== Here is the API endpoint which is called
        super(httpClient, loginService, apiEndpoint);
    }
    // this method returns a Promise!
    testApi() {
        const apiRoute = `${this.getApiBasePath()}`
        return this.httpClient.post(
            apiRoute, {}, {
                headers: this.getBasicHeaders()
            }
        ).then((response) => {
            return ApiService.handleResponse(response);
        });
    }
}

This service needs to be registered and initialised.

// src/Resources/app/administration/src/init/testApi-service.init.js

const Application = Shopware.Application;
import TestApiService from "../../src/core/service/api/testApi.service";

Application.addServiceProvider('testApi', (container) => { /// testApi is the name which will be injected later!
    const initContainer = Application.getContainer('init');
    return new TestApiService(initContainer.httpClient, container.loginService);
});

And once this service is registered, you can inject it into your component.

// src/Resources/app/administration/src/component/custom-component/test-api/index.js

import template from './test-api.html.twig';

Shopware.Component.register('test-api', {
    inject: ['testApi'],

    template,

    methods: {
        someMethod() {
            // testApi() returns a Promise, so we can chain it with then()
            this.testApi.testApi().then((data) => {
                // do something with the data
            });
        }
    },
});

If you have questions, leave a comment here and we try to help!

3 thoughts on “Shopware 6: Services in the admin

Leave a Reply