Lesson 4.2. Store API

Wednesday, 1:00 PM

The frontend developer of a headless store: "The product gets added, but after a page reload the cart is empty." Every Store API request arrives without a Cart-Token, so WooCommerce sees a new guest with a new empty cart every time.

The backend works correctly. It just doesn't know it's the same customer.

Goal

After the lesson you work with the cart and checkout through the Store API, keep the customer's session between requests and add your own data to the response.

Key concepts

  • Store API — a public REST API for the customer: /wp-json/wc/store/v1/ (cart, cart/add-item, checkout, products)
  • Needs no keys, works on behalf of the current customer (session or Cart-Token)
  • The Nonce header for requests that change data
  • Extending the response: woocommerce_store_api_register_endpoint_data() (ExtendSchema)
  • The difference from WC REST API v3: v3 is admin access with keys, the Store API is customer actions

Diagram

sequenceDiagram
  participant B as Browser / headless
  participant S as Store API
  participant C as WC()->cart
  B->>S: GET /wc/store/v1/cart
  S-->>B: cart + Nonce + Cart-Token
  B->>S: POST /cart/add-item {id, quantity} + Nonce
  S->>C: add_to_cart() + totals
  S-->>B: updated cart JSON

Code

Add data to Store API cart items:

PHP
<?php
use Automattic\WooCommerce\StoreApi\Schemas\V1\CartItemSchema;

add_action( 'woocommerce_blocks_loaded', static function () {
	woocommerce_store_api_register_endpoint_data( [
		'endpoint'        => CartItemSchema::IDENTIFIER,
		'namespace'       => 'my-plugin',
		'data_callback'   => static function ( array $cart_item ): array {
			$product = $cart_item['data'];
			return [ 'supplier_code' => (string) $product->get_meta( '_supplier_code' ) ];
		},
		'schema_callback' => static fn (): array => [
			'supplier_code' => [ 'type' => 'string', 'readonly' => true ],
		],
		'schema_type'     => ARRAY_A,
	] );
} );

A request from the frontend (JS):

JAVASCRIPT
const res = await fetch( '/wp-json/wc/store/v1/cart' );
const nonce = res.headers.get( 'Nonce' );
const cart = await res.json();
console.log( cart.items[0].extensions['my-plugin'].supplier_code );

await fetch( '/wp-json/wc/store/v1/cart/add-item', {
	method: 'POST',
	headers: { 'Content-Type': 'application/json', Nonce: nonce },
	body: JSON.stringify( { id: 41, quantity: 1 } ),
} );

Common mistakes

SymptomCauseFix
401/403 on add-itemNo Nonce headerTake the Nonce from the GET /cart response
Your data doesn't show in the cartRegistered before the blocks loadedRegister on woocommerce_blocks_loaded
The headless cart "gets lost" between requestsThe Cart-Token isn't sentStore and send the Cart-Token header

Weak and strong answer

Question: How does the Store API differ from the WC REST API?

Weak answer. The Store API is newer.

Strong answer. They are different APIs for different roles. WC REST API v3 is for administration and integrations: keys, full access to products and orders. The Store API is public and works on behalf of the customer: cart, checkout, catalog, no keys, with Nonce and Cart-Token. That's why a headless frontend is built on the Store API, and an ERP sync on REST v3.

Why the second is stronger: The candidate explains the difference through roles and security and knows when to use which.

Practice

First, in the terminal: get the cart and save the nonce and cart-token. Add a product without Nonce, then without Cart-Token, then with both, and get the cart again with the token. You'll reproduce the bug from the start of the lesson and its fix.

Then on your own site: build a "cart" in plain JS (get the cart, add a product, change the quantity, remove an item) and add your own field to the cart response with ExtendSchema.

curl / wp — Module 4. Cart and Checkout

Interview Questions

No, it's the customer's public API. Changes need the Nonce header (CSRF protection) and a session or a Cart-Token.

With woocommerce_store_api_register_endpoint_data() for the endpoint you need (cart, cart item). The data shows up in the extensions.<namespace> field.

Yes, that's its main use case together with blocks. But payment on an external frontend depends on the payment gateway: not every gateway supports paying through the Store API.

Save your progress

Sign in or create a free account to mark lessons as completed and continue the whole course. You will come back to this lesson.