Building a Shopify app with Laravel · Part 5 of 6

Shopify10 min read

Webhooks, Events and the privacy topics

One middleware for classic webhooks and the newer Events deliveries, deduplication by webhook ID, the three privacy topics every app must answer, and a real uninstall and reinstall.

By Abhishek Fouzdar · Updated

So far Shopify has only answered the app. This part is about Shopify calling it: when a merchant uninstalls, when a product is deleted, and when a customer exercises a privacy right. Two delivery mechanisms exist now, and the app uses both where each fits. It ends with a real uninstall and reinstall, which is the one test no sample payload can stand in for.

Webhooks and Events

Webhooks are the classic mechanism: subscribe to a topic such as app/uninstalled, receive a fixed REST-shaped JSON payload at a URL, signed with your client secret. Every Shopify resource has topics; the privacy topics and the app lifecycle exist only here.

Events reached general availability in API version 2026-10. A subscription names a resource (Product), the actions that interest you (delete), optionally which fields must have changed, and a GraphQL query that shapes the payload. Deliveries are signed the same way and carry the same deduplication header. Eighteen resources support Events at the time of writing; product deletion is one of them, and it is the natural fit for "a product went away, drop its reviews".

Both are declared in shopify.app.toml and reach Shopify with shopify app deploy. Both arrive as a POST that the app must answer with a 2xx within five seconds, or Shopify retries, for up to two days. The retries are why deduplication matters: the same delivery can arrive twice, and handling an uninstall twice is harmless but handling a refund twice is not.

What the app subscribes to

Added to shopify.app.toml:

[webhooks]
api_version = "2026-10"

  # Classic webhooks: the app lifecycle and the three privacy topics every app must answer.
  [[webhooks.subscriptions]]
  topics = [ "app/uninstalled" ]
  uri = "/api/webhooks"

  [[webhooks.subscriptions]]
  compliance_topics = [ "customers/data_request", "customers/redact", "shop/redact" ]
  uri = "/api/webhooks"

# Events: the newer delivery mechanism, GraphQL-shaped. One subscription, so that reviews
# of a deleted product are deleted with it.
[events]
api_version = "2026-10"

  [[events.subscription]]
  handle = "product-deleted"
  topic = "Product"
  actions = [ "delete" ]
  uri = "/api/events"

The three compliance topics are mandatory for any app that will be listed or installed on more than your own store: a customer asks for their data, a customer asks to be forgotten, a shop is to be forgotten 48 hours after uninstall. Shopify will not approve an app without handlers for them. Relative URIs resolve against application_url, so they follow the tunnel.

shopify app deploy --message "Part 5: webhooks, compliance topics and the product-deleted event"
│  New version released to users.                                         │
│  reviewmini-3                                                           │

One middleware for both

Verification is an HMAC-SHA256 of the raw body with the client secret, base64 encoded, compared with the Shopify-Hmac-Sha256 header. The package does it; the middleware's own work is deduplication, which is one insert into a table with a unique index. A second delivery with the same Shopify-Webhook-Id hits the index and is answered with a 204 without reaching the controller.

The headers differ between the two mechanisms, and that was a surprise found by reading the database: webhooks prefix theirs with X- (X-Shopify-Topic), Events do not (Shopify-Topic) and add Shopify-Action. The middleware reads both and records Events as Product/delete.

database/migrations/2026_10_23_100300_create_webhook_deliveries_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
    {
        // Every delivery Shopify makes, keyed by its Shopify-Webhook-Id. Shopify retries
        // until it sees a 2xx, so the same delivery can arrive twice; the unique index is
        // what makes handling it twice harmless.
        Schema::create('webhook_deliveries', function (Blueprint $table) {
            $table->id();
            $table->string('webhook_id')->unique();
            $table->string('topic');
            $table->string('shop');
            $table->timestamp('received_at');
        });
    }

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

app/Models/WebhookDelivery.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class WebhookDelivery extends Model
{
    public $timestamps = false;

    protected $fillable = ['webhook_id', 'topic', 'shop', 'received_at'];

    protected function casts(): array
    {
        return ['received_at' => 'datetime'];
    }
}

app/Http/Middleware/VerifyShopifyWebhook.php:

<?php

namespace App\Http\Middleware;

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

/**
 * For deliveries Shopify pushes to the app: classic webhooks and Events. Both are
 * signed the same way, an HMAC of the raw body in the Shopify-Hmac-Sha256 header,
 * and both carry a Shopify-Webhook-Id the app uses to ignore repeats.
 */
class VerifyShopifyWebhook
{
    public function __construct(private ShopifyApp $shopify) {}

