Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ All notable changes to this plugin are documented here. The format follows [Keep

## [Unreleased]

## [1.1.0] - Unreleased

### Added

- Optional client-credentials authentication for apps and stores in the same Shopify organization, with encrypted expiring tokens and automatic renewal.
- Connection tests identify missing scopes for the enabled sync directions. Validation errors never flash credentials or client IDs.

## [1.0.3] - Unreleased

### Fixed
Expand Down
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ The plugin needs the Inventoros **queue worker** and **scheduler** running (`sho

## Set up a store

In short: create a custom app in the Shopify admin with the scopes `read_products`, `write_products`, `read_inventory`, `write_inventory`, `read_locations` and `read_orders`, install it, then paste its Admin API access token and API secret key under **Shopify > Connect a store**. Map locations to warehouses, run a full sync and confirm the SKU suggestions.
Install a Shopify app with the scopes `read_products`, `write_products`, `read_inventory`, `write_inventory`, `read_locations` and `read_orders`, then connect under **Shopify > Connect a store** using client credentials for an app and store in your own Shopify organization, or an existing Admin API access token and API secret key. Map locations to warehouses, run a full sync and confirm the SKU suggestions.

The step-by-step guide, with what each status means: **[docs/setup.md](docs/setup.md)**. How orders, stock, products, webhooks and retries behave: **[docs/sync.md](docs/sync.md)**.

Expand Down Expand Up @@ -143,3 +143,21 @@ queue retry policy. Mutations keep their existing idempotency and queue retries.

Query shapes are bounded below Shopify's default 1,000-point single-query limit.
Shopify can assign field costs, so response throttle metadata remains authoritative.

### Client credentials and missing scopes

Choose **App client credentials** for apps and stores in the same Shopify
organization. Enter the app client ID and API secret key (its client secret).
The server exchanges these for an expiring token, keeps it encrypted alongside
its expiry, and renews it two minutes before expiration before each API request, including later pages of an already-running client.
A connection-row lock prevents concurrent workers from minting duplicate tokens.
Manual tokens remain supported; they are never replaced automatically.

Connection tests name missing scopes for the enabled sync directions. Updating
app permissions may require reinstalling/reauthorizing the app before testing
again. Secrets and client IDs are write-only and excluded from validation-session
old input. Failed token exchanges report sanitized errors without provider bodies.
No OAuth redirect/authorization-code flow is provided by this option.

See [Shopify client credentials](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant)
and [token lifetimes](https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens).
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "Shopify",
"description": "Connect Inventoros with Shopify for asynchronous two-way product, inventory and order sync, with webhooks, retries, mappings and sync health checks.",
"version": "1.0.3",
"version": "1.1.0",
"author": "Inventoros",
"author_url": "https://inventoros.com",
"license": "AGPL-3.0-or-later",
Expand Down
29 changes: 23 additions & 6 deletions src/Http/Controllers/ActionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

namespace Inventoros\Plugins\Shopify\Http\Controllers;

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Inventoros\Plugins\Shopify\Jobs\ImportOrder;
use Inventoros\Plugins\Shopify\Jobs\PushInventory;
use Inventoros\Plugins\Shopify\Jobs\RunSync;
Expand All @@ -29,7 +31,7 @@
use Inventoros\Plugins\Shopify\Sync\InventoryPush;
use Inventoros\Plugins\Shopify\Sync\Locations;
use Inventoros\Plugins\Shopify\Sync\OrderImporter;
use InvalidArgumentException;
use Inventoros\Plugins\Shopify\Sync\SkuMatcher;

/**
* Every write the pages make, under /p/shopify/actions (web group: session,
Expand All @@ -55,7 +57,7 @@ public function storeConnection(Request $request): RedirectResponse
'acting_user_id' => $user->id,
'name' => $data['name'],
'shop_domain' => $data['shop_domain'],
'credentials' => ['access_token' => $data['access_token'], 'webhook_secret' => $data['webhook_secret']],
'credentials' => array_filter(['access_token' => $data['access_token'] ?? null, 'webhook_secret' => $data['webhook_secret'], 'client_id' => $data['client_id'] ?? null]),
'status' => Connection::PENDING,
'settings' => SyncPolicy::sanitize($data + ['orders_since' => $data['orders_since'] ?? now()->toDateString()]),
]);
Expand All @@ -74,13 +76,23 @@ public function updateConnection(Request $request, int $connection): RedirectRes
$credentials = $record->credentials ?? [];
$retest = false;

foreach (['access_token', 'webhook_secret'] as $key) {
foreach (['access_token', 'webhook_secret', 'client_id'] as $key) {
if (($data[$key] ?? '') !== '') {
$credentials[$key] = $data[$key];
$retest = true;
}
}

if ($data['auth_mode'] !== $record->setting('auth_mode', 'token')) {
$retest = true;
}
if ($data['auth_mode'] === 'client_credentials' && $retest) {
unset($credentials['access_token'], $credentials['token_expires_at']);
}
if ($data['auth_mode'] === 'token') {
unset($credentials['client_id'], $credentials['token_expires_at']);
}

$record->forceFill([
'name' => $data['name'],
'acting_user_id' => $user->id,
Expand Down Expand Up @@ -221,7 +233,7 @@ public function linkMapping(Request $request, int $mapping): RedirectResponse
}

$data = $request->validate(['sku' => ['required', 'string', 'max:191']]);
$candidates = \Inventoros\Plugins\Shopify\Sync\SkuMatcher::candidates($organizationId, $data['sku']);
$candidates = SkuMatcher::candidates($organizationId, $data['sku']);

if (count($candidates) !== 1) {
throw ValidationException::withMessages(['sku' => count($candidates) === 0
Expand Down Expand Up @@ -369,12 +381,17 @@ private function validateConnection(Request $request, ?Connection $existing): ar
$request->merge(['shop_domain' => ShopDomain::normalize((string) $request->input('shop_domain', ''))]);
}

$request->merge(['auth_mode' => $request->input('auth_mode', $existing?->setting('auth_mode', 'token') ?? 'token')]);
$clientMode = $request->input('auth_mode') === 'client_credentials';
$secret = $existing === null ? 'required' : 'nullable';
$tokenRequired = ! $clientMode && ($existing === null || $existing->setting('auth_mode', 'token') !== 'token');

$data = $request->validate([
'name' => ['required', 'string', 'max:120'],
'shop_domain' => $existing === null ? ['required', 'string', 'max:191'] : ['exclude'],
'access_token' => [$secret, 'string', 'max:255'],
'auth_mode' => ['required', Rule::in(['token', 'client_credentials'])],
'client_id' => [$clientMode && ! $existing?->hasCredential('client_id') ? 'required' : 'nullable', 'string', 'max:255'],
'access_token' => [$tokenRequired ? 'required' : 'nullable', 'string', 'max:255'],
'webhook_secret' => [$secret, 'string', 'max:255'],
'stock_source' => ['required', Rule::in(SyncPolicy::STOCK_SOURCES)],
'product_source' => ['required', Rule::in(SyncPolicy::PRODUCT_SOURCES)],
Expand All @@ -390,7 +407,7 @@ private function validateConnection(Request $request, ?Connection $existing): ar
return $data;
}

private function authorizeManage(Request $request): \App\Models\User
private function authorizeManage(Request $request): User
{
$user = $request->user();

Expand Down
3 changes: 2 additions & 1 deletion src/Http/Controllers/PagesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
use Inventoros\Plugins\Shopify\Kit\Models\SyncLog;
use Inventoros\Plugins\Shopify\Kit\Models\SyncRun;
use Inventoros\Plugins\Shopify\Shopify\ShopifyClient;
use Inventoros\Plugins\Shopify\ShopifyPlugin;
use Inventoros\Plugins\Shopify\Shopify\SyncPolicy;
use Inventoros\Plugins\Shopify\ShopifyPlugin;
use Inventoros\Plugins\Shopify\Support\Core;
use Inventoros\Plugins\Shopify\Support\Permissions;
use Inventoros\Plugins\Shopify\Sync\Catalog;
Expand Down Expand Up @@ -202,6 +202,7 @@ public static function connection(Connection $connection): array
'currency' => ($connection->remote ?? [])['currency'] ?? null,
'webhooks_registered_at' => ($connection->remote ?? [])['webhooks_registered_at'] ?? null,
'has_access_token' => $connection->hasCredential('access_token'),
'has_client_id' => $connection->hasCredential('client_id'),
'has_webhook_secret' => $connection->hasCredential('webhook_secret'),
'last_tested_at' => $connection->last_tested_at?->toIso8601String(),
'webhook_url' => RegisterWebhooks::callbackUrl($connection),
Expand Down
79 changes: 79 additions & 0 deletions src/Shopify/AccessTokens.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

declare(strict_types=1);

namespace Inventoros\Plugins\Shopify\Shopify;

use Carbon\Carbon;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Inventoros\Plugins\Shopify\Kit\Exceptions\PermanentError;
use Inventoros\Plugins\Shopify\Kit\Exceptions\RateLimited;
use Inventoros\Plugins\Shopify\Kit\Exceptions\TransientError;
use Inventoros\Plugins\Shopify\Kit\Models\Connection;
use Inventoros\Plugins\Shopify\Kit\Support\RetryAfter;

/** Tokens for apps and stores owned by the same Shopify organization. */
final class AccessTokens
{
public function token(Connection $connection): string
{
$connection->refresh();
if (! ShopDomain::valid($connection->shop_domain)) {
throw new PermanentError('The shop domain is not a myshopify.com address.');
}
if ($connection->setting('auth_mode', 'token') !== 'client_credentials') {
return $connection->credential('access_token')
?? throw new PermanentError('This connection has no access token. Add one in the connection settings.', authentication: true);
}

$token = DB::transaction(function () use ($connection) {
$locked = Connection::forOrganization($connection->organization_id)->whereKey($connection->id)->lockForUpdate()->firstOrFail();
if ($locked->setting('auth_mode', 'token') !== 'client_credentials') {
return $locked->credential('access_token')
?? throw new PermanentError('The connection has no saved access token.', authentication: true);
}
$credentials = $locked->credentials ?? [];
$expires = $credentials['token_expires_at'] ?? null;
if (is_string($expires) && $locked->hasCredential('access_token') && Carbon::parse($expires)->gt(now()->addMinutes(2))) {
return $locked->credential('access_token');
}
if (! $locked->hasCredential('client_id') || ! $locked->hasCredential('webhook_secret')) {
throw new PermanentError('Add the app client ID and API secret key for client-credentials authentication.', authentication: true);
}
try {
$response = Http::asForm()->acceptJson()->timeout(30)->connectTimeout(10)
->withOptions(['allow_redirects' => false])
->post('https://'.$locked->shop_domain.'/admin/oauth/access_token', [
'grant_type' => 'client_credentials', 'client_id' => $locked->credential('client_id'),
'client_secret' => $locked->credential('webhook_secret'),
]);
} catch (ConnectionException) {
throw new TransientError('Could not reach Shopify to renew the access token.');
}
if ($response->status() === 429) {
throw new RateLimited('Shopify limited token requests.', RetryAfter::seconds($response->header('Retry-After'), 5));
}
if ($response->serverError()) {
throw new TransientError('Shopify could not renew the access token. Retry later.');
}
if (! $response->successful()) {
throw new PermanentError('Shopify refused the app credentials. Check the client ID/secret, app installation and that the app and store belong to the same Shopify organization.', authentication: true);
}
$body = $response->json();
if (! is_array($body) || ! is_string($body['access_token'] ?? null) || $body['access_token'] === ''
|| ! is_numeric($body['expires_in'] ?? null) || (int) $body['expires_in'] <= 120) {
throw new TransientError('Shopify returned an invalid token response. Retry the connection test.');
}
$locked->forceFill(['credentials' => array_replace($credentials, [
'access_token' => $body['access_token'], 'token_expires_at' => now()->addSeconds((int) $body['expires_in'])->toIso8601String(),
])])->save();

return $body['access_token'];
});
$connection->refresh(); // Error/log scrubbing sees the newly minted secret.

return $token;
}
}
14 changes: 3 additions & 11 deletions src/Shopify/ClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Inventoros\Plugins\Shopify\Shopify;

use Inventoros\Plugins\Shopify\Kit\Exceptions\PermanentError;
use Inventoros\Plugins\Shopify\Kit\Models\Connection;
use Inventoros\Plugins\Shopify\Kit\Support\CostBudget;

Expand All @@ -16,16 +15,9 @@ class ClientFactory
{
public function make(Connection $connection): ShopifyClient
{
$token = $connection->credential('access_token');
$token = app(AccessTokens::class)->token($connection);

if ($token === null) {
throw new PermanentError('This connection has no access token. Add one in the connection settings.', authentication: true);
}

if (! ShopDomain::valid($connection->shop_domain)) {
throw new PermanentError('The shop domain is not a myshopify.com address.');
}

return new HttpShopifyClient($connection->shop_domain, $token, CostBudget::for($connection->id));
return new HttpShopifyClient($connection->shop_domain, $token, CostBudget::for($connection->id),
tokenResolver: fn () => app(AccessTokens::class)->token($connection));
}
}
8 changes: 7 additions & 1 deletion src/Shopify/HttpShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ final class HttpShopifyClient implements ShopifyClient

public function __construct(
private readonly string $shopDomain,
private readonly string $accessToken,
private string $accessToken,
private readonly CostBudget $budget,
private readonly string $apiVersion = self::API_VERSION,
private readonly ?\Closure $tokenResolver = null,
) {}

public function shop(): array
Expand All @@ -52,6 +53,7 @@ public function shop(): array
'domain' => (string) ($shop['myshopifyDomain'] ?? $this->shopDomain),
'currency' => (string) ($shop['currencyCode'] ?? ''),
'plan' => $shop['plan']['displayName'] ?? null,
'scopes' => array_column($data['currentAppInstallation']['accessScopes'] ?? [], 'handle'),
];
}

Expand Down Expand Up @@ -222,6 +224,9 @@ public function subscribeWebhook(string $topic, string $callbackUrl): void
*/
private function query(string $query, array $variables, int $expectedCost): array
{
if ($this->tokenResolver !== null) {
$this->accessToken = ($this->tokenResolver)();
}
$this->budget->reserve($expectedCost);

try {
Expand All @@ -231,6 +236,7 @@ private function query(string $query, array $variables, int $expectedCost): arra
])
->timeout(30)
->connectTimeout(10)
->withOptions(['allow_redirects' => false])
->post($this->endpoint(), ['query' => $query, 'variables' => (object) array_filter($variables, fn ($v) => $v !== null)]);
} catch (ConnectionException $error) {
throw new TransientError('Could not reach Shopify: '.$this->clean($error->getMessage()));
Expand Down
1 change: 1 addition & 0 deletions src/Shopify/Queries.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ final class Queries
public const SHOP = <<<'GQL'
query Shop {
shop { id name myshopifyDomain currencyCode plan { displayName } }
currentAppInstallation { accessScopes { handle } }
}
GQL;

Expand Down
2 changes: 1 addition & 1 deletion src/Shopify/ShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ interface ShopifyClient
public const API_VERSION = '2026-07';

/**
* @return array{id: string, name: string, domain: string, currency: string, plan: string|null}
* @return array{id: string, name: string, domain: string, currency: string, plan: string|null, scopes: array<int, string>}
*/
public function shop(): array;

Expand Down
18 changes: 18 additions & 0 deletions src/Shopify/ShopifyConnectionTester.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,24 @@ public function test(Connection $connection): TestResult
return TestResult::failed($error->getMessage());
}

$policy = SyncPolicy::for($connection);
$required = ['read_products', 'read_inventory', 'read_locations'];
if ($policy->pushesStock()) {
$required[] = 'write_inventory';
}
if ($policy->pushesProducts()) {
$required[] = 'write_products';
}
if ($policy->importsOrders()) {
$required[] = 'read_orders';
}
$granted = $shop['scopes'] ?? [];
$missing = array_values(array_filter($required, fn ($scope) => ! in_array($scope, $granted, true)
&& ! (str_starts_with($scope, 'read_') && in_array('write_'.substr($scope, 5), $granted, true))));
if ($missing !== []) {
return TestResult::failed('Missing Shopify access scopes: '.implode(', ', $missing).'. Update the app permissions and reinstall or reauthorize it, then test again.');
}

if (! $connection->hasCredential('webhook_secret')) {
return TestResult::failed('The access token works, but the API secret key is missing: webhooks cannot be verified without it.');
}
Expand Down
5 changes: 5 additions & 0 deletions src/Shopify/SyncPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ final class SyncPolicy
public const PRODUCT_SOURCES = ['shopify', 'inventoros'];

public const DEFAULTS = [
'auth_mode' => 'token',
'stock_source' => 'inventoros',
'product_source' => 'shopify',
'import_orders' => true,
Expand All @@ -52,6 +53,10 @@ public static function sanitize(array $input, array $current = []): array
{
$settings = array_merge(self::DEFAULTS, array_intersect_key($current, self::DEFAULTS));

if (in_array($input['auth_mode'] ?? null, ['token', 'client_credentials'], true)) {
$settings['auth_mode'] = $input['auth_mode'];
}

if (in_array($input['stock_source'] ?? null, self::STOCK_SOURCES, true)) {
$settings['stock_source'] = $input['stock_source'];
}
Expand Down
7 changes: 7 additions & 0 deletions src/ShopifyPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Illuminate\Console\Application as Artisan;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Facades\Route;
use Inventoros\Plugins\Shopify\Console\PruneCommand;
use Inventoros\Plugins\Shopify\Console\SyncCommand;
Expand Down Expand Up @@ -56,6 +57,12 @@ public function __construct(

public function register(): void
{
$handler = app(ExceptionHandler::class);
// Console renderers can decorate the HTTP handler without exposing
// its validation-input configuration (for example Collision).
if (method_exists($handler, 'dontFlash')) {
$handler->dontFlash(['access_token', 'webhook_secret', 'client_id']);
}
$this->registerServices();
$this->registerTranslations();
$this->registerPermissions();
Expand Down
Loading
Loading