Building a Shopify app with Laravel · Part 3 of 6

Shopify14 min read

Reviews, settings, product search and the rating metafields

Data scoped by shop, JSON endpoints for the admin UI, product search through the Admin API, and a queued job that writes each product's rating to app-owned metafields, with the token problem jobs have.

By Abhishek Fouzdar

The app can tell who is calling and has a token for them. This part gives it something to do: reviews and settings stored per shop, JSON endpoints the admin UI will use in part 4, a product search that goes through the Admin API, and a queued job that writes each product's average rating into Shopify, where the storefront can read it without ever calling the app. The job is where the token model from part 2 meets the queue, and the package has a specific answer for that.

Tables

Reviews belong to a shop and name a product by its Shopify global ID, the gid://shopify/Product/… string the Admin API uses everywhere. The product's title is copied in so that the admin list can show it without a round trip; nothing else about the product is stored, because Shopify owns it. Status is a plain string column with three values.

database/migrations/2026_10_23_100100_create_reviews_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('reviews', function (Blueprint $table) {
            $table->id();
            $table->foreignId('shop_id')->constrained()->cascadeOnDelete();
            // Shopify's global ID, e.g. "gid://shopify/Product/8501234567890".
            $table->string('product_id');
            $table->string('product_title');
            $table->string('author_name');
            $table->string('author_email')->nullable();
            $table->unsignedTinyInteger('rating');
            $table->string('title')->nullable();
            $table->text('body');
            $table->string('status')->default('pending'); // pending | approved | rejected
            $table->timestamps();

            $table->index(['shop_id', 'product_id', 'status']);
        });
    }

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

Settings get their own table with one row per shop. Two settings are enough to make the storefront part interesting: whether a visitor's review publishes immediately, and the heading the storefront block shows.

database/migrations/2026_10_23_100200_create_shop_settings_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('shop_settings', function (Blueprint $table) {
            $table->id();
            $table->foreignId('shop_id')->unique()->constrained()->cascadeOnDelete();
            // Publish storefront reviews without a merchant looking at them first.
            $table->boolean('auto_approve')->default(false);
            // Heading of the review block on the storefront.
            $table->string('widget_title')->default('Customer reviews');
            $table->timestamps();
        });
    }

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

app/Models/Review.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Review extends Model
{
    public const STATUSES = ['pending', 'approved', 'rejected'];

    protected $fillable = [
        'product_id', 'product_title', 'author_name', 'author_email',
        'rating', 'title', 'body', 'status',
    ];

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

    public function shop(): BelongsTo
    {
        return $this->belongsTo(Shop::class);
    }
}

app/Models/ShopSettings.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ShopSettings extends Model
{
    protected $fillable = ['auto_approve', 'widget_title'];

    protected $attributes = [
        'auto_approve' => false,
        'widget_title' => 'Customer reviews',
    ];

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

    public function shop(): BelongsTo
    {
        return $this->belongsTo(Shop::class);
    }
}

The shop model gains the two relations. withDefault() on the settings relation means $shop->settings->auto_approve works for a shop that never saved settings; the defaults come from the model's $attributes.

app/Models/Shop.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
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',
        ];
    }

    public function reviews(): HasMany
    {
        return $this->hasMany(Review::class);
    }

    /** Settings always exist from the app's point of view; a shop without a row gets the defaults. */
    public function settings(): HasOne
    {
        return $this->hasOne(ShopSettings::class)->withDefault();
    }

    /** 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();
    }
}

Calling the Admin API on a shop's behalf

Part 2 called adminGraphQLRequest directly in a controller. Every call needs the same two things around it: a token fresh enough to use, and the housekeeping when Shopify says the token is dead. A small class owns both.

app/Shopify/Admin.php:

<?php

namespace App\Shopify;

use App\Models\Shop;
use RuntimeException;
use Shopify\App\ShopifyApp;
use Shopify\App\Types\GQLResult;

/**
 * Admin API calls on behalf of a shop. Wraps the package's GraphQL method with the two
 * things every call needs: a token that is fresh enough, and the housekeeping when
 * Shopify rejects it.
 */
final class Admin
{
    public function __construct(private ShopifyApp $shopify) {}