    public function handle(Request $request, Closure $next): Response
    {
        $result = $this->shopify->verifyWebhookReq(Adapter::req($request));

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

        // Webhooks prefix their headers with X-; Events deliveries do not, and add
        // Shopify-Action ("delete") next to the topic ("Product").
        $topic = $request->header('X-Shopify-Topic') ?? $request->header('Shopify-Topic', '');
        $webhookId = $request->header('X-Shopify-Webhook-Id') ?? $request->header('Shopify-Webhook-Id', '');

        if ($action = $request->header('Shopify-Action')) {
            $topic = "{$topic}/{$action}";
        }

        try {
            WebhookDelivery::create([
                'webhook_id' => $webhookId,
                'topic' => $topic,
                'shop' => $result->shop,
                'received_at' => now(),
            ]);
        } catch (UniqueConstraintViolationException) {
            // Already handled. Tell Shopify so, or it keeps retrying.
            return response()->noContent();
        }

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

        return $next($request);
    }
}

The handlers

Each handler is a quick database change, so they run inline and answer well within the five seconds. An app that did more per delivery, calling the Admin API or sending mail, would record the delivery and dispatch a job.

On app/uninstalled, the token is dead from that moment and the row says so, but the reviews stay. shop/redact arrives 48 hours later and deletes everything; a merchant who reinstalls inside those 48 hours gets their reviews back. customers/redact strips the reviewer's name and email and keeps the rating, which is not personal data. customers/data_request is the merchant's obligation to answer; the app's job is to make its data findable, which here is a log line with the matching count. A real app would email the merchant an export.

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

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Shop;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

/**
 * Classic webhooks: the app lifecycle and the three privacy topics every app must
 * answer. Each handler is a quick database change, so it runs inline; Shopify wants a
 * 2xx within five seconds, and anything slower belongs in a queued job.
 */
class WebhookController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $shop = Shop::where('shop', $request->attributes->get('shop'))->first();
        $payload = $request->json()->all();

        match ($request->attributes->get('topic')) {
            'app/uninstalled' => $this->uninstalled($shop),
            'customers/data_request' => $this->customerDataRequest($shop, $payload),
            'customers/redact' => $this->customerRedact($shop, $payload),
            'shop/redact' => $this->shopRedact($shop),
            default => Log::info('Unhandled webhook topic', ['topic' => $request->attributes->get('topic')]),
        };

        return response()->noContent();
    }

    /** The token is dead from this moment; keep the rows for shop/redact 48 hours later. */
    private function uninstalled(?Shop $shop): void
    {
        $shop?->forgetAccessToken();
        $shop?->forceFill(['uninstalled_at' => now()])->save();
    }

    /**
     * A customer asked the merchant for their data. Shopify sends the request, the
     * merchant answers it; the app's job is to make the data findable. Here the only
     * personal data is the reviewer email, so log the match for the merchant's export.
     */
    private function customerDataRequest(?Shop $shop, array $payload): void
    {
        $email = $payload['customer']['email'] ?? null;
        $count = $shop && $email ? $shop->reviews()->where('author_email', $email)->count() : 0;

        Log::info('Customer data request', [
            'shop' => $shop?->shop,
            'request_id' => $payload['data_request']['id'] ?? null,
            'reviews_matching' => $count,
        ]);
    }

    /** Strip personal data from the customer's reviews but keep the ratings. */
    private function customerRedact(?Shop $shop, array $payload): void
    {
        $email = $payload['customer']['email'] ?? null;

        if ($shop && $email) {
            $shop->reviews()->where('author_email', $email)->update([
                'author_name' => 'Anonymous',
                'author_email' => null,
            ]);
        }
    }

    /** 48 hours after uninstall: everything about the shop goes. */
    private function shopRedact(?Shop $shop): void
    {
        $shop?->delete(); // reviews and settings cascade
    }
}

An Events delivery names its subscription by handle. For a delete, data.product is null, because the product no longer exists to be queried, and the ID is in query_variables.

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

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Shop;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

/**
 * Events deliveries. The payload names the topic, the action and the subscription
 * handle, carries the data the subscription's GraphQL query asked for, and lists the
 * query variables. For a delete the data is null; the ID is in query_variables.
 */
class EventsController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $shop = Shop::where('shop', $request->attributes->get('shop'))->first();
        $event = $request->json()->all();

        match ($event['handle'] ?? null) {
            'product-deleted' => $this->productDeleted($shop, $event['query_variables']['productId'] ?? null),
            default => Log::info('Unhandled event', ['handle' => $event['handle'] ?? null, 'action' => $event['action'] ?? null]),
        };

        return response()->noContent();
    }

    /** Reviews of a product that no longer exists have nowhere to show; drop them. */
    private function productDeleted(?Shop $shop, ?string $productId): void
    {
        if ($shop && $productId) {
            $shop->reviews()->where('product_id', $productId)->delete();
        }
    }
}

