Building a Shopify app with Laravel · Part 2 of 6

Shopify14 min read

Authentication with ID tokens and expiring access tokens

No login page, no redirect, no cookie: how the admin identifies the merchant on every request, how token exchange gets an access token, how the official package refreshes it, and tests that mint their own Shopify tokens.

By Abhishek Fouzdar · Updated

Part 1 left a page that renders inside the admin for anyone who adds ?shop= to the URL. This part makes the app sure the request came from Shopify, learns which merchant is on the other side, and obtains an access token for the Admin API, all without a login page, a redirect, or a cookie. By the end, the App Home page shows the shop's name fetched live from Shopify, and the app's tests mint their own Shopify tokens.

How an embedded app authenticates now

Older Shopify tutorials, and both Laravel community packages, describe OAuth: redirect the merchant to Shopify, get a code back, exchange it for a permanent access token, keep a session cookie. Embedded apps stopped working that way, because browsers stopped sending cookies to iframes from other origins.

The current model has three pieces.

ID token. Every time the admin loads App Home, it appends a short-lived JWT to the URL as id_token. Every fetch() the page makes afterwards carries a fresh one in an Authorization: Bearer header, added by App Bridge. The token is signed with your client secret, names the shop in its dest claim, names your app in aud, and expires after about a minute. Verifying it proves the request came through the admin, for that shop, just now. Shopify's documentation also calls it a session token.

Token exchange. An ID token can be traded, server to server, for an access token to the Admin API. No redirect, no consent screen on a dev store, no code to carry around. The app does this the first time it sees a shop and stores the result.

Expiring access tokens. For public apps created since April 2026, and for all public apps from January 2027, the offline access token lives one hour and comes with a refresh token that lives 90 days. The app refreshes before calls; if the refresh token has expired too, which takes 90 days without a merchant visiting, it exchanges a new ID token.

Shopify's official PHP package implements all three, with the verification details that are easy to get subtly wrong. It is framework-agnostic, so a Laravel app writes a thin adapter and a middleware around it. That is this part.

The adapter

The package works on plain arrays and returns result objects; it does not know what a Laravel request is. Two static methods translate. One wrinkle appears here, and it cost an hour: Laravel keeps every header as a list of values, and the package expects one string per header. The package's own README shows the Laravel example without the array_map, and that version crashes inside the package with a TypeError (reported upstream as shopify-app-php#31) the first time a request carries an Authorization header.

app/Shopify/Adapter.php:

<?php

namespace App\Shopify;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

/**
 * Translates between Laravel's request/response objects and the shapes the
 * shopify/shopify-app-php package works with. The package is framework-agnostic,
 * so every framework writes these two functions once.
 */
final class Adapter
{
    /**
     * The package wants the raw request: method, every header, the full URL including
     * the query string, and the unmodified body. Verification depends on the exact bytes
     * Shopify sent, so nothing is filtered or re-encoded here.
     *
     * One wrinkle: Laravel keeps every header as a list of values, and the package
     * expects one string per header. Join repeated values the way HTTP itself does.
     *
     * @return array{method: string, headers: array<string, string>, url: string, body: string}
     */
    public static function req(Request $request): array
    {
        return [
            'method' => $request->method(),
            'headers' => array_map(fn (array $values) => implode(', ', $values), $request->headers->all()),
            'url' => $request->fullUrl(),
            'body' => $request->getContent(),
        ];
    }

    /**
     * Every package call returns a result with a pre-built HTTP response and a log entry.
     * When a call fails, that response is what the browser (or Shopify) must receive:
     * it carries the status and headers that make App Bridge retry with a fresh token,
     * redirect to the token page, or give up. Return it as-is.
     */
    public static function response(object $result): Response
    {
        Log::info("shopify: {$result->log->code} - {$result->log->detail}");

        return response($result->response->body, $result->response->status)
            ->withHeaders((array) $result->response->headers);
    }
}

The second method matters more than it looks. When verification fails, the package returns a complete HTTP response: a redirect to a token-refresh page, a 401 with a header that tells App Bridge to retry with a fresh token, a 400 for a malformed request. Return it unchanged and the recovery flows work; build your own 401 and they do not.

One instance of the package for the whole app, from the service container.

app/Providers/AppServiceProvider.php:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Shopify\App\ShopifyApp;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // One ShopifyApp instance for the whole request. It verifies requests from Shopify,
        // exchanges ID tokens for access tokens and talks to the Admin API.
        $this->app->singleton(ShopifyApp::class, fn () => new ShopifyApp(
            clientId: config('shopify.api_key'),
            clientSecret: config('shopify.api_secret'),
        ));
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}