    /**
     * @param  array<string, mixed>  $variables
     * @param  array<string, mixed>|null  $invalidTokenResponse  from the verify result when
     *                                                           answering an App Home request; null in jobs
     */
    public function query(Shop $shop, string $query, array $variables = [], ?array $invalidTokenResponse = null): GQLResult
    {
        $this->ensureFreshToken($shop);

        $result = $this->shopify->adminGraphQLRequest(
            $query,
            shop: $shop->shop,
            accessToken: $shop->access_token,
            apiVersion: config('shopify.api_version'),
            invalidTokenResponse: $invalidTokenResponse,
            variables: $variables ?: null,
        );

        // Shopify no longer accepts the token: the app was uninstalled or the token was
        // revoked. Drop it so the next App Home visit exchanges a new one.
        if (! $result->ok && $result->log->code === 'unauthorized') {
            $shop->forgetAccessToken();
        }

        return $result;
    }

    /**
     * Inside a request the middleware already did this. In a queued job nobody has, and
     * an access token lives for an hour, so a job that runs later must refresh first.
     */
    private function ensureFreshToken(Shop $shop): void
    {
        $token = $shop->accessToken()
            ?? throw new RuntimeException("Shop {$shop->shop} has no access token; the app is not installed.");

        $refresh = $this->shopify->refreshTokenExchangedAccessToken($token);

        if (! $refresh->ok) {
            $shop->forgetAccessToken();
            throw new RuntimeException("Could not refresh the access token for {$shop->shop}: {$refresh->log->code}");
        }

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

The refresh step is the reason this class exists. Inside a request, the middleware already refreshed the token, and the call returns immediately. In a queued job nothing has, and a job that runs more than an hour after the merchant's last visit holds an expired token. Calling refreshTokenExchangedAccessToken first, unconditionally, is what the package's README asks for, and it means jobs and requests share one code path.

invalidTokenResponse is null by default. Part 2 explained what passing it does: it lets the package turn a rejected token into a "retry with a fresh ID token" response for App Bridge. A job has no App Bridge to answer, so it passes nothing and the call simply fails, which the queue then retries.

Endpoints for the admin UI

Four controllers, all behind the App Home middleware, all reading the verified shop from the request attributes. The review controller is ordinary Laravel; the one thing to notice is that every lookup goes through $shop->reviews(), so a review ID from another shop is a 404 rather than someone else's data. Laravel's route-model binding would happily find any review by ID, which is why the routes take a plain {id}.

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

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\SyncProductRating;
use App\Models\Review;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ReviewController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $shop = $request->attributes->get('shop');

        $reviews = $shop->reviews()
            ->when($request->query('status'), fn ($q, $status) => $q->where('status', $status))
            ->when($request->query('product_id'), fn ($q, $id) => $q->where('product_id', $id))
            ->latest()
            ->paginate(20);

        return response()->json($reviews);
    }

    public function store(Request $request): JsonResponse
    {
        $shop = $request->attributes->get('shop');

        $data = $request->validate([
            'product_id' => ['required', 'string', 'starts_with:gid://shopify/Product/'],
            'product_title' => ['required', 'string', 'max:255'],
            'author_name' => ['required', 'string', 'max:100'],
            'author_email' => ['nullable', 'email', 'max:255'],
            'rating' => ['required', 'integer', 'between:1,5'],
            'title' => ['nullable', 'string', 'max:150'],
            'body' => ['required', 'string', 'max:3000'],
            'status' => ['sometimes', Rule::in(Review::STATUSES)],
        ]);

        $review = $shop->reviews()->create($data + ['status' => 'approved']);

        SyncProductRating::dispatch($shop, $review->product_id);

        return response()->json($review, 201);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $shop = $request->attributes->get('shop');
        // Scoped lookup: a review ID from another shop is a 404, not someone else's data.
        $review = $shop->reviews()->findOrFail($id);

        $data = $request->validate([
            'status' => ['sometimes', Rule::in(Review::STATUSES)],
            'rating' => ['sometimes', 'integer', 'between:1,5'],
            'title' => ['sometimes', 'nullable', 'string', 'max:150'],
            'body' => ['sometimes', 'string', 'max:3000'],
        ]);

        $review->update($data);

        if ($review->wasChanged(['status', 'rating'])) {
            SyncProductRating::dispatch($shop, $review->product_id);
        }

        return response()->json($review);
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        $shop = $request->attributes->get('shop');
        $review = $shop->reviews()->findOrFail($id);

        $review->delete();

        SyncProductRating::dispatch($shop, $review->product_id);

        return response()->json(status: 204);
    }
}