The routes sit outside the App Home middleware and outside the api group's per-IP rate limit, since a busy shop sends bursts from a handful of addresses.

routes/api.php:

<?php

use App\Http\Controllers\Api\EventsController;
use App\Http\Controllers\Api\ProductController;
use App\Http\Controllers\Api\ReviewController;
use App\Http\Controllers\Api\SettingsController;
use App\Http\Controllers\Api\ShopController;
use App\Http\Controllers\Api\WebhookController;
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);

    Route::get('/reviews', [ReviewController::class, 'index']);
    Route::post('/reviews', [ReviewController::class, 'store']);
    Route::patch('/reviews/{id}', [ReviewController::class, 'update']);
    Route::delete('/reviews/{id}', [ReviewController::class, 'destroy']);

    Route::get('/products', [ProductController::class, 'index']);

    Route::get('/settings', [SettingsController::class, 'show']);
    Route::put('/settings', [SettingsController::class, 'update']);
});

// Deliveries pushed by Shopify. Verified by HMAC, not by an ID token, and exempt from
// the per-IP rate limit: a busy shop can send bursts from the same addresses.
Route::middleware('shopify.webhook')->withoutMiddleware('throttle:api')->group(function () {
    Route::post('/webhooks', WebhookController::class);
    Route::post('/events', EventsController::class);
});

bootstrap/app.php gains the alias:

$middleware->alias([
    'shopify.app-home' => AuthenticateAppHome::class,
    'shopify.webhook' => VerifyShopifyWebhook::class,
]);

Trying it three ways

Sample payloads from the CLI. The CLI can sign and send a sample of any webhook topic to any URL. The samples name a placeholder shop, so the handlers find no row, but the signature check, the deduplication and the dispatch by topic all run for real.

shopify app webhook trigger --topic app/uninstalled --api-version 2026-10 \
  --delivery-method http --address https://reviewmini.shipbytes.dev/api/webhooks \
  --client-id "$SHOPIFY_API_KEY" --client-secret "$SHOPIFY_API_SECRET"
✅ Success! Webhook has been enqueued for delivery.

After triggering the three topics the same way, the webhook_deliveries table reads:

app/uninstalled          shop
customers/data_request   shop
customers/redact         shop

A real product deletion. Create a throwaway product with the Admin API, add a review for it through the app, delete the product. Twelve seconds later the Events delivery had arrived at /api/events, the reviews for that product were gone, and the deliveries table had a row with topic Product/delete for saanjh-living.

A real uninstall. In the admin, Settings, Apps, the app's menu, Uninstall. The CLI's log shows the delivery:

[web]  2026-10-23 16:56:38 /api/webhooks .. ~ 1.06ms

The shop row now has no token and an uninstalled_at, and still has its three reviews. The app's URL in the admin answers 404 until it is installed again, which the install URL does:

https://admin.shopify.com/store/saanjh-living/oauth/install?client_id=<client id>

It shows the scopes, one click installs, and the app loads with a fresh token exchanged by the part 2 middleware. The reviews are where they were.

Tests

A test signs its own deliveries with the test secret. The last test sends an Events delivery with the unprefixed headers.

tests/Feature/WebhookTest.php:

<?php

namespace Tests\Feature;

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

class WebhookTest extends TestCase
{
    use RefreshDatabase;

    private Shop $shop;

    protected function setUp(): void
    {
        parent::setUp();

        $this->shop = Shop::create(['shop' => 'test-shop']);
        $this->shop->forceFill(['access_token' => 'shpat_test', 'installed_at' => now()])->save();
        $this->shop->reviews()->create([
            'product_id' => 'gid://shopify/Product/1', 'product_title' => 'Cushion',
            'author_name' => 'Asha', 'author_email' => '[email protected]', 'rating' => 5, 'body' => 'Lovely', 'status' => 'approved',
        ]);
    }

    /**
     * Shopify signs the raw body with the client secret; the test signs the same way.
     *
     * @param  array<string, mixed>  $payload
     */
    private function deliver(string $path, string $topic, array $payload, string $webhookId = 'delivery-1', array $extraHeaders = []): TestResponse
    {
        $body = json_encode($payload);
        $hmac = base64_encode(hash_hmac('sha256', $body, config('shopify.api_secret'), true));

        return $this->call('POST', $path, [], [], [], $this->transformHeadersToServerVars([
            'Content-Type' => 'application/json',
            'X-Shopify-Hmac-Sha256' => $hmac,
            'X-Shopify-Shop-Domain' => 'test-shop.myshopify.com',
            'X-Shopify-Topic' => $topic,
            'X-Shopify-Webhook-Id' => $webhookId,
            ...$extraHeaders,
        ]), $body);
    }