Where tokens live

One row per shop. The package identifies a shop by its myshopify subdomain, saanjh-living for saanjh-living.myshopify.com, so the app does too. Token and refresh token are encrypted at rest with Laravel's encrypted cast; the rest is what the package needs to decide whether a refresh is due.

database/migrations/2026_10_23_100000_create_shops_table.php:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('shops', function (Blueprint $table) {
            $table->id();
            // The shop's myshopify subdomain, e.g. "example-store". The package always
            // identifies a shop this way, so the app does too.
            $table->string('shop')->unique();
            // Expiring offline access token and what is needed to renew it. The token
            // and refresh token are encrypted at rest by the model's casts.
            $table->text('access_token')->nullable();
            $table->string('scope')->nullable();
            $table->text('refresh_token')->nullable();
            $table->timestamp('access_token_expires_at')->nullable();
            $table->timestamp('refresh_token_expires_at')->nullable();
            $table->timestamp('installed_at')->nullable();
            $table->timestamp('uninstalled_at')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('shops');
    }
};

The model converts between the table and the package's token object in both directions.

app/Models/Shop.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Shopify\App\Types\TokenExchangeAccessToken;

class Shop extends Model
{
    protected $fillable = ['shop'];

    protected function casts(): array
    {
        return [
            'access_token' => 'encrypted',
            'refresh_token' => 'encrypted',
            'access_token_expires_at' => 'datetime',
            'refresh_token_expires_at' => 'datetime',
            'installed_at' => 'datetime',
            'uninstalled_at' => 'datetime',
        ];
    }

    /** The full myshopify domain, e.g. "example-store.myshopify.com". */
    public function domain(): string
    {
        return "{$this->shop}.myshopify.com";
    }

    /**
     * The stored token in the shape the package accepts, or null when the shop has none
     * (never installed, uninstalled, or the token was dropped after Shopify rejected it).
     */
    public function accessToken(): ?TokenExchangeAccessToken
    {
        if ($this->access_token === null) {
            return null;
        }

        return new TokenExchangeAccessToken(
            accessMode: 'offline',
            shop: $this->shop,
            token: $this->access_token,
            expires: $this->access_token_expires_at?->toIso8601String(),
            scope: $this->scope ?? '',
            refreshToken: $this->refresh_token,
            refreshTokenExpires: $this->refresh_token_expires_at?->toIso8601String(),
            user: null,
        );
    }

    /** Save a token the package returned, from a first exchange or a refresh. */
    public function storeAccessToken(TokenExchangeAccessToken $token): void
    {
        $this->forceFill([
            'access_token' => $token->token,
            'scope' => $token->scope,
            'refresh_token' => $token->refreshToken,
            'access_token_expires_at' => $token->expires,
            'refresh_token_expires_at' => $token->refreshTokenExpires,
            'installed_at' => $this->installed_at ?? now(),
            'uninstalled_at' => null,
        ])->save();
    }

    /** Drop the token so the next App Home request exchanges a fresh one. */
    public function forgetAccessToken(): void
    {
        $this->forceFill([
            'access_token' => null,
            'scope' => null,
            'refresh_token' => null,
            'access_token_expires_at' => null,
            'refresh_token_expires_at' => null,
        ])->save();
    }
}

The middleware

Everything the admin UI calls, the page and the JSON endpoints behind it, runs through one middleware. It does four things in order, and the comments in the file say which is which.

app/Http/Middleware/AuthenticateAppHome.php:

<?php

namespace App\Http\Middleware;

use App\Models\Shop;
use App\Shopify\Adapter;
use Closure;
use Illuminate\Http\Request;
use Shopify\App\ShopifyApp;
use Symfony\Component\HttpFoundation\Response;

/**
 * Protects every route the embedded admin UI calls: the App Home page itself and the
 * JSON endpoints its fetch() calls hit. After this middleware, the route can trust
 * $request->attributes->get('shop') and knows the shop holds a usable access token.
 */
class AuthenticateAppHome
{
    public function __construct(private ShopifyApp $shopify) {}

