@porulle/adapter-shopify 0.9.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/LICENSE +21 -0
- package/README.md +3 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +260 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/package.json +37 -0
- package/src/index.ts +271 -0
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@porulle/adapter-shopify",
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"import": "./dist/index.js",
|
|
9
|
+
"types": "./src/index.ts"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"dependencies": {
|
|
13
|
+
"@porulle/core": "0.9.0"
|
|
14
|
+
},
|
|
15
|
+
"devDependencies": {
|
|
16
|
+
"@types/node": "^24.5.2",
|
|
17
|
+
"eslint": "^9.39.1",
|
|
18
|
+
"typescript": "5.9.2",
|
|
19
|
+
"vitest": "^3.2.4",
|
|
20
|
+
"@porulle/eslint-config": "0.1.0",
|
|
21
|
+
"@porulle/typescript-config": "0.1.0"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src",
|
|
28
|
+
"dist",
|
|
29
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "rm -rf dist tsconfig.build.tsbuildinfo && tsc -p tsconfig.build.json && cp -R dist/src/. dist/ && rm -rf dist/src",
|
|
33
|
+
"check-types": "tsc --noEmit",
|
|
34
|
+
"lint": "eslint . --max-warnings 1000",
|
|
35
|
+
"test": "vitest run"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { defineChannelConnector, Err, Ok } from "@porulle/core";
|
|
2
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import type {
|
|
4
|
+
ChannelCatalogPage,
|
|
5
|
+
ChannelConnector,
|
|
6
|
+
ChannelConnectorError,
|
|
7
|
+
ChannelInventoryLevel,
|
|
8
|
+
ChannelStore,
|
|
9
|
+
ChannelOrderSlice,
|
|
10
|
+
ChannelOrderStatus,
|
|
11
|
+
Result,
|
|
12
|
+
} from "@porulle/core";
|
|
13
|
+
|
|
14
|
+
export interface ShopifyConnectorOptions {
|
|
15
|
+
fetchImpl?: typeof fetch;
|
|
16
|
+
apiVersion?: string;
|
|
17
|
+
clientId?: string;
|
|
18
|
+
clientSecret?: string;
|
|
19
|
+
appUrl?: string;
|
|
20
|
+
scopes?: string[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const REQUIRED_SCOPES = [
|
|
24
|
+
"read_products",
|
|
25
|
+
"read_inventory",
|
|
26
|
+
"read_orders",
|
|
27
|
+
"write_orders",
|
|
28
|
+
"read_fulfillments",
|
|
29
|
+
] as const;
|
|
30
|
+
|
|
31
|
+
type ShopifyProduct = {
|
|
32
|
+
id: number | string;
|
|
33
|
+
title: string;
|
|
34
|
+
handle?: string;
|
|
35
|
+
body_html?: string;
|
|
36
|
+
variants?: Array<{ id: number | string; sku?: string | null; barcode?: string | null; price?: string | null }>;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function parseMoney(value: string | null | undefined): number {
|
|
40
|
+
if (!value) return 0;
|
|
41
|
+
const parsed = Number.parseFloat(value);
|
|
42
|
+
return Number.isFinite(parsed) ? Math.round(parsed * 100) : 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function apiBase(store: ChannelStore, version: string): string {
|
|
46
|
+
return `https://${store.storeDomain.replace(/^https?:\/\//, "").replace(/\/$/, "")}/admin/api/${version}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function request<T>(fetchImpl: typeof fetch, url: string, accessToken: string, init?: RequestInit): Promise<Result<{ data: T; response: Response }>> {
|
|
50
|
+
try {
|
|
51
|
+
const response = await fetchImpl(url, {
|
|
52
|
+
...init,
|
|
53
|
+
headers: { accept: "application/json", ...(init?.headers ?? {}), "x-shopify-access-token": accessToken },
|
|
54
|
+
});
|
|
55
|
+
if (!response.ok) return Err({ code: "SHOPIFY_API_FAILED", message: `Shopify API request failed (${response.status}) for ${url}.`, retriable: response.status >= 500 });
|
|
56
|
+
return Ok({ data: await response.json() as T, response });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
return Err({ code: "SHOPIFY_API_FAILED", message: error instanceof Error ? error.message : "Shopify API request failed.", retriable: true });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function shopifyStatus(order: { financial_status?: string | null; fulfillment_status?: string | null; cancelled_at?: string | null }): ChannelOrderStatus {
|
|
63
|
+
if (order.cancelled_at) return { status: "cancelled" };
|
|
64
|
+
if (order.fulfillment_status === "fulfilled") return { status: "fulfilled" };
|
|
65
|
+
if (order.financial_status === "paid" || order.financial_status === "partially_paid") return { status: "confirmed" };
|
|
66
|
+
if (order.financial_status === "refunded" || order.financial_status === "voided") return { status: "failed" };
|
|
67
|
+
return { status: "pending" };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function credentials(store: ChannelStore): string | undefined {
|
|
71
|
+
const accessToken = store.credentials.accessToken;
|
|
72
|
+
return typeof accessToken === "string" && accessToken.length > 0 ? accessToken : undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function validBase64Hmac(secret: string, body: string, signature: string | null): boolean {
|
|
76
|
+
if (!signature) return false;
|
|
77
|
+
const expected = createHmac("sha256", secret).update(body).digest();
|
|
78
|
+
const actual = Buffer.from(signature, "base64");
|
|
79
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function validShopDomain(value: string): boolean {
|
|
83
|
+
return /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.myshopify\.com$/i.test(value);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function oauthHmacMessage(searchParams: URLSearchParams): string {
|
|
87
|
+
return [...searchParams.entries()]
|
|
88
|
+
.filter(([key]) => key !== "hmac")
|
|
89
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
90
|
+
.map(([key, value]) => `${key}=${value}`)
|
|
91
|
+
.join("&");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function validOAuthHmac(searchParams: URLSearchParams, secret: string): boolean {
|
|
95
|
+
const provided = searchParams.get("hmac");
|
|
96
|
+
if (!provided || !/^[a-f0-9]+$/i.test(provided)) return false;
|
|
97
|
+
const expected = createHmac("sha256", secret).update(oauthHmacMessage(searchParams)).digest();
|
|
98
|
+
const actual = Buffer.from(provided, "hex");
|
|
99
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function oauthError(code: string, message: string): Result<never, ChannelConnectorError> {
|
|
103
|
+
return Err({ code, message, retriable: false });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function shopifyConnector(options: ShopifyConnectorOptions = {}): ChannelConnector {
|
|
107
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
108
|
+
const version = options.apiVersion ?? "2024-10";
|
|
109
|
+
return defineChannelConnector({
|
|
110
|
+
providerId: "shopify",
|
|
111
|
+
capabilities: { importCatalog: true, importInventory: true, pushOrder: true, receiveWebhooks: true },
|
|
112
|
+
buildAuthUrl(params) {
|
|
113
|
+
if (!options.clientId || !options.clientSecret || !options.appUrl) {
|
|
114
|
+
return oauthError("SHOPIFY_OAUTH_NOT_CONFIGURED", "Shopify OAuth requires clientId, clientSecret, and appUrl.");
|
|
115
|
+
}
|
|
116
|
+
const shopDomain = params.storeDomain.toLowerCase();
|
|
117
|
+
if (!validShopDomain(shopDomain)) return oauthError("SHOPIFY_INVALID_STORE_DOMAIN", "Shopify storeDomain must be a *.myshopify.com domain.");
|
|
118
|
+
const scopes = [...new Set([...REQUIRED_SCOPES, ...(options.scopes ?? []), ...params.scopes])];
|
|
119
|
+
const url = new URL(`https://${shopDomain}/admin/oauth/authorize`);
|
|
120
|
+
url.searchParams.set("client_id", options.clientId);
|
|
121
|
+
url.searchParams.set("scope", scopes.join(","));
|
|
122
|
+
url.searchParams.set("redirect_uri", params.redirectUri);
|
|
123
|
+
url.searchParams.set("state", params.state);
|
|
124
|
+
return Ok(url.toString());
|
|
125
|
+
},
|
|
126
|
+
async completeAuth(request, ctx) {
|
|
127
|
+
if (!options.clientId || !options.clientSecret || !options.appUrl) {
|
|
128
|
+
return oauthError("SHOPIFY_OAUTH_NOT_CONFIGURED", "Shopify OAuth requires clientId, clientSecret, and appUrl.");
|
|
129
|
+
}
|
|
130
|
+
const url = new URL(request.url);
|
|
131
|
+
const shopDomain = ctx.storeDomain.toLowerCase();
|
|
132
|
+
const callbackShop = url.searchParams.get("shop")?.toLowerCase();
|
|
133
|
+
if (!validShopDomain(shopDomain) || callbackShop !== shopDomain) {
|
|
134
|
+
return oauthError("SHOPIFY_INVALID_STORE_DOMAIN", "Shopify storeDomain must be a *.myshopify.com domain.");
|
|
135
|
+
}
|
|
136
|
+
if (!validOAuthHmac(url.searchParams, options.clientSecret)) {
|
|
137
|
+
return oauthError("SHOPIFY_INVALID_OAUTH_HMAC", "Shopify OAuth callback HMAC is invalid.");
|
|
138
|
+
}
|
|
139
|
+
const timestamp = Number(url.searchParams.get("timestamp"));
|
|
140
|
+
if (!Number.isInteger(timestamp) || Math.abs(Math.floor(Date.now() / 1000) - timestamp) > 300) {
|
|
141
|
+
return oauthError("SHOPIFY_STALE_OAUTH_CALLBACK", "Shopify OAuth callback timestamp is stale.");
|
|
142
|
+
}
|
|
143
|
+
const code = url.searchParams.get("code");
|
|
144
|
+
if (!code) return oauthError("SHOPIFY_OAUTH_CODE_REQUIRED", "Shopify OAuth callback code is required.");
|
|
145
|
+
try {
|
|
146
|
+
const response = await fetchImpl(`https://${shopDomain}/admin/oauth/access_token`, {
|
|
147
|
+
method: "POST",
|
|
148
|
+
headers: { accept: "application/json", "content-type": "application/json" },
|
|
149
|
+
body: JSON.stringify({ client_id: options.clientId, client_secret: options.clientSecret, code }),
|
|
150
|
+
});
|
|
151
|
+
if (!response.ok) return oauthError("SHOPIFY_TOKEN_EXCHANGE_FAILED", `Shopify token exchange failed (${response.status}).`);
|
|
152
|
+
const body = await response.json() as { access_token?: unknown };
|
|
153
|
+
if (typeof body.access_token !== "string" || !body.access_token) return oauthError("SHOPIFY_TOKEN_INVALID", "Shopify token exchange did not return an access token.");
|
|
154
|
+
return Ok({ credentials: { accessToken: body.access_token }, storeDomain: shopDomain });
|
|
155
|
+
} catch (error) {
|
|
156
|
+
return Err({ code: "SHOPIFY_TOKEN_EXCHANGE_FAILED", message: error instanceof Error ? error.message : "Shopify token exchange failed.", retriable: true });
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
async importCatalog(store, cursor): Promise<Result<ChannelCatalogPage>> {
|
|
160
|
+
const token = credentials(store);
|
|
161
|
+
if (!token) return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required." });
|
|
162
|
+
const url = cursor ?? `${apiBase(store, version)}/products.json?limit=250`;
|
|
163
|
+
const result = await request<{ products: ShopifyProduct[] }>(fetchImpl, url, token);
|
|
164
|
+
if (!result.ok) return result;
|
|
165
|
+
const link = result.value.response.headers.get("link") ?? "";
|
|
166
|
+
const next = link.match(/<([^>]+)>;\s*rel="next"/)?.[1] ?? null;
|
|
167
|
+
return Ok({
|
|
168
|
+
items: result.value.data.products.map((product) => ({
|
|
169
|
+
externalId: String(product.id),
|
|
170
|
+
slug: product.handle ?? String(product.id),
|
|
171
|
+
title: product.title,
|
|
172
|
+
...(product.body_html ? { description: product.body_html } : {}),
|
|
173
|
+
variants: (product.variants ?? []).map((variant) => ({
|
|
174
|
+
externalId: String(variant.id),
|
|
175
|
+
...(variant.sku ? { sku: variant.sku } : {}),
|
|
176
|
+
...(variant.barcode ? { barcode: variant.barcode } : {}),
|
|
177
|
+
metadata: { price: parseMoney(variant.price) },
|
|
178
|
+
})),
|
|
179
|
+
})),
|
|
180
|
+
nextCursor: next,
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
async fetchInventory(store, ids): Promise<Result<ChannelInventoryLevel[]>> {
|
|
184
|
+
const token = credentials(store);
|
|
185
|
+
if (!token) return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required." });
|
|
186
|
+
const params = new URLSearchParams({ limit: "250" });
|
|
187
|
+
if (ids?.length) params.set("inventory_item_ids", ids.join(","));
|
|
188
|
+
const result = await request<{ inventory_levels: Array<{ inventory_item_id: number | string; available: number | null }> }>(fetchImpl, `${apiBase(store, version)}/inventory_levels.json?${params}`, token);
|
|
189
|
+
if (!result.ok) return result;
|
|
190
|
+
return Ok(result.value.data.inventory_levels.map((level) => ({ externalId: String(level.inventory_item_id), available: level.available ?? 0 })));
|
|
191
|
+
},
|
|
192
|
+
async pushOrder(store, slice: ChannelOrderSlice) {
|
|
193
|
+
const token = credentials(store);
|
|
194
|
+
if (!token) return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required.", retriable: false });
|
|
195
|
+
const [firstName, ...lastParts] = slice.customer.name.trim().split(/\s+/);
|
|
196
|
+
const result = await request<{ order: { id: number | string; admin_graphql_api_id?: string } }>(fetchImpl, `${apiBase(store, version)}/orders.json`, token, {
|
|
197
|
+
method: "POST",
|
|
198
|
+
headers: { "content-type": "application/json", "idempotency-key": `porulle:${slice.orderId}` },
|
|
199
|
+
body: JSON.stringify({ order: {
|
|
200
|
+
financial_status: "paid",
|
|
201
|
+
line_items: slice.lines.map((line) => ({ variant_id: line.externalVariantId, quantity: line.quantity, price: line.unitPrice / 100 })),
|
|
202
|
+
customer: { email: slice.customer.email, first_name: firstName ?? "", last_name: lastParts.join(" ") },
|
|
203
|
+
shipping_address: slice.customer.shippingAddress,
|
|
204
|
+
transactions: [{ kind: "sale", status: "success", amount: slice.grandTotal / 100 }],
|
|
205
|
+
} }),
|
|
206
|
+
});
|
|
207
|
+
if (!result.ok) return result;
|
|
208
|
+
const id = String(result.value.data.order.id);
|
|
209
|
+
return Ok({ remoteOrderId: id, remoteUrl: `${apiBase(store, version)}/orders/${id}.json` });
|
|
210
|
+
},
|
|
211
|
+
async fetchOrderStatus(store, remoteId) {
|
|
212
|
+
const token = credentials(store);
|
|
213
|
+
if (!token) return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required.", retriable: false });
|
|
214
|
+
const result = await request<{ order: { financial_status?: string | null; fulfillment_status?: string | null; cancelled_at?: string | null } }>(fetchImpl, `${apiBase(store, version)}/orders/${encodeURIComponent(remoteId)}.json`, token);
|
|
215
|
+
return result.ok ? Ok(shopifyStatus(result.value.data.order)) : result;
|
|
216
|
+
},
|
|
217
|
+
async verifyWebhook(_store, request) {
|
|
218
|
+
const body = await request.text();
|
|
219
|
+
// Shopify signs every webhook for an app with the app CLIENT SECRET — there is no
|
|
220
|
+
// per-store/per-subscription secret (unlike WooCommerce). Verify against clientSecret.
|
|
221
|
+
if (!options.clientSecret) {
|
|
222
|
+
return Err({ code: "SHOPIFY_CLIENT_SECRET_MISSING", message: "Shopify clientSecret is required to verify webhooks." });
|
|
223
|
+
}
|
|
224
|
+
if (!validBase64Hmac(options.clientSecret, body, request.headers.get("x-shopify-hmac-sha256"))) {
|
|
225
|
+
return Err({ code: "INVALID_WEBHOOK_SIGNATURE", message: "Invalid Shopify webhook signature." });
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
const data = JSON.parse(body) as unknown;
|
|
229
|
+
const id = request.headers.get("x-shopify-event-id");
|
|
230
|
+
const type = request.headers.get("x-shopify-topic");
|
|
231
|
+
if (!id || !type) return Err({ code: "INVALID_WEBHOOK", message: "Shopify webhook headers are incomplete." });
|
|
232
|
+
return Ok({ id, type, data });
|
|
233
|
+
} catch {
|
|
234
|
+
return Err({ code: "INVALID_WEBHOOK", message: "Shopify webhook body must be valid JSON." });
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
async verifyAppWebhook(request) {
|
|
238
|
+
if (!options.clientSecret) {
|
|
239
|
+
return Err({ code: "SHOPIFY_CLIENT_SECRET_MISSING", message: "Shopify clientSecret is required to verify app webhooks.", retriable: false });
|
|
240
|
+
}
|
|
241
|
+
const body = await request.text();
|
|
242
|
+
if (!validBase64Hmac(options.clientSecret, body, request.headers.get("x-shopify-hmac-sha256"))) {
|
|
243
|
+
return Err({ code: "INVALID_APP_WEBHOOK_SIGNATURE", message: "Invalid Shopify app webhook signature.", retriable: false });
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
const data = JSON.parse(body) as unknown;
|
|
247
|
+
const payload = data as Record<string, unknown>;
|
|
248
|
+
const topic = request.headers.get("x-shopify-topic");
|
|
249
|
+
const shopDomain = typeof payload.shop_domain === "string" ? payload.shop_domain : "";
|
|
250
|
+
if (!topic) return Err({ code: "INVALID_APP_WEBHOOK", message: "Shopify app webhook topic header is missing.", retriable: false });
|
|
251
|
+
return Ok({ topic, shopDomain, data });
|
|
252
|
+
} catch {
|
|
253
|
+
return Err({ code: "INVALID_APP_WEBHOOK", message: "Shopify app webhook body must be valid JSON.", retriable: false });
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
async registerWebhooks(store: ChannelStore, topics: string[], callbackUrl: string) {
|
|
257
|
+
const token = credentials(store);
|
|
258
|
+
if (!token) return Err({ code: "SHOPIFY_CREDENTIALS_REQUIRED", message: "Shopify accessToken is required." });
|
|
259
|
+
for (const topic of topics) {
|
|
260
|
+
const result = await request<{ webhook: unknown }>(fetchImpl, `${apiBase(store, version)}/webhooks.json`, token, {
|
|
261
|
+
method: "POST",
|
|
262
|
+
headers: { "content-type": "application/json" },
|
|
263
|
+
body: JSON.stringify({ webhook: { topic, address: callbackUrl, format: "json" } }),
|
|
264
|
+
});
|
|
265
|
+
if (!result.ok) return result;
|
|
266
|
+
}
|
|
267
|
+
return Ok({ registered: topics.length });
|
|
268
|
+
},
|
|
269
|
+
async refundExecute() { return Err({ code: "NOT_IMPLEMENTED", message: "Shopify refund execution is not implemented in this slice." }); },
|
|
270
|
+
});
|
|
271
|
+
}
|