Skip to content

Working with App Extensions

Jeroen de Lau edited this page Sep 25, 2024 · 3 revisions

pending release: https://github.com/Kyon147/laravel-shopify/pull/329

You can use Shopify App Extensions with your Laravel backend.

Steps to achieve this:

1. Create an App Extension

2. Retrieve and use the session token

The session token is retrieved through the useSessionToken (checkout ui) hook. Note that the import path varies based on the type of extension. IE: this is the same hook for customer account UI useSessionToken (customer account ui). So make sure to import the correct one.

note: below is just an example, you can choose your own implementation using Axios or a context, whatever suits you

import React, { useCallback, useState } from 'react';
import { useApi } from '@shopify/ui-extensions-react/checkout';

export default function useBackend(
    route: string,
    method: string,
    data?: any,
    params?: any,
    onSuccess?: (response: any) => void,
) {
    // retrieve and store the token
    const [token, setSessionToken] = useState('');
    const { sessionToken } = useApi();
    sessionToken.get().then(setSessionToken);

    const [calling, setCalling] = React.useState(false);

    const call = useCallback(() => {
        const doCall = async () => {
            setCalling(true);

            const url = route + (params ? `?${new URLSearchParams(params).toString()}` : '');
            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    Accept: 'application/json',
                    // pass the token to the request
                    Authorization: `Bearer ${token}`,
                },
                body: data ? JSON.stringify(data) : null,
            });

            setCalling(false);
            if (onSuccess) {
                onSuccess(response);
            }
        };
        doCall();
    }, [route, method, data, params, onSuccess, token]);

    return [call, calling];
}