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.3.0] - Unreleased

### Added

- Opt-in records of completed Shopify payments and refunds, using core imported-payment support. Provider IDs prevent duplicates; currencies, manual-entry conflicts, voids and refund limits are checked.
- Refund webhooks refresh transaction history; incomplete histories are refused. Historical financial imports stay silent and current order announcements wait for the complete aggregate to commit.

## [1.2.0] - Unreleased

### Added
Expand Down
35 changes: 32 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ Admins hold both. On Inventoros versions without plugin permissions they fall ba
- Routes follow the plugin route namespace: names `plg.shopify.*`, pages and actions under `/p/shopify/` (the overview moved from `/shopify` to `/p/shopify` in 1.0.1; update bookmarks). The webhook address, `/webhooks/plugins/shopify/{connection}`, is unchanged, so subscriptions registered by 1.0.0 keep delivering and nothing needs re-registering.
- The sidebar item is translated on cores that translate plugin menu items (`label_key`).
- Known limitations and SDK gaps:
- Core has no stock reservations (SDK gap G4): an order placed in Shopify takes stock when it is imported, not when it is placed.
- Orders take stock when imported. External Shopify checkout reservations are not created in Inventoros before the order webhook arrives.
- On cores with variant location stock, each variant syncs its own bins per mapped warehouse. Older cores retain primary-location variant sync. Local and global stock holds reduce pushed availability; warehouse quantities share a single SKU availability budget, allocated primary location first.
- On cores before Inventoros#254, `OrderService::cancel()` takes its actor from the signed-in user, so the plugin signs in the connection's user for that one call when it cancels in a background job. Newer cores take the actor as a parameter and nobody is signed in.
- Fulfillments and tracking are not pushed to Shopify yet; refunds and order edits after import are not applied.
- No public OAuth app yet (custom app tokens only); see [docs/setup.md](docs/setup.md#7-future-a-public-app-with-oauth).
- Fulfillments and tracking are not pushed to Shopify yet; order edits after import are not applied. Completed payment/refund records can be imported with the optional ledger setting.
- Public multi-merchant OAuth installation is not implemented; see [docs/setup.md](docs/setup.md#7-future-a-public-app-with-oauth).

## Develop and test

Expand Down Expand Up @@ -182,3 +182,32 @@ Variant mappings are still required. Orders skipped by the start-date filter in
this version can be revisited as history after changing the range. Manually ignored
records and ignored records with no recorded reason stay ignored. Existing live
orders are never converted into history by changing a setting.

### Payment and refund records

Enable **Record Shopify payments and refunds** after reconciling any manual
payment entries. This optional setting is off by default and requires core's
`OrderPaymentService::recordImported()` API (core PR Inventoros/Inventoros#305).
Older cores retain all existing sync features and show an upgrade hint instead
of enabling payment import. Enabling the setting retests the connection and
registers the refund webhook; scheduled order reconciliation also updates it.

Only successful sales, captures and refunds create ledger records. Pending or
failed transactions and uncaptured authorizations create no receipts. Amounts
and dates come from Shopify transactions in shop currency; a currency mismatch
is refused. There are no calls to capture, charge or refund money in Shopify.
Payment status and balances are derived by core from the imported ledger, never
from a Shopify status label. Actual overpayments remain visible as overpayments.

Provider transaction IDs map to core payment IDs, so repeated webhooks/resyncs
add nothing twice. Conflicting transaction changes and missing mapped payments
need review. Manual voids remain voided. Active manual/unrelated payment rows
block automatic import until reconciled or voided to prevent double counting.
Refunds cannot exceed recorded receipts. Historical imports use the same ledger
path silently, including cancelled orders; live imports announce core payment
hooks only after commit. Importing financial records does not restock returns.

The API reader checks the exact transaction count and refuses incomplete lists
or orders with more than 100 transactions for manual review. It does not
silently import a subset. Financial records and new-order creation are atomic;
an invalid transaction leaves no partial order/payment ledger.
2 changes: 1 addition & 1 deletion bin/package.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
// The folder name inside the archive. bin/rename.php rewrites it.
const SLUG = 'shopify';

const PACKED = ['plugin.json', 'Plugin.php', 'bootstrap.php', 'assets', 'src', 'database', 'hooks', 'lang', 'dist', 'README.md', 'CHANGELOG.md', 'LICENSE'];
const PACKED = ['plugin.json', 'Plugin.php', 'bootstrap.php', 'assets', 'src', 'database', 'hooks', 'lang', 'dist', 'README.md', 'docs/setup.md', 'CHANGELOG.md', 'LICENSE'];

$root = dirname(__DIR__);
$manifest = json_decode((string) file_get_contents($root.'/plugin.json'), true);
Expand Down
37 changes: 20 additions & 17 deletions docs/setup.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Setting up the Shopify connection

This guide connects one Shopify store to one Inventoros organization with a **custom app** and its Admin API access token. You need to be a Shopify store owner or a staff member allowed to develop apps, and an Inventoros user with **Manage Shopify sync** (or **Edit Settings** on cores without plugin permissions).
This guide connects one Shopify store to one Inventoros organization with an installed Shopify app, using client credentials for an app and store in the same Shopify organization or an existing Admin API token. You need to be a Shopify store owner or a staff member allowed to develop apps, and an Inventoros user with **Manage Shopify sync** (or **Edit Settings** on cores without plugin permissions).

## Contents

Expand All @@ -14,24 +14,23 @@ This guide connects one Shopify store to one Inventoros organization with a **cu

## 1. Create the custom app in Shopify

1. In the Shopify admin, open **Settings > Apps and sales channels > Develop apps**. If app development is not enabled yet, choose **Allow custom app development** (store owners only).
2. Choose **Create an app**, name it (for example *Inventoros*) and pick yourself as the developer.
3. Open **Configuration > Admin API integration > Configure** and select these scopes:
1. Create an app in the Shopify Dev Dashboard and install it on the store. Client-credentials authentication requires the app and store to belong to the same Shopify organization.
2. Configure the scopes used by your sync directions:

| Scope | Why |
|-------|-----|
| `read_products` | Read products and variants to map them by SKU |
| `write_products` | Push titles and prices, only when Inventoros owns products |
| `read_products` | Read products and variants for mapping |
| `write_products` | Push titles/prices when Inventoros owns products |
| `read_inventory` | Read inventory levels |
| `write_inventory` | Push stock levels, when Inventoros owns stock |
| `read_locations` | Read your locations to map them to warehouses |
| `read_orders` | Import orders (Shopify serves the last 60 days; add `read_all_orders` if you import older ones) |
| `write_inventory` | Push stock when Inventoros owns stock |
| `read_locations` | Map locations to warehouses |
| `read_orders` | Import orders and their transactions |
| `read_all_orders` | Approved access to orders older than 60 days |

4. Save, open **API credentials** and choose **Install app**.
5. Reveal and copy the **Admin API access token** (it starts with `shpat_` and is shown once).
6. On the same page, copy the **API secret key**. Shopify signs every webhook with it; Inventoros refuses any webhook it cannot verify.
3. Copy the app **Client ID** and **Client secret** from its settings. In Inventoros, the API secret key field holds that client secret and verifies incoming webhooks. Tokens are acquired and renewed automatically in client-credentials mode; the Dev Dashboard does not show a permanent token for this grant.
4. Existing manually obtained Admin API tokens remain supported with the app's API secret key. Select the saved-token authentication mode for these. A public multi-merchant OAuth installation flow is not provided here.

If your store no longer offers custom app development in the admin, create the app in the Shopify Dev Dashboard instead, give it the same scopes, install it on the store, and use its Admin API access token and client secret in the same two fields.
See [Shopify's client-credentials setup](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant).

## 2. Connect it in Inventoros

Expand All @@ -41,14 +40,18 @@ Open **Shopify** in the sidebar (`/p/shopify`) and fill in **Connect a store**:
|-------|-------|
| Name | Anything that tells your stores apart |
| Shop domain | `your-store.myshopify.com` (the handle alone, `your-store`, also works). Custom storefront domains are not Admin API hosts and are refused. |
| Admin API access token | The `shpat_...` token |
| API secret key | The secret from step 1.6 |
| Authentication | App client credentials for stores in your own Shopify organization, or a saved Admin API token |
| App client ID | The app client ID in client-credentials mode |
| Admin API access token | Your existing token in saved-token mode |
| API secret key | The app client secret used to verify webhooks |
| Who owns stock levels | **Inventoros** pushes Inventoros quantities to Shopify; **Shopify** applies Shopify's quantities to Inventoros. Pick one owner. |
| Who owns product names and prices | **Shopify** copies Shopify edits into Inventoros; **Inventoros** pushes Inventoros edits to Shopify. |
| Import Shopify orders | On by default |
| Import orders placed on or after | Today by default, so old orders are not imported by accident |
| Import orders before this date as history | Optional cutoff (UTC); earlier orders do not change stock or announce new orders |
| Record Shopify payments and refunds | Optional, off by default; requires imported-payment support in core and reconciliation of manual entries |

**Save and test** stores the token and secret encrypted and queues a connection test. The page never waits on Shopify: refresh after a few seconds. When the test passes the store shows **Healthy**, the plugin registers its webhooks and reads your locations. If it fails, the card shows why (a wrong token, missing scopes, a token for another store).
**Save and test** stores credentials encrypted and queues a connection test. The page never waits on Shopify: refresh after a few seconds. When the test passes the store shows **Healthy**, the plugin registers its webhooks and reads your locations. If it fails, the card shows why (a wrong token, missing scopes, a token for another store).

The background work needs the Inventoros queue worker and scheduler running (on cPanel the scheduler also drains the queue; see the core's CPANEL.md).

Expand Down Expand Up @@ -91,4 +94,4 @@ Place a test order in Shopify (enable **Also import test orders** first, or use

## 7. Future: a public app with OAuth

Version 1 connects with a custom app's access token, one store at a time. A public Shopify app installed through OAuth (an install link, offline access tokens, Shopify's mandatory privacy webhooks) is planned; the connection model already keeps credentials as an encrypted set so an OAuth token can replace the custom app token without a data migration.
The plugin connects one store at a time with app client credentials or an existing Admin API token. A public Shopify app installed through OAuth (an install link, offline access tokens, Shopify's mandatory privacy webhooks) is planned; the connection model already keeps credentials as an encrypted set so an OAuth token can replace the custom app token without a data migration.
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.2.0",
"version": "1.3.0",
"author": "Inventoros",
"author_url": "https://inventoros.com",
"license": "AGPL-3.0-or-later",
Expand Down
10 changes: 10 additions & 0 deletions src/Http/Controllers/ActionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use Inventoros\Plugins\Shopify\Sync\InventoryPush;
use Inventoros\Plugins\Shopify\Sync\Locations;
use Inventoros\Plugins\Shopify\Sync\OrderImporter;
use Inventoros\Plugins\Shopify\Sync\Payments;
use Inventoros\Plugins\Shopify\Sync\SkuMatcher;

/**
Expand Down Expand Up @@ -93,6 +94,10 @@ public function updateConnection(Request $request, int $connection): RedirectRes
unset($credentials['client_id'], $credentials['token_expires_at']);
}

if (($data['import_payments'] ?? false) && ! $record->setting('import_payments', false)) {
$retest = true; // Register the refund topic when payment imports are enabled.
}

$record->forceFill([
'name' => $data['name'],
'acting_user_id' => $user->id,
Expand Down Expand Up @@ -396,11 +401,16 @@ private function validateConnection(Request $request, ?Connection $existing): ar
'stock_source' => ['required', Rule::in(SyncPolicy::STOCK_SOURCES)],
'product_source' => ['required', Rule::in(SyncPolicy::PRODUCT_SOURCES)],
'import_orders' => ['required', 'boolean'],
'import_payments' => ['nullable', 'boolean'],
'import_test_orders' => ['nullable', 'boolean'],
'orders_since' => ['required_with:history_before', 'nullable', 'date'],
'history_before' => ['nullable', 'date', 'after_or_equal:orders_since', 'before_or_equal:today'],
]);

if (($data['import_payments'] ?? false) && ! Payments::supported()) {
throw ValidationException::withMessages(['import_payments' => 'Update Inventoros core to enable imported-payment records.']);
}

if ($existing === null && ! ShopDomain::valid($data['shop_domain'])) {
throw ValidationException::withMessages(['shop_domain' => __('shopify::messages.invalid_domain')]);
}
Expand Down
2 changes: 2 additions & 0 deletions src/Http/Controllers/PagesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Inventoros\Plugins\Shopify\Sync\Catalog;
use Inventoros\Plugins\Shopify\Sync\Locations;
use Inventoros\Plugins\Shopify\Sync\OrderImporter;
use Inventoros\Plugins\Shopify\Sync\Payments;

/**
* Props of the plugin's three pages. register_page() calls these only for
Expand Down Expand Up @@ -56,6 +57,7 @@ public static function overview(Request $request, User $user): array
'canManage' => Permissions::canManage($user),
'apiVersion' => ShopifyClient::API_VERSION,
'defaults' => SyncPolicy::DEFAULTS,
'supportsPaymentImport' => Payments::supported(),
'urls' => self::urls(),
];
}
Expand Down
20 changes: 20 additions & 0 deletions src/Shopify/HttpShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,26 @@ public function order(string $id): ?array
return is_array($data['order'] ?? null) ? Normalizer::order($this->complete($data['order'], 'lineItems', Queries::ORDER_LINES, 'order', 800)) : null;
}

public function transactions(string $orderId): array
{
$data = $this->read(Queries::ORDER_TRANSACTIONS, ['id' => Gid::make('Order', $orderId)], 500);
$order = $data['order'] ?? [];
$rows = $order['transactions'] ?? null;
if (! is_array($rows) || ($order['transactionsCount']['precision'] ?? '') !== 'EXACT'
|| ($order['transactionsCount']['count'] ?? -1) !== count($rows)) {
throw new PermanentError('Shopify did not return the complete transaction history (maximum 100 transactions per order). Review this order manually rather than importing partial payments.');
}

return array_map(fn ($row) => [
'id' => (string) Gid::id($row['id'] ?? null), 'kind' => strtolower((string) ($row['kind'] ?? '')),
'status' => strtolower((string) ($row['status'] ?? '')), 'gateway' => $row['gateway'] ?? '',
'amount' => (string) ($row['amountSet']['shopMoney']['amount'] ?? ''),
'currency' => $row['amountSet']['shopMoney']['currencyCode'] ?? '',
'processed_at' => $row['processedAt'] ?? $row['createdAt'] ?? null,
'parent_id' => Gid::id($row['parentTransaction']['id'] ?? null),
], $rows);
}

public function setInventoryQuantities(array $quantities, string $idempotencyKey): void
{
if ($quantities === []) {
Expand Down
12 changes: 12 additions & 0 deletions src/Shopify/Queries.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,18 @@ final class Queries
}
GQL;

public const ORDER_TRANSACTIONS = <<<'GQL'
query OrderTransactions($id: ID!) {
order(id: $id) {
transactionsCount { count precision }
transactions(first: 100) {
id kind status gateway processedAt createdAt parentTransaction { id }
amountSet { shopMoney { amount currencyCode } }
}
}
}
GQL;

public const SET_QUANTITIES = <<<'GQL'
mutation SetQuantities($input: InventorySetQuantitiesInput!, $idempotencyKey: String!) {
inventorySetQuantities(input: $input) @idempotent(key: $idempotencyKey) {
Expand Down
3 changes: 3 additions & 0 deletions src/Shopify/ShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ interface ShopifyClient
*/
public function shop(): array;

/** Successful and non-successful transactions, in shop currency; complete or refused. */
public function transactions(string $orderId): array;

/**
* @return Page<array{id: string, name: string, active: bool}>
*/
Expand Down
8 changes: 7 additions & 1 deletion src/Shopify/SyncPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ final class SyncPolicy
'stock_source' => 'inventoros',
'product_source' => 'shopify',
'import_orders' => true,
'import_payments' => false,
'import_test_orders' => false,
'orders_since' => null,
'history_before' => null,
Expand Down Expand Up @@ -66,7 +67,7 @@ public static function sanitize(array $input, array $current = []): array
$settings['product_source'] = $input['product_source'];
}

foreach (['import_orders', 'import_test_orders'] as $flag) {
foreach (['import_orders', 'import_test_orders', 'import_payments'] as $flag) {
if (array_key_exists($flag, $input)) {
$settings[$flag] = (bool) $input[$flag];
}
Expand Down Expand Up @@ -108,6 +109,11 @@ public function importsOrders(): bool
return (bool) $this->settings['import_orders'];
}

public function importsPayments(): bool
{
return (bool) $this->settings['import_payments'];
}

public function importsTestOrders(): bool
{
return (bool) $this->settings['import_test_orders'];
Expand Down
Loading
Loading