    public function handle(Request $request, Closure $next): Response
    {
        // 1. Is this really Shopify? The page request carries an id_token query
        //    parameter, fetch() calls carry an Authorization: Bearer header; the package
        //    checks both. A missing or stale token gets a response that tells App Bridge
        //    how to recover (redirect to the token page, or retry with a fresh token).
        $result = $this->shopify->verifyAppHomeReq(
            Adapter::req($request),
            appHomePatchIdTokenPath: config('shopify.patch_id_token_path'),
        );

        if (! $result->ok) {
            return Adapter::response($result);
        }

        // 2. Do we hold an access token for this shop, and is it still good?
        $shop = Shop::firstOrCreate(['shop' => $result->shop]);
        $token = $shop->accessToken();

        if ($token !== null) {
            // The package knows when a token needs refreshing; call it every time and
            // save whatever comes back. A refresh that fails means the refresh token has
            // expired too (90 days without a visit), so fall through to a new exchange.
            $refresh = $this->shopify->refreshTokenExchangedAccessToken($token);

            if (! $refresh->ok) {
                $shop->forgetAccessToken();
                $token = null;
            } elseif ($refresh->accessToken !== null) {
                $shop->storeAccessToken($refresh->accessToken);
            }
        }

        if ($token === null) {
            // 3. No token: trade the ID token for an offline access token. This is the
            //    whole install flow, no OAuth redirect, no consent screen on a dev store.
            $exchange = $this->shopify->exchangeUsingTokenExchange(
                accessMode: 'offline',
                idToken: $result->idToken,
                invalidTokenResponse: $result->invalidTokenResponse,
            );

            if (! $exchange->ok) {
                return Adapter::response($exchange);
            }

            $shop->storeAccessToken($exchange->accessToken);
        }

        $request->attributes->set('shop', $shop);
        $request->attributes->set('shopify', $result);

        $response = $next($request);

        // 4. The verify result carries the headers an embedded page needs (the
        //    Content-Security-Policy that allows the admin to frame it). Copy them on.
        foreach ((array) $result->response->headers as $name => $value) {
            $response->headers->set($name, $value);
        }

        return $response;
    }
}

Three decisions in there deserve a word.

The verify call is given appHomePatchIdTokenPath. An ordinary link or a full-page navigation inside the iframe reaches the server without an ID token, because App Bridge only intercepts fetch() and certain Polaris elements. The package handles that case by redirecting to a page of its own, rendered by the route below, which asks App Bridge for a token and retries the original URL. Without that path the package returns a configuration error.

refreshTokenExchangedAccessToken is called on every request that has a stored token. The package's README is firm about this: do not add your own expiry check in front of it. It returns quickly when nothing needs doing and returns a new token only when one was fetched. The one deviation from the README here: when the refresh fails, which means the refresh token itself has expired, the middleware drops the stored token and falls through to a new exchange, instead of returning the 401 the package suggests. With token exchange there is nothing for the merchant to do, so there is no reason to show them an error.

The verify result's response headers are copied onto the rendered response. For a page request they carry the Content-Security-Policy from part 1, now computed by the package from the verified shop rather than from a query parameter, plus preload hints for the two CDN scripts.

Register the alias, and trust the proxy. The tunnel terminates TLS and talks plain HTTP to php artisan serve, so without trustProxies Laravel builds http:// URLs, and the package's redirect to the token page goes to an address the browser will not load inside an HTTPS iframe.

bootstrap/app.php:

<?php

use App\Http\Middleware\AuthenticateAppHome;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // TLS ends at the tunnel (and later at the load balancer); the app itself speaks
        // plain HTTP. Trusting the forwarded headers keeps generated URLs on https.
        $middleware->trustProxies(at: '*');

        $middleware->alias([
            'shopify.app-home' => AuthenticateAppHome::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->shouldRenderJsonWhen(
            fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
        );
    })->create();

Routes

The token-refresh page stays outside the middleware; it is where requests without a token are sent. The page route is inside it.

routes/web.php:

<?php

use App\Http\Controllers\AppHomeController;
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;

// The token-refresh page must stay outside the App Home middleware: it is where
// requests without a token are sent to get one.
Route::get('/auth/patch-id-token', [AuthController::class, 'patchIdToken']);

Route::middleware('shopify.app-home')->group(function () {
    Route::get('/', AppHomeController::class)->name('app.home');
});

app/Http/Controllers/AuthController.php:

<?php

namespace App\Http\Controllers;

use App\Shopify\Adapter;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Shopify\App\ShopifyApp;

class AuthController extends Controller
{
    /**
     * The token-refresh page. When a navigation inside the admin iframe reaches the app
     * without an ID token, the middleware redirects here; the page the package renders
     * asks App Bridge for a fresh token and retries the original URL with it.
     */
    public function patchIdToken(Request $request, ShopifyApp $shopify): Response
    {
        return Adapter::response($shopify->appHomePatchIdToken(Adapter::req($request)));
    }
}

app/Http/Controllers/AppHomeController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;

class AppHomeController extends Controller
{
    public function __invoke(Request $request): View
    {
        return view('app', ['shop' => $request->attributes->get('shop')]);
    }
}