    public function test_a_delivery_with_a_bad_signature_is_rejected(): void
    {
        $this->postJson('/api/webhooks', ['shop_domain' => 'test-shop.myshopify.com'], [
            'X-Shopify-Hmac-Sha256' => base64_encode('nope'),
            'X-Shopify-Shop-Domain' => 'test-shop.myshopify.com',
            'X-Shopify-Topic' => 'app/uninstalled',
            'X-Shopify-Webhook-Id' => 'x',
        ])->assertUnauthorized();

        $this->assertNotNull($this->shop->fresh()->access_token);
    }

    public function test_app_uninstalled_drops_the_token_but_keeps_the_data(): void
    {
        $this->deliver('/api/webhooks', 'app/uninstalled', ['domain' => 'test-shop.myshopify.com'])->assertNoContent();

        $shop = $this->shop->fresh();
        $this->assertNull($shop->access_token);
        $this->assertNotNull($shop->uninstalled_at);
        $this->assertSame(1, $shop->reviews()->count());
    }

    public function test_a_repeated_delivery_is_acknowledged_without_being_handled_twice(): void
    {
        $this->deliver('/api/webhooks', 'app/uninstalled', [], 'same-id')->assertNoContent();
        $this->shop->forceFill(['access_token' => 'shpat_new'])->save();

        $this->deliver('/api/webhooks', 'app/uninstalled', [], 'same-id')->assertNoContent();

        $this->assertSame('shpat_new', $this->shop->fresh()->access_token);
    }

    public function test_customers_redact_anonymises_their_reviews(): void
    {
        $this->deliver('/api/webhooks', 'customers/redact', [
            'shop_domain' => 'test-shop.myshopify.com',
            'customer' => ['id' => 1, 'email' => '[email protected]'],
        ])->assertNoContent();

        $this->assertDatabaseHas('reviews', ['author_name' => 'Anonymous', 'author_email' => null, 'rating' => 5]);
    }

    public function test_shop_redact_removes_everything(): void
    {
        $this->deliver('/api/webhooks', 'shop/redact', ['shop_domain' => 'test-shop.myshopify.com'])->assertNoContent();

        $this->assertDatabaseMissing('shops', ['shop' => 'test-shop']);
        $this->assertDatabaseCount('reviews', 0);
    }

    public function test_a_product_delete_event_removes_its_reviews(): void
    {
        $this->call('POST', '/api/events', [], [], [], $this->transformHeadersToServerVars([
            'Content-Type' => 'application/json',
            'Shopify-Hmac-Sha256' => base64_encode(hash_hmac('sha256', $body = json_encode([
                'topic' => 'Product', 'action' => 'delete', 'handle' => 'product-deleted',
                'data' => ['product' => null],
                'query_variables' => ['productId' => 'gid://shopify/Product/1'],
            ]), config('shopify.api_secret'), true)),
            'Shopify-Shop-Domain' => 'test-shop.myshopify.com',
            'Shopify-Topic' => 'Product',
            'Shopify-Action' => 'delete',
            'Shopify-Webhook-Id' => 'event-1',
        ]), $body)->assertNoContent();

        $this->assertDatabaseCount('reviews', 0);
        $this->assertDatabaseHas('webhook_deliveries', ['topic' => 'Product/delete']);
    }
}

When it goes wrong

Deliveries arrive, the log shows nothing from the package, and the shops table does not change. Look for an exception in laravel.log. Here it was Target class [shopify.webhook] does not exist: the alias was never registered, because a formatter had rewritten the line the edit was aimed at. The route answered 500 and Shopify will have retried.

Deliveries are recorded with an empty topic. They are Events, and the middleware read only the X- headers.

Nonexistent flag: --no-color on shopify app webhook trigger. That command does not take the flag other commands do.

The CLI trigger says success and nothing arrives. Check the address is the public tunnel URL with the path, and that the dev session is running; the trigger is sent from Shopify's side.

Every delivery is a 401. The secret the app verifies with is not the one the app record has. After rotating a secret, pull it again with shopify app env pull and restart the dev session. The package accepts an oldClientSecret during a rotation.

Shopify shows the delivery as failed with a timeout. The handler took more than five seconds, usually because it called the Admin API inline. Record and dispatch a job.

Part 6 adds the storefront: a signed proxy route, a theme app extension, and a review that goes from a product page to the admin and back.

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.