Product search asks Shopify. The query uses Shopify's search syntax; title:*rug* matches "Braided Jute Rug" and "Bhadohi Wool Rug". The featuredMedia path is the current way to get a product's image; featuredImage still works but is on its way out.

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

<?php

namespace App\Http\Controllers\Api;

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

/**
 * Product search for the admin UI's "add a review" form. The app stores a product's ID
 * and title with each review; everything else about the product stays in Shopify.
 */
class ProductController extends Controller
{
    public function index(Request $request, Admin $admin): JsonResponse|Response
    {
        $shop = $request->attributes->get('shop');
        $search = trim((string) $request->query('query', ''));

        $result = $admin->query($shop, <<<'GRAPHQL'
            query SearchProducts($query: String) {
              products(first: 10, query: $query, sortKey: TITLE) {
                nodes {
                  id
                  title
                  handle
                  featuredMedia { preview { image { url(transform: { maxWidth: 80, maxHeight: 80 }) } } }
                }
              }
            }
            GRAPHQL, [
            // Shopify's search syntax; "title:*shirt*" finds "T-shirt" and "Shirt, blue".
            'query' => $search === '' ? null : "title:*{$search}*",
        ], invalidTokenResponse: $request->attributes->get('shopify')->invalidTokenResponse);

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

        $products = array_map(fn (array $node) => [
            'id' => $node['id'],
            'title' => $node['title'],
            'handle' => $node['handle'],
            'image' => $node['featuredMedia']['preview']['image']['url'] ?? null,
        ], $result->data['products']['nodes']);

        return response()->json($products);
    }
}

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

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        return response()->json($request->attributes->get('shop')->settings);
    }

    public function update(Request $request): JsonResponse
    {
        $shop = $request->attributes->get('shop');

        $data = $request->validate([
            'auto_approve' => ['required', 'boolean'],
            'widget_title' => ['required', 'string', 'max:80'],
        ]);

        // updateOrCreate because the row does not exist until the merchant saves once.
        $settings = $shop->settings()->updateOrCreate([], $data);

        return response()->json($settings);
    }
}

routes/api.php:

<?php

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 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']);
});

The rating metafields

A storefront that showed "4.5 out of 5" by calling the app on every product page would be slow and would put the app on the critical path of someone's shop. Shopify's answer is metafields: structured values attached to a product, readable from Liquid in a theme. The app writes two per product, the average rating of its approved reviews and the count, whenever a review is created, moderated or deleted. Part 6 reads them from the storefront block in one line of Liquid.

Metafields need definitions, which say what type a value has and who may read it. An app declares its own definitions in shopify.app.toml, under a namespace that belongs to the app alone; no other app and no merchant can change them. The reviewmini segment becomes $app:reviewmini in GraphQL and app--<app id>--reviewmini in responses. Storefront read access is what lets Liquid see the values.

Added to shopify.app.toml:

# App-owned product metafields, created on every shop by `shopify app deploy`. The
# storefront block in part 6 reads them, so they are public on the storefront.
[product.metafields.reviewmini.rating_average]
name = "Rating average"
description = "Average rating of approved ReviewMini reviews, 1 to 5"
type = "number_decimal"
access.storefront = "public_read"

[product.metafields.reviewmini.rating_count]
name = "Rating count"
description = "Number of approved ReviewMini reviews"
type = "number_integer"
access.storefront = "public_read"

Declarations reach Shopify with shopify app deploy, which creates a new version of the app record. Before running it, set application_url and redirect_urls in the TOML to your tunnel's address; the file is pushed as a whole, and the placeholders from part 1 would otherwise replace the URLs the dev command set. With the named tunnel from part 1 this is a one-time edit. With the CLI's tunnel, run shopify app dev again after each deploy and let it put the URLs back.

shopify app deploy --message "Part 3: product rating metafields"
Releasing a new app version as part of ReviewMini
Running validation ...
Releasing an app version ...

╭─ success ───────────────────────────────────────────────────────────────╮
│  New version released to users.                                         │
│  reviewmini-2                                                           │
│  Part 3: product rating metafields                                      │
╰─────────────────────────────────────────────────────────────────────────╯

The file as it stands at the end of part 3:

# The app's configuration. `shopify app config link` created the app record and wrote client_id;
# `shopify app dev` keeps application_url and redirect_urls pointed at the current tunnel;
# `shopify app deploy` uploads the rest (scopes, webhooks, events) to Shopify.
client_id = "fe474784a47726e6213eb880b74c9852"
name = "ReviewMini"
application_url = "https://reviewmini.shipbytes.dev"
embedded = true