JSON endpoints go in routes/api.php, under the api middleware group: no session, no CSRF token, which is right, because the Bearer token is the authentication and there is no cookie to forge. Laravel 13 does not create the file by default; install:api would, but it also installs Sanctum, which this app does not need. The api group exists regardless; the file just has to be registered, which the bootstrap/app.php above does. One endpoint for now, as proof that the stored token works.

routes/api.php:

<?php

use App\Http\Controllers\Api\ShopController;
use Illuminate\Support\Facades\Route;

// JSON endpoints called by the admin UI with fetch(). App Bridge attaches the ID token
// as a Bearer header; the same middleware verifies it. No session, no CSRF: these
// routes run in the "api" middleware group.
Route::middleware('shopify.app-home')->group(function () {
    Route::get('/shop', ShopController::class);
});

app/Http/Controllers/Api/ShopController.php:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Shopify\Adapter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Shopify\App\ShopifyApp;

/**
 * Proof that the stored access token works: one Admin API query, made on behalf of
 * the shop that the middleware verified.
 */
class ShopController extends Controller
{
    public function __invoke(Request $request, ShopifyApp $shopify): JsonResponse|Response
    {
        $shop = $request->attributes->get('shop');
        $verified = $request->attributes->get('shopify');

        $result = $shopify->adminGraphQLRequest(
            '{ shop { name myshopifyDomain currencyCode plan { publicDisplayName partnerDevelopment } } }',
            shop: $shop->shop,
            accessToken: $shop->access_token,
            apiVersion: config('shopify.api_version'),
            // Tells the package this call answers a live App Home request, so a rejected
            // token can be turned into a "retry with a fresh token" response.
            invalidTokenResponse: $verified->invalidTokenResponse,
        );

        if (! $result->ok) {
            // Shopify no longer accepts the token (the app was uninstalled, or the token
            // was revoked). Drop it; the retried request exchanges a new one.
            if ($result->log->code === 'unauthorized') {
                $shop->forgetAccessToken();
            }

            return Adapter::response($result);
        }

        return response()->json($result->data['shop']);
    }
}

invalidTokenResponse is passed through from the verify result. It tells the package that this GraphQL call is answering a live request from the admin, so that if Shopify rejects the access token, the package can return the response that makes App Bridge retry the whole request with a fresh ID token. In a queued job there is no such request, and part 3 passes null instead.

The page shows the result of that call, with an inline script that part 4 replaces with React. App Bridge intercepts the fetch() and attaches the Bearer header; nothing in the script knows about tokens.

resources/views/app.blade.php:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ReviewMini</title>
    {{-- App Bridge reads the client ID from this meta tag. --}}
    <meta name="shopify-api-key" content="{{ config('shopify.api_key') }}">
    <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
    <script src="https://cdn.shopify.com/shopifycloud/polaris-2.js"></script>
</head>
<body>
    <s-page heading="ReviewMini">
        <s-section heading="Installed on {{ $shop->domain() }}">
            <s-paragraph id="shop-info">Asking the Admin API who we are…</s-paragraph>
        </s-section>
    </s-page>

    <script>
        // App Bridge intercepts same-origin fetch() calls and adds the ID token as
        // an Authorization: Bearer header, so the API route can verify them.
        fetch('/api/shop')
            .then((response) => response.json())
            .then((shop) => {
                document.getElementById('shop-info').textContent =
                    `${shop.name} (${shop.myshopifyDomain}), ${shop.plan.publicDisplayName}, prices in ${shop.currencyCode}.`;
            })
            .catch((error) => {
                document.getElementById('shop-info').textContent = `Request failed: ${error}`;
            });
    </script>
</body>
</html>

What happens on the first visit

Open the preview URL. Reading the CLI's log and the shops table together:

  1. The admin requests / with id_token in the query. The middleware verifies it, finds no row for saanjh-living, creates one, and exchanges the ID token for an access token.
  2. The row now holds a token that expires an hour later and a refresh token that expires 90 days later. The scope reads write_products only, because Shopify folds read_products into it.
  3. The page loads and its script fetches /api/shop with a Bearer header. The middleware verifies that token too, finds the row, asks the package whether a refresh is due (it is not), and the controller queries the Admin API.
  4. The page reads "Saanjh Living (saanjh-living.myshopify.com), Advanced, prices in INR." A dev store reports a plan of Advanced with partnerDevelopment true.

No redirect happened, no consent screen, no cookie was set.

Tests that mint Shopify tokens

ID tokens are HS256 JWTs signed with the client secret, so a test can create one the package accepts, using the firebase/php-jwt library the package already depends on. The test secret has to be at least 32 bytes; the library refuses shorter keys. Set both values in phpunit.xml:

