I've a shopware storefront where customer can add products to their cart.
I want to fetch the cart-content with an ajax-request with the api endpoint: /checkout/cart. In the header i sent:
{
"Accept": "application/json"
"sw-context-token": "1234567890",
"sw-access-key": "ENKJDSKFDNSJKFNEJ0815"
}
In my response-body stay the 'lineItems' still empty.
"lineItems": [],
Maybe it depends on fetching the correct 'sw-context-token' first, but how ? Background: i want to check, if the cart contains a product of a specified category. Any better/other solution is very welcome.
I've a shopware storefront where customer can add products to their cart.
I want to fetch the cart-content with an ajax-request with the api endpoint: /checkout/cart. In the header i sent:
{
"Accept": "application/json"
"sw-context-token": "1234567890",
"sw-access-key": "ENKJDSKFDNSJKFNEJ0815"
}
In my response-body stay the 'lineItems' still empty.
"lineItems": [],
Maybe it depends on fetching the correct 'sw-context-token' first, but how ? Background: i want to check, if the cart contains a product of a specified category. Any better/other solution is very welcome.
Share Improve this question asked Mar 18 at 13:57 Shao KhanShao Khan 4589 silver badges32 bronze badges1 Answer
Reset to default 0I have encountered a similar scenario as yours a couple of days ago and here is what worked for me.
I assume you already created/have a custom plugin.
The solution below assumes that the user has already logged in, ex. checkout/confirm page.
As you already mentioned, the problem derives from not providing the correct 'sw-context-token'.
First, extend the base.html.twig in your plugin/theme if you haven't already and place the following code below in base.html.twig:
{% sw_extends '@Storefront/storefront/base.html.twig' %}
{% block base_body_script %}
{{ parent() }}
<script>
window.contextToken = '{{ context.token }}';
window.salesChannelAccessKey = '{{ context.salesChannel.accessKey }}';
</script>
{% endblock %}
Then create your storefront JavaScript plugin if you haven't already.
The file path should be as follows:
// <plugin root>/src/Resources/app/storefront/src/example-plugin/example-plugin.plugin.js
You can check the docs over here how/where to place it:
https://developer.shopware/docs/guides/plugins/plugins/storefront/fetching-data-with-javascript.html
My function was as follows which returned the current user's cart.
async getCart() {
const contextToken = window.contextToken;
const accessKey = window.salesChannelAccessKey;
const cartResponse = await fetch('/store-api/checkout/cart', {
method: 'GET',
headers: {
'sw-context-token': contextToken,
'sw-access-key': accessKey
},
});
const cartData = await cartResponse.json();
console.log('customer cart:', cartData);
}
Hope it helps to resolve your problem.
By the go, don't fet to call your function in init function.
Cheers