[access_scopes]
scopes = "read_products,write_products"

[webhooks]
api_version = "2026-10"

[build]
automatically_update_urls_on_dev = true

[auth]
# Token exchange needs no OAuth redirect, but the CLI still wants one entry here and
# rewrites it to the tunnel during `shopify app dev`.
redirect_urls = [ "https://reviewmini.shipbytes.dev/auth/patch-id-token" ]

# App-owned product metafields, created on every shop by `shopify app deploy`. The
# storefront block in part 6 reads them, so they are public on the storefront.
[product.metafields.reviewmini.rating_average]
name = "Rating average"
description = "Average rating of approved ReviewMini reviews, 1 to 5"
type = "number_decimal"
access.storefront = "public_read"

[product.metafields.reviewmini.rating_count]
name = "Rating count"
description = "Number of approved ReviewMini reviews"
type = "number_integer"
access.storefront = "public_read"

The job computes the two numbers and sends one metafieldsSet mutation. It is queued because it is an Admin API round trip the merchant should not wait for, and because part 5 dispatches it from webhooks too.

app/Jobs/SyncProductRating.php:

<?php

namespace App\Jobs;

use App\Models\Shop;
use App\Shopify\Admin;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

/**
 * Writes a product's approved-review average and count to two app-owned metafields,
 * where the storefront (part 6) reads them. Queued because it is an Admin API round
 * trip the merchant should not wait for, and because it runs after webhooks too.
 */
class SyncProductRating implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    public function __construct(public Shop $shop, public string $productId) {}

    public function handle(Admin $admin): void
    {
        $approved = $this->shop->reviews()
            ->where('product_id', $this->productId)
            ->where('status', 'approved');

        $count = $approved->count();
        $average = $count === 0 ? 0 : round($approved->avg('rating'), 2);

        $result = $admin->query($this->shop, <<<'GRAPHQL'
            mutation SyncProductRating($metafields: [MetafieldsSetInput!]!) {
              metafieldsSet(metafields: $metafields) {
                metafields { key value }
                userErrors { field message }
              }
            }
            GRAPHQL, [
            'metafields' => [
                [
                    'ownerId' => $this->productId,
                    'namespace' => '$app:reviewmini',
                    'key' => 'rating_average',
                    'type' => 'number_decimal',
                    'value' => number_format($average, 2, '.', ''),
                ],
                [
                    'ownerId' => $this->productId,
                    'namespace' => '$app:reviewmini',
                    'key' => 'rating_count',
                    'type' => 'number_integer',
                    'value' => (string) $count,
                ],
            ],
        ]);

        if (! $result->ok) {
            // Let the queue retry transient failures; "unauthorized" already dropped the token.
            throw new \RuntimeException("metafieldsSet failed for {$this->shop->shop}: {$result->log->code}");
        }

        if ($errors = $result->data['metafieldsSet']['userErrors']) {
            Log::warning('metafieldsSet user errors', ['shop' => $this->shop->shop, 'errors' => $errors]);
        }
    }
}

Laravel 13 defaults to the database queue, so the job needs a worker. For the rest of the series, run one next to the app:

php artisan queue:listen --tries=1

Part 4 folds this into shopify app dev.

Trying it without a UI

The admin UI arrives in part 4. Until then the endpoints can be exercised with a signed ID token, minted the way the tests do it. Three requests and a look at Shopify:

# create two reviews for a product, then list them
curl -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"product_id":"gid://shopify/Product/15918744600945","product_title":"Ajrakh Cushion Cover","author_name":"Asha","rating":5,"title":"Beautiful","body":"Lovely print, colours exactly as pictured."}' \
  https://reviewmini.shipbytes.dev/api/reviews
curl -H "Authorization: Bearer $TOKEN" "https://reviewmini.shipbytes.dev/api/reviews"
{"current_page":1,"data":[{"id":2,"rating":4,"status":"approved","author_name":"Ravi",…},{"id":1,"rating":5,…}],"total":2,…}

The worker ran two jobs, 615 ms and 487 ms, and the product's metafields in Shopify read:

[{"namespace":"app--439072489473--reviewmini","key":"rating_average","value":"4.5","type":"number_decimal"},
 {"namespace":"app--439072489473--reviewmini","key":"rating_count","value":"2","type":"number_integer"}]

Tests