<env name="SHOPIFY_API_KEY" value="test-client-id"/>
<env name="SHOPIFY_API_SECRET" value="test-client-secret-at-least-32-bytes-long"/>

tests/Feature/AppHomeTest.php:

<?php

namespace Tests\Feature;

use App\Models\Shop;
use Firebase\JWT\JWT;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AppHomeTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Shopify signs ID tokens with the app's client secret (HS256), so a test can mint
     * one the package accepts. The claims mirror what the admin sends.
     */
    private function idToken(string $shop = 'test-shop', ?string $secret = null): string
    {
        $now = time();

        return JWT::encode([
            'iss' => "https://{$shop}.myshopify.com/admin",
            'dest' => "https://{$shop}.myshopify.com",
            'aud' => config('shopify.api_key'),
            'sub' => '1234567890',
            'exp' => $now + 60,
            'nbf' => $now,
            'iat' => $now,
            'jti' => uniqid(),
            'sid' => 'session-id',
        ], $secret ?? config('shopify.api_secret'), 'HS256');
    }

    private function installedShop(string $shop = 'test-shop'): Shop
    {
        $model = Shop::create(['shop' => $shop]);
        $model->forceFill([
            'access_token' => 'shpat_test',
            'scope' => 'write_products',
            'refresh_token' => 'refresh_test',
            'access_token_expires_at' => now()->addMinutes(30),
            'refresh_token_expires_at' => now()->addDays(60),
            'installed_at' => now(),
        ])->save();

        return $model;
    }

    public function test_a_request_without_a_token_is_sent_to_the_token_page(): void
    {
        $response = $this->get('/?shop=test-shop.myshopify.com&embedded=1');

        $response->assertRedirect();
        $this->assertStringContainsString('/auth/patch-id-token', $response->headers->get('Location'));
    }

    public function test_the_app_home_renders_for_a_verified_shop(): void
    {
        $this->installedShop();

        $response = $this->get('/?shop=test-shop.myshopify.com&id_token='.$this->idToken());

        $response->assertOk();
        $response->assertSee('Installed on test-shop.myshopify.com');
        $this->assertStringContainsString(
            'frame-ancestors https://test-shop.myshopify.com',
            $response->headers->get('Content-Security-Policy'),
        );
    }

    public function test_a_token_signed_with_the_wrong_secret_is_rejected(): void
    {
        $this->installedShop();

        $response = $this->getJson('/api/shop', [
            'Authorization' => 'Bearer '.$this->idToken(secret: 'not-the-secret-but-also-32-bytes-long!'),
        ]);

        $response->assertUnauthorized();
        $response->assertHeader('X-Shopify-Retry-Invalid-Session-Request', '1');
    }
}

The third test is the one worth having: a token signed with the wrong secret gets a 401 with X-Shopify-Retry-Invalid-Session-Request: 1, which is exactly what App Bridge needs to see. Delete Laravel's stock ExampleTest, which expects / to answer 200 to anyone.

php artisan test
PASS  Tests\Feature\AppHomeTest
✓ a request without a token is sent to the token page
✓ the app home renders for a verified shop
✓ a token signed with the wrong secret is rejected

When it goes wrong

TypeError: strpos(): Argument #1 ($haystack) must be of type string, array given inside the package. The adapter is passing Laravel's header arrays through. Join them, as the adapter above does.

The page loads, then every fetch fails, and the browser console shows a redirect to /auth/patch-id-token. The fetch reached the server without a Bearer header. Usually App Bridge did not load: check the script tag and the shopify-api-key meta tag, and that the client ID in .env matches the TOML.

The redirect goes to http://, and the iframe shows a blank page or a mixed-content error. trustProxies is missing. Laravel built the URL from what it saw, which is plain HTTP behind the tunnel.

missing_shopify_reload and a 400 when visiting the token page directly. Expected; the page only makes sense with the shopify-reload parameter the package's redirect adds.

Every request exchanges a new token. The stored token is not being found. The package identifies the shop by subdomain, saanjh-living, not by the full domain. Store what $result->shop gives you.

Provided key is too short in tests. The JWT library wants a 32-byte secret. Lengthen the value in phpunit.xml.

The package's log codes. The adapter logs code - detail for every failure. redirect_to_patch_id_token_page, expired_id_token, invalid_aud, unauthorized each say what to look at, and the package's README has the full list. Read the log before reading the code.

Part 3 gives the app something to store: reviews, settings, product search, and a queued job that writes to Shopify, which has its own token problem.

New posts by email

Get new posts by email. Nothing else, no digests, unsubscribe in one click.

Comments

Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.