shopwareshopware6storefront

Interact with storefront customer's session in Shopware 6 app


I need to retrieve a customer connected to the storefront backend side to reward him in different ways.

I created a plugin that extends the plugin.class of the plugins system.

It fetches the customer on the store api using the route store-api/account/customer then it sends to my backend its identifier. I also resolve the shop_url of the admin api with window.location.protocol and window.location.hostname...

This seems to me not secured or accurate (the domain can be different from the sales channel to the admin api) and I would like to know if it would be possible to fetch a secured unique customer's token that would allow me to resolve both the shop_url and the customer's identifier.

I cannot find anything in the documentation that would help me securing that part of my app.

Thanks.

(Edit)

Here is my actual code to fetch the customer inside the plugin:

import Plugin from 'src/plugin-system/plugin.class';
import StoreApiClient from 'src/service/store-api-client.service';

const storeClient = new StoreApiClient();

const handleUser = (data, request) => {
  let unsecuredUserId = null;
  if (request.status === 200) {
    try {
      const user = JSON.parse(data);
      unsecuredUserId = user.id || null;
    } catch (e) {}
  }
  doSomethingWith(unsecuredUserId);
}

export default class SaylPlugin extends Plugin {
  init() {
    storeClient.get('store-api/account/customer', handleUser);
  }
}

Solution

  • I finally found a way to get the things more secured.

    My new plugin code:

    import Plugin from 'src/plugin-system/plugin.class';
    import StoreApiClient from 'src/service/store-api-client.service';
    
    const storeClient = new StoreApiClient();
    
    const handleContext = (data, request) => {
      if (request.status === 200) {
        try {
          const context = JSON.parse(data);
          if (context instanceof Object) {
            resolveCustomerBackendSide(
              context.token,
              context.salesChannel.id
            );
          }
        } catch (e) {
          console.error(e);
        }
      }
    }
    
    export default class SaylPlugin extends Plugin {
      init() {
        storeClient.get('store-api/context', handleContext);
      }
    }
    

    With this context I can resolve the admin api credentials backend side using the sales channel identifier that I save during the app registration process (you will have to allow sales_channel read in the app's manifest). Therefore I fetch the sales channel backend side to retrieve the sw-access-key header and I can finally fetch the store-api backend side to retrieve the customer in a secured way (the token that you get after fetching the store-api/context can be used as sw-context-token header.