The review endpoints test the same way as part 2, with the queue faked so that no job reaches Shopify. The scoping test is the important one.

tests/Feature/ReviewApiTest.php:

<?php

namespace Tests\Feature;

use App\Jobs\SyncProductRating;
use App\Models\Shop;
use Firebase\JWT\JWT;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

class ReviewApiTest extends TestCase
{
    use RefreshDatabase;

    private Shop $shop;

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

        Queue::fake();

        $this->shop = Shop::create(['shop' => 'test-shop']);
        $this->shop->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 array<string, string> */
    private function authHeaders(string $shop = 'test-shop'): array
    {
        $now = time();

        $token = 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',
        ], config('shopify.api_secret'), 'HS256');

        return ['Authorization' => "Bearer {$token}"];
    }

    public function test_a_review_is_created_and_the_rating_sync_is_queued(): void
    {
        $response = $this->postJson('/api/reviews', [
            'product_id' => 'gid://shopify/Product/1',
            'product_title' => 'Cushion cover',
            'author_name' => 'Asha',
            'rating' => 5,
            'body' => 'Lovely print.',
        ], $this->authHeaders());

        $response->assertCreated()->assertJsonPath('status', 'approved');
        $this->assertDatabaseHas('reviews', ['shop_id' => $this->shop->id, 'rating' => 5]);
        Queue::assertPushed(SyncProductRating::class, fn ($job) => $job->productId === 'gid://shopify/Product/1');
    }

    public function test_invalid_input_is_rejected(): void
    {
        $this->postJson('/api/reviews', ['rating' => 9], $this->authHeaders())
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['product_id', 'author_name', 'rating', 'body']);
    }

    public function test_reviews_are_scoped_to_the_requesting_shop(): void
    {
        $other = Shop::create(['shop' => 'other-shop']);
        $review = $other->reviews()->create([
            'product_id' => 'gid://shopify/Product/1', 'product_title' => 'X',
            'author_name' => 'Someone', 'rating' => 1, 'body' => 'Not yours', 'status' => 'approved',
        ]);

        $this->getJson('/api/reviews', $this->authHeaders())->assertOk()->assertJsonPath('total', 0);
        $this->patchJson("/api/reviews/{$review->id}", ['status' => 'rejected'], $this->authHeaders())->assertNotFound();
    }

    public function test_changing_the_status_requeues_the_rating_sync(): void
    {
        $review = $this->shop->reviews()->create([
            'product_id' => 'gid://shopify/Product/1', 'product_title' => 'X',
            'author_name' => 'Asha', 'rating' => 5, 'body' => 'Lovely', 'status' => 'pending',
        ]);

        $this->patchJson("/api/reviews/{$review->id}", ['status' => 'approved'], $this->authHeaders())
            ->assertOk()->assertJsonPath('status', 'approved');

        Queue::assertPushed(SyncProductRating::class, 1);
    }

    public function test_settings_have_defaults_and_can_be_saved(): void
    {
        $this->getJson('/api/settings', $this->authHeaders())
            ->assertOk()->assertJsonPath('auto_approve', false);

        $this->putJson('/api/settings', ['auto_approve' => true, 'widget_title' => 'What customers say'], $this->authHeaders())
            ->assertOk()->assertJsonPath('widget_title', 'What customers say');

        $this->assertDatabaseHas('shop_settings', ['shop_id' => $this->shop->id, 'auto_approve' => true]);
    }
}

When it goes wrong

shopify app deploy succeeded and the admin now shows a 404 for the app. The deploy pushed the placeholder application_url from the TOML. Set it to the tunnel address and deploy again, or run shopify app dev, which restores it.

metafieldsSet returns user errors about the namespace or type. The definitions have not been deployed to this shop, or the type in the job differs from the declaration. Query metafieldDefinitions(ownerType: PRODUCT, namespace: "$app:reviewmini") to see what Shopify has.

The job runs but the metafields do not change. Check the queue is working the right connection; php artisan queue:listen with no .env changes uses the database queue the app writes to. A QUEUE_CONNECTION=sync in .env is also fine for development.

Jobs that ran fine yesterday fail with unauthorized today. The access token expired and nothing refreshed it. The Admin class above refreshes before every call; check the job uses it rather than calling the package directly.

A product search returns nothing for a title you can see in the admin. The search syntax is title:*word*; a bare word searches several fields but not as a substring.

Part 4 builds the admin UI on these endpoints with React, TypeScript and Polaris 2 web components.

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.