@porulle/adapter-shopify 0.87.0 → 0.89.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -37
- package/dist/graphql.js +3 -1
- package/dist/index.d.ts +32 -2
- package/dist/index.js +92 -5
- package/dist/oauth.d.ts +81 -8
- package/dist/oauth.js +167 -14
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/webhooks.d.ts +9 -0
- package/dist/webhooks.js +203 -0
- package/package.json +2 -2
- package/src/graphql.ts +3 -1
- package/src/index.ts +101 -5
- package/src/oauth.ts +191 -14
- package/src/webhooks.ts +188 -0
package/dist/webhooks.d.ts
CHANGED
|
@@ -5,5 +5,14 @@ import type { ShopifyGraphqlTarget } from "./graphql.js";
|
|
|
5
5
|
* its stock summed over locations are read fresh, so the level applied is the store's, not the payload's.
|
|
6
6
|
*/
|
|
7
7
|
export declare const INVENTORY_ITEM_VARIANT_QUERY = "query PorulleInventoryItemVariant($id: ID!) {\n inventoryItem(id: $id) { variant { legacyResourceId inventoryQuantity } }\n}";
|
|
8
|
+
/** The topics whose payload names the shop that sent it, signed: `shop_domain`. */
|
|
9
|
+
export declare function isComplianceTopic(topic: string): boolean;
|
|
10
|
+
export declare function decodeReadsTheStore(topic: string): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Keeps only the fields `decodeShopifyWebhook` and compliance handlers read before a delivery is
|
|
13
|
+
* persisted in `commerce_jobs.input` — stripping shopper names, shipping/billing addresses, phone
|
|
14
|
+
* numbers and any other extra webhook fields while preserving malformed-shape failures.
|
|
15
|
+
*/
|
|
16
|
+
export declare function minimizeShopifyWebhookPayload(topic: string, data: unknown): unknown;
|
|
8
17
|
/** What one Shopify delivery means. `shop` is the store's Admin API, for the reads a nudge needs. */
|
|
9
18
|
export declare function decodeShopifyWebhook(shop: ShopifyGraphqlTarget | undefined, event: ChannelWebhookEvent): Promise<Result<ChannelEvent[], ChannelConnectorError>>;
|
package/dist/webhooks.js
CHANGED
|
@@ -67,6 +67,209 @@ const COMPLIANCE = {
|
|
|
67
67
|
"customers/redact": "customer_redact",
|
|
68
68
|
"shop/redact": "shop_redact",
|
|
69
69
|
};
|
|
70
|
+
/** The topics whose payload names the shop that sent it, signed: `shop_domain`. */
|
|
71
|
+
export function isComplianceTopic(topic) {
|
|
72
|
+
return topic in COMPLIANCE;
|
|
73
|
+
}
|
|
74
|
+
/** The topics `decodeShopifyWebhook` answers with a read of the shop's Admin API; every other decodes from its body. */
|
|
75
|
+
const READS_THE_STORE = new Set(["inventory_levels/update"]);
|
|
76
|
+
export function decodeReadsTheStore(topic) {
|
|
77
|
+
return READS_THE_STORE.has(topic);
|
|
78
|
+
}
|
|
79
|
+
function isPlainRecord(value) {
|
|
80
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
81
|
+
}
|
|
82
|
+
/** Keeps an identifier/scalar field if present; replaces non-scalar malformed values with `false` so validation still rejects them without retaining PII. */
|
|
83
|
+
function keepId(value) {
|
|
84
|
+
if (value === undefined || value === null)
|
|
85
|
+
return value;
|
|
86
|
+
return typeof value === "string" || typeof value === "number" ? value : false;
|
|
87
|
+
}
|
|
88
|
+
function keepIdList(value) {
|
|
89
|
+
if (value === undefined)
|
|
90
|
+
return undefined;
|
|
91
|
+
if (!Array.isArray(value))
|
|
92
|
+
return false;
|
|
93
|
+
return value.map((entry) => (typeof entry === "string" || typeof entry === "number" ? entry : false));
|
|
94
|
+
}
|
|
95
|
+
function keepString(value) {
|
|
96
|
+
if (value === undefined || value === null)
|
|
97
|
+
return value;
|
|
98
|
+
return typeof value === "string" ? value : false;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Keeps only the fields `decodeShopifyWebhook` and compliance handlers read before a delivery is
|
|
102
|
+
* persisted in `commerce_jobs.input` — stripping shopper names, shipping/billing addresses, phone
|
|
103
|
+
* numbers and any other extra webhook fields while preserving malformed-shape failures.
|
|
104
|
+
*/
|
|
105
|
+
export function minimizeShopifyWebhookPayload(topic, data) {
|
|
106
|
+
if (topic === "app/uninstalled")
|
|
107
|
+
return {};
|
|
108
|
+
if (!isPlainRecord(data))
|
|
109
|
+
return null;
|
|
110
|
+
if (topic === "shop/redact") {
|
|
111
|
+
const out = {};
|
|
112
|
+
if ("shop_id" in data)
|
|
113
|
+
out.shop_id = keepId(data.shop_id);
|
|
114
|
+
if ("shop_domain" in data)
|
|
115
|
+
out.shop_domain = keepString(data.shop_domain);
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
if (topic === "customers/redact" || topic === "customers/data_request") {
|
|
119
|
+
const out = {};
|
|
120
|
+
if ("shop_id" in data)
|
|
121
|
+
out.shop_id = keepId(data.shop_id);
|
|
122
|
+
if ("shop_domain" in data)
|
|
123
|
+
out.shop_domain = keepString(data.shop_domain);
|
|
124
|
+
if ("email" in data)
|
|
125
|
+
out.email = keepString(data.email);
|
|
126
|
+
if ("customer_id" in data)
|
|
127
|
+
out.customer_id = keepId(data.customer_id);
|
|
128
|
+
if ("customer" in data) {
|
|
129
|
+
if (data.customer === null)
|
|
130
|
+
out.customer = null;
|
|
131
|
+
else if (isPlainRecord(data.customer)) {
|
|
132
|
+
const customer = {};
|
|
133
|
+
if ("id" in data.customer)
|
|
134
|
+
customer.id = keepId(data.customer.id);
|
|
135
|
+
if ("email" in data.customer)
|
|
136
|
+
customer.email = keepString(data.customer.email);
|
|
137
|
+
out.customer = customer;
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
out.customer = false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if ("orders_to_redact" in data)
|
|
144
|
+
out.orders_to_redact = keepIdList(data.orders_to_redact);
|
|
145
|
+
if ("orders_requested" in data)
|
|
146
|
+
out.orders_requested = keepIdList(data.orders_requested);
|
|
147
|
+
if ("data_request" in data) {
|
|
148
|
+
if (data.data_request === null)
|
|
149
|
+
out.data_request = null;
|
|
150
|
+
else if (isPlainRecord(data.data_request)) {
|
|
151
|
+
out.data_request = "id" in data.data_request ? { id: keepId(data.data_request.id) } : {};
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
out.data_request = false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
if (topic === "orders/cancelled") {
|
|
160
|
+
return "id" in data ? { id: keepId(data.id) } : {};
|
|
161
|
+
}
|
|
162
|
+
if (topic === "orders/fulfilled" || topic === "orders/partially_fulfilled") {
|
|
163
|
+
const out = {};
|
|
164
|
+
if ("id" in data)
|
|
165
|
+
out.id = keepId(data.id);
|
|
166
|
+
if ("fulfillments" in data) {
|
|
167
|
+
if (!Array.isArray(data.fulfillments)) {
|
|
168
|
+
out.fulfillments = false;
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
out.fulfillments = data.fulfillments.map((parcel) => {
|
|
172
|
+
if (!isPlainRecord(parcel))
|
|
173
|
+
return false;
|
|
174
|
+
const minimal = {};
|
|
175
|
+
if ("id" in parcel)
|
|
176
|
+
minimal.id = keepId(parcel.id);
|
|
177
|
+
if ("status" in parcel)
|
|
178
|
+
minimal.status = keepString(parcel.status);
|
|
179
|
+
if ("tracking_company" in parcel)
|
|
180
|
+
minimal.tracking_company = keepString(parcel.tracking_company);
|
|
181
|
+
if ("tracking_number" in parcel)
|
|
182
|
+
minimal.tracking_number = keepString(parcel.tracking_number);
|
|
183
|
+
if ("tracking_url" in parcel)
|
|
184
|
+
minimal.tracking_url = keepString(parcel.tracking_url);
|
|
185
|
+
if ("line_items" in parcel) {
|
|
186
|
+
minimal.line_items = Array.isArray(parcel.line_items)
|
|
187
|
+
? parcel.line_items.map((line) => (isPlainRecord(line)
|
|
188
|
+
? {
|
|
189
|
+
...("variant_id" in line ? { variant_id: keepId(line.variant_id) } : {}),
|
|
190
|
+
...("quantity" in line ? { quantity: typeof line.quantity === "number" ? line.quantity : false } : {}),
|
|
191
|
+
}
|
|
192
|
+
: false))
|
|
193
|
+
: false;
|
|
194
|
+
}
|
|
195
|
+
return minimal;
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
if (topic === "refunds/create") {
|
|
202
|
+
const out = {};
|
|
203
|
+
if ("id" in data)
|
|
204
|
+
out.id = keepId(data.id);
|
|
205
|
+
if ("order_id" in data)
|
|
206
|
+
out.order_id = keepId(data.order_id);
|
|
207
|
+
if ("refund_line_items" in data) {
|
|
208
|
+
out.refund_line_items = Array.isArray(data.refund_line_items)
|
|
209
|
+
? data.refund_line_items.map((entry) => {
|
|
210
|
+
if (!isPlainRecord(entry))
|
|
211
|
+
return false;
|
|
212
|
+
const minimal = {};
|
|
213
|
+
if ("quantity" in entry)
|
|
214
|
+
minimal.quantity = typeof entry.quantity === "number" ? entry.quantity : false;
|
|
215
|
+
if ("line_item" in entry) {
|
|
216
|
+
minimal.line_item = isPlainRecord(entry.line_item)
|
|
217
|
+
? {
|
|
218
|
+
...("variant_id" in entry.line_item ? { variant_id: keepId(entry.line_item.variant_id) } : {}),
|
|
219
|
+
...("product_id" in entry.line_item ? { product_id: keepId(entry.line_item.product_id) } : {}),
|
|
220
|
+
}
|
|
221
|
+
: false;
|
|
222
|
+
}
|
|
223
|
+
return minimal;
|
|
224
|
+
})
|
|
225
|
+
: false;
|
|
226
|
+
}
|
|
227
|
+
if ("transactions" in data) {
|
|
228
|
+
out.transactions = Array.isArray(data.transactions)
|
|
229
|
+
? data.transactions.map((tx) => (isPlainRecord(tx)
|
|
230
|
+
? {
|
|
231
|
+
...("kind" in tx ? { kind: keepString(tx.kind) } : {}),
|
|
232
|
+
...("status" in tx ? { status: keepString(tx.status) } : {}),
|
|
233
|
+
...("amount" in tx ? { amount: keepId(tx.amount) } : {}),
|
|
234
|
+
...("currency" in tx ? { currency: keepString(tx.currency) } : {}),
|
|
235
|
+
}
|
|
236
|
+
: false))
|
|
237
|
+
: false;
|
|
238
|
+
}
|
|
239
|
+
if ("refund_shipping_lines" in data) {
|
|
240
|
+
out.refund_shipping_lines = Array.isArray(data.refund_shipping_lines)
|
|
241
|
+
? data.refund_shipping_lines.map((line) => {
|
|
242
|
+
if (!isPlainRecord(line))
|
|
243
|
+
return false;
|
|
244
|
+
const set = isPlainRecord(line.subtotal_amount_set) ? line.subtotal_amount_set : null;
|
|
245
|
+
const shopMoney = set && isPlainRecord(set.shop_money) ? set.shop_money : null;
|
|
246
|
+
return shopMoney
|
|
247
|
+
? {
|
|
248
|
+
subtotal_amount_set: {
|
|
249
|
+
shop_money: {
|
|
250
|
+
...("amount" in shopMoney ? { amount: keepId(shopMoney.amount) } : {}),
|
|
251
|
+
...("currency_code" in shopMoney ? { currency_code: keepString(shopMoney.currency_code) } : {}),
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
: false;
|
|
256
|
+
})
|
|
257
|
+
: false;
|
|
258
|
+
}
|
|
259
|
+
return out;
|
|
260
|
+
}
|
|
261
|
+
if (topic === "inventory_levels/update") {
|
|
262
|
+
return "inventory_item_id" in data ? { inventory_item_id: keepId(data.inventory_item_id) } : {};
|
|
263
|
+
}
|
|
264
|
+
if (topic === "products/create"
|
|
265
|
+
|| topic === "products/update"
|
|
266
|
+
|| topic === "products/delete"
|
|
267
|
+
|| topic in RETURN_STATUS
|
|
268
|
+
|| topic.startsWith("orders/")) {
|
|
269
|
+
return "id" in data ? { id: keepId(data.id) } : {};
|
|
270
|
+
}
|
|
271
|
+
return {};
|
|
272
|
+
}
|
|
70
273
|
function malformed(topic, error) {
|
|
71
274
|
return Err({ code: "SHOPIFY_WEBHOOK_MALFORMED", message: `A Shopify ${topic} delivery did not parse: ${error.message}`, retriable: false });
|
|
72
275
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@porulle/adapter-shopify",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.89.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"zod": "^4.6.7",
|
|
19
|
-
"@porulle/core": "0.
|
|
19
|
+
"@porulle/core": "0.89.0"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
22
|
"@types/node": "^24.5.2",
|
package/src/graphql.ts
CHANGED
|
@@ -116,7 +116,9 @@ export async function shopifyGraphql<T>(
|
|
|
116
116
|
if (errors.length > 0) {
|
|
117
117
|
const message = errors.map((error) => error.message ?? "unknown error").join("; ");
|
|
118
118
|
const denied = errors.some((error) => error.extensions?.code === "ACCESS_DENIED");
|
|
119
|
-
|
|
119
|
+
const customerDataBlocked = denied && (/not approved to access the Order object/i.test(message) || /protected[- ]customer[- ]data/i.test(message));
|
|
120
|
+
const code = customerDataBlocked ? "SHOPIFY_CUSTOMER_DATA_NOT_ALLOWED" : denied ? "SHOPIFY_ACCESS_DENIED" : "SHOPIFY_GRAPHQL_ERROR";
|
|
121
|
+
return Err({ code, message: `Shopify GraphQL error: ${message}`, retriable: false });
|
|
120
122
|
}
|
|
121
123
|
const data = schema.safeParse(envelope?.data);
|
|
122
124
|
if (!data.success) {
|
package/src/index.ts
CHANGED
|
@@ -13,7 +13,7 @@ import type {
|
|
|
13
13
|
} from "@porulle/core";
|
|
14
14
|
import { z } from "zod";
|
|
15
15
|
import { readCatalogItems, readCatalogPage } from "./catalog.js";
|
|
16
|
-
import { decodeShopifyWebhook } from "./webhooks.js";
|
|
16
|
+
import { decodeReadsTheStore, decodeShopifyWebhook, isComplianceTopic, minimizeShopifyWebhookPayload } from "./webhooks.js";
|
|
17
17
|
import { shopifyGid, shopifyGraphql } from "./graphql.js";
|
|
18
18
|
import type { ShopifyGraphqlTarget } from "./graphql.js";
|
|
19
19
|
import {
|
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
export { SHOPIFY_API_VERSION } from "./graphql.js";
|
|
30
30
|
export { CATALOG_ITEMS_QUERY, CATALOG_PAGE_QUERY, VARIANTS_PAGE_QUERY } from "./catalog.js";
|
|
31
31
|
export { INVENTORY_ITEM_VARIANT_QUERY } from "./webhooks.js";
|
|
32
|
-
export { REQUIRED_SCOPES, normalizeShopDomain, parseShopifyCredentials } from "./oauth.js";
|
|
32
|
+
export { REQUIRED_SCOPES, exchangeIdToken, mintClientCredentials, missingScopes, normalizeShopDomain, parseShopifyCredentials, validShopDomain, verifyShopifyIdToken } from "./oauth.js";
|
|
33
33
|
export type { ShopifyCredentials } from "./oauth.js";
|
|
34
34
|
|
|
35
35
|
export interface ShopifyConnectorOptions {
|
|
@@ -43,6 +43,12 @@ export interface ShopifyConnectorOptions {
|
|
|
43
43
|
* code exercised by a test is the code that runs. There is no mock flag inside this adapter.
|
|
44
44
|
*/
|
|
45
45
|
shopOrigin?: (shopDomain: string) => string;
|
|
46
|
+
/**
|
|
47
|
+
* Payment gateway name written on the `SALE` transaction in `orderCreate` (shown in Shopify's
|
|
48
|
+
* order timeline as "payment was processed on <name>" and on refunds). Defaults to `"porulle"`.
|
|
49
|
+
* Does not change `sourceName` or `sourceIdentifier`, which the duplicate guard looks orders up by.
|
|
50
|
+
*/
|
|
51
|
+
paymentGateway?: string;
|
|
46
52
|
}
|
|
47
53
|
|
|
48
54
|
export const INVENTORY_QUERY = `query PorulleInventoryPage($after: String) {
|
|
@@ -98,6 +104,78 @@ export const ORDER_BY_SOURCE_QUERY = `query PorulleOrderBySource($query: String!
|
|
|
98
104
|
orders(first: 1, query: $query) { nodes { legacyResourceId } }
|
|
99
105
|
}`;
|
|
100
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Every topic this connector acts on (see `decodeShopifyWebhook`), in Shopify's header spelling, less
|
|
109
|
+
* the compliance topics: those are app configuration only, and Shopify's `WebhookSubscriptionTopic`
|
|
110
|
+
* has no value for them. An app whose configuration declares its subscriptions (`shopify.app.toml`)
|
|
111
|
+
* lists exactly these; an app that cannot carry ours is subscribed with {@link subscribeShopifyWebhooks}.
|
|
112
|
+
*/
|
|
113
|
+
export const SHOPIFY_WEBHOOK_TOPICS = [
|
|
114
|
+
"products/create",
|
|
115
|
+
"products/update",
|
|
116
|
+
"products/delete",
|
|
117
|
+
"inventory_levels/update",
|
|
118
|
+
"orders/fulfilled",
|
|
119
|
+
"orders/partially_fulfilled",
|
|
120
|
+
"orders/cancelled",
|
|
121
|
+
"refunds/create",
|
|
122
|
+
"returns/approve",
|
|
123
|
+
"returns/decline",
|
|
124
|
+
"returns/close",
|
|
125
|
+
"returns/cancel",
|
|
126
|
+
"app/uninstalled",
|
|
127
|
+
] as const;
|
|
128
|
+
|
|
129
|
+
export const WEBHOOK_SUBSCRIPTIONS_QUERY = `query PorulleWebhookSubscriptions($uri: String!) {
|
|
130
|
+
webhookSubscriptions(first: 100, uri: $uri) { nodes { topic } }
|
|
131
|
+
}`;
|
|
132
|
+
|
|
133
|
+
export const WEBHOOK_SUBSCRIPTION_CREATE_MUTATION = `mutation PorulleWebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) {
|
|
134
|
+
webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) { webhookSubscription { id } userErrors { field message } }
|
|
135
|
+
}`;
|
|
136
|
+
|
|
137
|
+
const webhookSubscriptionsSchema = z.object({ webhookSubscriptions: z.object({ nodes: z.array(z.object({ topic: z.string() })) }) });
|
|
138
|
+
const webhookSubscriptionCreateSchema = z.object({
|
|
139
|
+
webhookSubscriptionCreate: z.object({
|
|
140
|
+
webhookSubscription: z.object({ id: z.string() }).nullable(),
|
|
141
|
+
userErrors: z.array(z.object({ field: z.array(z.string()).nullable(), message: z.string() })),
|
|
142
|
+
}),
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
/** `inventory_levels/update` → `INVENTORY_LEVELS_UPDATE`: the header spelling and the enum name of one topic. */
|
|
146
|
+
function webhookTopicEnum(topic: string): string {
|
|
147
|
+
return topic.replaceAll("/", "_").toUpperCase();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Subscribes the app that holds `accessToken` to every {@link SHOPIFY_WEBHOOK_TOPICS} topic on this
|
|
152
|
+
* store, delivered to `uri`, creating only the subscriptions missing — so connecting again does not
|
|
153
|
+
* double the deliveries. For an app whose configuration does not carry our subscriptions: a merchant's
|
|
154
|
+
* own Dev Dashboard app, connected with the client credentials grant. Deliveries are signed with that
|
|
155
|
+
* app's client secret.
|
|
156
|
+
*/
|
|
157
|
+
export async function subscribeShopifyWebhooks(params: { origin: string; accessToken: string; uri: string; fetchImpl?: typeof fetch }): Promise<Result<{ created: number }, ChannelConnectorError>> {
|
|
158
|
+
const target: ShopifyGraphqlTarget = { fetchImpl: params.fetchImpl ?? fetch, origin: params.origin, accessToken: params.accessToken };
|
|
159
|
+
const existing = await shopifyGraphql(target, WEBHOOK_SUBSCRIPTIONS_QUERY, { uri: params.uri }, webhookSubscriptionsSchema);
|
|
160
|
+
if (!existing.ok) return existing;
|
|
161
|
+
const held = new Set(existing.value.webhookSubscriptions.nodes.map((node) => node.topic));
|
|
162
|
+
let created = 0;
|
|
163
|
+
for (const topic of SHOPIFY_WEBHOOK_TOPICS.map(webhookTopicEnum).filter((name) => !held.has(name))) {
|
|
164
|
+
const answer = await shopifyGraphql(target, WEBHOOK_SUBSCRIPTION_CREATE_MUTATION, { topic, webhookSubscription: { uri: params.uri } }, webhookSubscriptionCreateSchema);
|
|
165
|
+
if (!answer.ok) return answer;
|
|
166
|
+
const { webhookSubscription, userErrors } = answer.value.webhookSubscriptionCreate;
|
|
167
|
+
if (userErrors.length > 0 || !webhookSubscription) {
|
|
168
|
+
const detail = userErrors.map((error) => error.message).join("; ") || "no subscription returned";
|
|
169
|
+
const code = userErrors.some((error) => /protected[- ]customer[- ]data/i.test(error.message))
|
|
170
|
+
? "SHOPIFY_CUSTOMER_DATA_NOT_ALLOWED"
|
|
171
|
+
: "SHOPIFY_WEBHOOK_SUBSCRIPTION_REFUSED";
|
|
172
|
+
return Err({ code, message: `Shopify refused the ${topic} subscription: ${detail}.`, retriable: false });
|
|
173
|
+
}
|
|
174
|
+
created += 1;
|
|
175
|
+
}
|
|
176
|
+
return Ok({ created });
|
|
177
|
+
}
|
|
178
|
+
|
|
101
179
|
export const ORDER_STATUS_QUERY = `query PorulleOrderStatus($id: ID!) {
|
|
102
180
|
order(id: $id) { cancelledAt displayFinancialStatus displayFulfillmentStatus }
|
|
103
181
|
}`;
|
|
@@ -183,6 +261,7 @@ const credentialsRequired: ChannelConnectorError = { code: "SHOPIFY_CREDENTIALS_
|
|
|
183
261
|
|
|
184
262
|
export function shopifyConnector(options: ShopifyConnectorOptions): ChannelConnector {
|
|
185
263
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
264
|
+
const paymentGateway = options.paymentGateway?.trim() || SOURCE_NAME;
|
|
186
265
|
const origin = (shopDomain: string): string => options.shopOrigin?.(shopDomain) ?? `https://${shopDomain}`;
|
|
187
266
|
const target = (store: ChannelStore): ShopifyGraphqlTarget | undefined => {
|
|
188
267
|
const credentials = parseShopifyCredentials(store.credentials);
|
|
@@ -283,7 +362,6 @@ export function shopifyConnector(options: ShopifyConnectorOptions): ChannelConne
|
|
|
283
362
|
if (!existing.ok) return existing;
|
|
284
363
|
const already = existing.value.orders.nodes[0];
|
|
285
364
|
if (already) return Ok({ remoteOrderId: already.legacyResourceId });
|
|
286
|
-
const [firstName, ...rest] = slice.customer.name.trim().split(/\s+/);
|
|
287
365
|
const address = slice.customer.shippingAddress;
|
|
288
366
|
// Shopify takes a province as its CODE. A region the shopper typed as a name is kept for the
|
|
289
367
|
// courier on the second address line rather than sent where Shopify would reject it.
|
|
@@ -301,6 +379,11 @@ export function shopifyConnector(options: ShopifyConnectorOptions): ChannelConne
|
|
|
301
379
|
countryCode: address.countryCode,
|
|
302
380
|
...(address.phone ? { phone: address.phone } : {}),
|
|
303
381
|
};
|
|
382
|
+
// No `customer.toUpsert`: measured on live Shopify (2026-11-24), `orderCreate` with
|
|
383
|
+
// `customer.toUpsert` for an email that already exists as a customer fails with ACCESS_DENIED
|
|
384
|
+
// ("Required access: `write_customers` access scope to update an existing customer with
|
|
385
|
+
// `customer.toUpsert`"). Passing `email` and `shippingAddress` alone creates orders for new,
|
|
386
|
+
// existing and repeat emails, and the brand's admin shows name, email, phone and address.
|
|
304
387
|
const created = await shopifyGraphql(shop, ORDER_CREATE_MUTATION, {
|
|
305
388
|
order: {
|
|
306
389
|
sourceName: SOURCE_NAME,
|
|
@@ -308,7 +391,6 @@ export function shopifyConnector(options: ShopifyConnectorOptions): ChannelConne
|
|
|
308
391
|
currency: slice.currency,
|
|
309
392
|
email: slice.customer.email,
|
|
310
393
|
financialStatus: "PAID",
|
|
311
|
-
customer: { toUpsert: { email: slice.customer.email, firstName: firstName ?? "", lastName: rest.join(" ") } },
|
|
312
394
|
shippingAddress,
|
|
313
395
|
lineItems: slice.lines.map((line) => ({
|
|
314
396
|
variantId: shopifyGid("ProductVariant", line.externalVariantId),
|
|
@@ -322,7 +404,7 @@ export function shopifyConnector(options: ShopifyConnectorOptions): ChannelConne
|
|
|
322
404
|
...(slice.shipping ? { shippingLines: [{ title: slice.shipping.title, priceSet: money(slice.shipping.amount, slice.currency) }] } : {}),
|
|
323
405
|
// The shopper's discount as a fixed amount off the items, so the store's total is what was paid.
|
|
324
406
|
...(slice.discount ? { discountCode: { itemFixedDiscountCode: { code: slice.discount.code, amountSet: money(slice.discount.amount, slice.currency) } } } : {}),
|
|
325
|
-
transactions: [{ kind: "SALE", status: "SUCCESS", gateway:
|
|
407
|
+
transactions: [{ kind: "SALE", status: "SUCCESS", gateway: paymentGateway, amountSet: money(slice.grandTotal, slice.currency) }],
|
|
326
408
|
},
|
|
327
409
|
options: { inventoryBehaviour: "DECREMENT_OBEYING_POLICY", sendReceipt: false, sendFulfillmentReceipt: false },
|
|
328
410
|
}, orderCreateSchema);
|
|
@@ -417,11 +499,25 @@ export function shopifyConnector(options: ShopifyConnectorOptions): ChannelConne
|
|
|
417
499
|
} catch {
|
|
418
500
|
return Err({ code: "INVALID_APP_WEBHOOK", message: "Shopify webhook body must be valid JSON.", retriable: false });
|
|
419
501
|
}
|
|
502
|
+
// The HMAC proves which app sent this, not which shop: the shop is a header. The compliance topics
|
|
503
|
+
// also name their shop inside the signed body, and a sender holding the app's secret could pair
|
|
504
|
+
// any body with any header, so the two must agree before anything is erased on either's say.
|
|
505
|
+
if (isComplianceTopic(topic)) {
|
|
506
|
+
const named = typeof data === "object" && data !== null && "shop_domain" in data && typeof data.shop_domain === "string" ? data.shop_domain.toLowerCase() : undefined;
|
|
507
|
+
if (named !== shopDomain) return Err({ code: "INVALID_APP_WEBHOOK", message: "The shop in the webhook body does not match the shop in its headers.", retriable: false });
|
|
508
|
+
}
|
|
509
|
+
// An uninstall names its shop in the body too (`myshopify_domain`), where it carries it. The same pairing
|
|
510
|
+
// argument holds: it takes a store's grant away, so a body for one shop must not ride a header for another.
|
|
511
|
+
if (topic === "app/uninstalled" && typeof data === "object" && data !== null && "myshopify_domain" in data && typeof data.myshopify_domain === "string" && data.myshopify_domain.toLowerCase() !== shopDomain) {
|
|
512
|
+
return Err({ code: "INVALID_APP_WEBHOOK", message: "The shop in the webhook body does not match the shop in its headers.", retriable: false });
|
|
513
|
+
}
|
|
420
514
|
return Ok({ id, topic, shopDomain, data });
|
|
421
515
|
},
|
|
422
516
|
async decodeWebhook(store, event) {
|
|
423
517
|
return decodeShopifyWebhook(target(store), event);
|
|
424
518
|
},
|
|
519
|
+
decodeWebhookNeedsCredentials: (event) => decodeReadsTheStore(event.type),
|
|
520
|
+
minimizeWebhookPayload: minimizeShopifyWebhookPayload,
|
|
425
521
|
async refundExecute() {
|
|
426
522
|
return Err({ code: "NOT_IMPLEMENTED", message: "Refunds are issued by the platform, not executed in the Shopify store." });
|
|
427
523
|
},
|