@porulle/adapter-woocommerce 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 +5 -0
- package/dist/index.js +209 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/package.json +37 -0
- package/src/index.ts +203 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 unified-commerce-engine contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { defineChannelConnector, Err, Ok } from "@porulle/core";
|
|
2
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
3
|
+
function buildWooUrl(base, path, key, secret, page, cursor) {
|
|
4
|
+
const url = new URL(path, base.replace(/\/$/, "/"));
|
|
5
|
+
url.searchParams.set("consumer_key", key);
|
|
6
|
+
url.searchParams.set("consumer_secret", secret);
|
|
7
|
+
url.searchParams.set("per_page", "100");
|
|
8
|
+
url.searchParams.set("page", String(page));
|
|
9
|
+
if (cursor)
|
|
10
|
+
url.searchParams.set("modified_after", cursor);
|
|
11
|
+
return url.toString();
|
|
12
|
+
}
|
|
13
|
+
function parseMoney(value) {
|
|
14
|
+
if (!value)
|
|
15
|
+
return 0;
|
|
16
|
+
const parsed = Number.parseFloat(value);
|
|
17
|
+
return Number.isFinite(parsed) ? Math.round(parsed * 100) : 0;
|
|
18
|
+
}
|
|
19
|
+
async function request(fetchImpl, url, init) {
|
|
20
|
+
try {
|
|
21
|
+
const response = await fetchImpl(url, { ...init, headers: { accept: "application/json", ...(init?.headers ?? {}) } });
|
|
22
|
+
if (!response.ok)
|
|
23
|
+
return Err({ code: "WOO_API_FAILED", message: `WooCommerce request failed (${response.status}) for ${url}.`, retriable: response.status >= 500 });
|
|
24
|
+
return Ok({ data: await response.json(), response });
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
return Err({ code: "WOO_API_FAILED", message: error instanceof Error ? error.message : "WooCommerce request failed.", retriable: true });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function wooStatus(status) {
|
|
31
|
+
if (status === "completed")
|
|
32
|
+
return { status: "fulfilled" };
|
|
33
|
+
if (status === "processing" || status === "on-hold")
|
|
34
|
+
return { status: "confirmed" };
|
|
35
|
+
if (status === "cancelled")
|
|
36
|
+
return { status: "cancelled" };
|
|
37
|
+
if (status === "failed" || status === "refunded")
|
|
38
|
+
return { status: "failed" };
|
|
39
|
+
return { status: "pending" };
|
|
40
|
+
}
|
|
41
|
+
function credentials(store) {
|
|
42
|
+
const key = store.credentials.consumerKey;
|
|
43
|
+
const secret = store.credentials.consumerSecret;
|
|
44
|
+
return typeof key === "string" && typeof secret === "string" && key && secret ? { key, secret } : undefined;
|
|
45
|
+
}
|
|
46
|
+
function validBase64Hmac(secret, body, signature) {
|
|
47
|
+
if (!signature)
|
|
48
|
+
return false;
|
|
49
|
+
const expected = createHmac("sha256", secret).update(body).digest();
|
|
50
|
+
const actual = Buffer.from(signature, "base64");
|
|
51
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
52
|
+
}
|
|
53
|
+
function oauthError(code, message) {
|
|
54
|
+
return Err({ code, message, retriable: false });
|
|
55
|
+
}
|
|
56
|
+
function storeUrl(domain) {
|
|
57
|
+
try {
|
|
58
|
+
const url = new URL(/^https?:\/\//i.test(domain) ? domain : `https://${domain}`);
|
|
59
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url : undefined;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export function wooConnector(options = {}) {
|
|
66
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
67
|
+
return defineChannelConnector({
|
|
68
|
+
providerId: "woocommerce",
|
|
69
|
+
capabilities: { importCatalog: true, importInventory: true, pushOrder: true, receiveWebhooks: true },
|
|
70
|
+
buildAuthUrl(params) {
|
|
71
|
+
const store = storeUrl(params.storeDomain);
|
|
72
|
+
if (!store)
|
|
73
|
+
return oauthError("WOO_INVALID_STORE_DOMAIN", "WooCommerce storeDomain must be an HTTP(S) URL.");
|
|
74
|
+
let callback;
|
|
75
|
+
try {
|
|
76
|
+
callback = new URL(params.callbackUri);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return oauthError("WOO_INVALID_CALLBACK_URL", "WooCommerce callbackUri must be an HTTPS URL.");
|
|
80
|
+
}
|
|
81
|
+
if (callback.protocol !== "https:")
|
|
82
|
+
return oauthError("WOO_INVALID_CALLBACK_URL", "WooCommerce callbackUri must be an HTTPS URL.");
|
|
83
|
+
callback.searchParams.set("state", params.state);
|
|
84
|
+
const returnUrl = new URL(params.callbackUri);
|
|
85
|
+
returnUrl.searchParams.set("state", params.state);
|
|
86
|
+
returnUrl.searchParams.set("return", "1");
|
|
87
|
+
const url = new URL("/wc-auth/v1/authorize", store.origin);
|
|
88
|
+
url.searchParams.set("app_name", "Porulle");
|
|
89
|
+
url.searchParams.set("scope", "read_write");
|
|
90
|
+
url.searchParams.set("user_id", "porulle");
|
|
91
|
+
url.searchParams.set("return_url", returnUrl.toString());
|
|
92
|
+
url.searchParams.set("callback_url", callback.toString());
|
|
93
|
+
return Ok(url.toString());
|
|
94
|
+
},
|
|
95
|
+
async completeAuth(request, ctx) {
|
|
96
|
+
if (request.method !== "POST")
|
|
97
|
+
return oauthError("WOO_AUTH_METHOD_REQUIRED", "WooCommerce auth credentials must be posted.");
|
|
98
|
+
const store = storeUrl(ctx.storeDomain);
|
|
99
|
+
if (!store)
|
|
100
|
+
return oauthError("WOO_INVALID_STORE_DOMAIN", "WooCommerce storeDomain must be an HTTP(S) URL.");
|
|
101
|
+
try {
|
|
102
|
+
const body = await request.json();
|
|
103
|
+
const consumerKey = body.consumer_key;
|
|
104
|
+
const consumerSecret = body.consumer_secret;
|
|
105
|
+
if (typeof consumerKey !== "string" || !consumerKey || typeof consumerSecret !== "string" || !consumerSecret) {
|
|
106
|
+
return oauthError("WOO_AUTH_CREDENTIALS_INVALID", "WooCommerce auth response must include consumer_key and consumer_secret.");
|
|
107
|
+
}
|
|
108
|
+
return Ok({ credentials: { consumerKey, consumerSecret }, storeDomain: ctx.storeDomain });
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return oauthError("WOO_AUTH_RESPONSE_INVALID", "WooCommerce auth response must be valid JSON.");
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
async importCatalog(store, cursor) {
|
|
115
|
+
const auth = credentials(store);
|
|
116
|
+
if (!auth)
|
|
117
|
+
return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
|
|
118
|
+
const [pagePart, ...afterParts] = cursor?.split("|") ?? [];
|
|
119
|
+
const isPage = pagePart === undefined || /^\d+$/.test(pagePart);
|
|
120
|
+
const parsedPage = isPage && pagePart ? Number.parseInt(pagePart, 10) : 1;
|
|
121
|
+
const page = Number.isFinite(parsedPage) && parsedPage > 0 ? parsedPage : 1;
|
|
122
|
+
const modifiedAfter = afterParts.length > 0 ? afterParts.join("|") : (!isPage ? cursor : undefined);
|
|
123
|
+
const result = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products", auth.key, auth.secret, page, modifiedAfter));
|
|
124
|
+
if (!result.ok)
|
|
125
|
+
return result;
|
|
126
|
+
const totalPages = Number.parseInt(result.value.response.headers.get("x-wp-totalpages") ?? "1", 10);
|
|
127
|
+
const nextCursor = page < totalPages ? (modifiedAfter ? `${page + 1}|${modifiedAfter}` : String(page + 1)) : null;
|
|
128
|
+
return Ok({ items: result.value.data.map((product) => ({
|
|
129
|
+
externalId: String(product.id),
|
|
130
|
+
slug: product.slug ?? String(product.id),
|
|
131
|
+
title: product.name,
|
|
132
|
+
...(product.description ? { description: product.description } : {}),
|
|
133
|
+
variants: (product.variations ?? []).map((variant) => ({
|
|
134
|
+
externalId: String(variant.id),
|
|
135
|
+
...(variant.sku ? { sku: variant.sku } : {}),
|
|
136
|
+
metadata: { price: parseMoney(variant.price) },
|
|
137
|
+
})),
|
|
138
|
+
})), nextCursor });
|
|
139
|
+
},
|
|
140
|
+
async fetchInventory(store, ids) {
|
|
141
|
+
const auth = credentials(store);
|
|
142
|
+
if (!auth)
|
|
143
|
+
return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
|
|
144
|
+
const page = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/products", auth.key, auth.secret, 1));
|
|
145
|
+
if (!page.ok)
|
|
146
|
+
return page;
|
|
147
|
+
const requested = ids ? new Set(ids) : undefined;
|
|
148
|
+
return Ok(page.value.data.filter((product) => !requested || requested.has(String(product.id))).map((product) => ({ externalId: String(product.id), available: product.stock_quantity ?? 0 })));
|
|
149
|
+
},
|
|
150
|
+
async pushOrder(store, slice) {
|
|
151
|
+
const auth = credentials(store);
|
|
152
|
+
if (!auth)
|
|
153
|
+
return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required.", retriable: false });
|
|
154
|
+
const url = buildWooUrl(store.storeDomain, "/wp-json/wc/v3/orders", auth.key, auth.secret, 1);
|
|
155
|
+
const [firstName, ...lastParts] = slice.customer.name.trim().split(/\s+/);
|
|
156
|
+
const address = slice.customer.shippingAddress;
|
|
157
|
+
const billing = { first_name: firstName ?? "", last_name: lastParts.join(" "), email: slice.customer.email, ...address };
|
|
158
|
+
const result = await request(fetchImpl, url, {
|
|
159
|
+
method: "POST",
|
|
160
|
+
headers: { "content-type": "application/json", "idempotency-key": `porulle:${slice.orderId}` },
|
|
161
|
+
body: JSON.stringify({ set_paid: true, line_items: slice.lines.map((line) => ({ variation_id: line.externalVariantId, quantity: line.quantity, total: line.totalPrice / 100 })), billing, shipping: address }),
|
|
162
|
+
});
|
|
163
|
+
if (!result.ok)
|
|
164
|
+
return result;
|
|
165
|
+
const id = String(result.value.data.id);
|
|
166
|
+
return Ok({ remoteOrderId: id, remoteUrl: `${store.storeDomain.replace(/\/$/, "")}/wp-admin/post.php?post=${id}&action=edit` });
|
|
167
|
+
},
|
|
168
|
+
async fetchOrderStatus(store, remoteId) {
|
|
169
|
+
const auth = credentials(store);
|
|
170
|
+
if (!auth)
|
|
171
|
+
return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required.", retriable: false });
|
|
172
|
+
const result = await request(fetchImpl, buildWooUrl(store.storeDomain, `/wp-json/wc/v3/orders/${encodeURIComponent(remoteId)}`, auth.key, auth.secret, 1));
|
|
173
|
+
return result.ok ? Ok(wooStatus(result.value.data.status)) : result;
|
|
174
|
+
},
|
|
175
|
+
async verifyWebhook(store, request) {
|
|
176
|
+
const body = await request.text();
|
|
177
|
+
if (!validBase64Hmac(store.webhookSecret ?? "", body, request.headers.get("x-wc-webhook-signature"))) {
|
|
178
|
+
return Err({ code: "INVALID_WEBHOOK_SIGNATURE", message: "Invalid WooCommerce webhook signature." });
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
const data = JSON.parse(body);
|
|
182
|
+
const id = request.headers.get("x-wc-webhook-id");
|
|
183
|
+
const type = request.headers.get("x-wc-webhook-topic");
|
|
184
|
+
if (!id || !type)
|
|
185
|
+
return Err({ code: "INVALID_WEBHOOK", message: "WooCommerce webhook headers are incomplete." });
|
|
186
|
+
return Ok({ id, type, data });
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return Err({ code: "INVALID_WEBHOOK", message: "WooCommerce webhook body must be valid JSON." });
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
async registerWebhooks(store, topics, callbackUrl) {
|
|
193
|
+
const auth = credentials(store);
|
|
194
|
+
if (!auth)
|
|
195
|
+
return Err({ code: "WOO_CREDENTIALS_REQUIRED", message: "WooCommerce consumerKey and consumerSecret are required." });
|
|
196
|
+
for (const topic of topics) {
|
|
197
|
+
const result = await request(fetchImpl, buildWooUrl(store.storeDomain, "/wp-json/wc/v3/webhooks", auth.key, auth.secret, 1), {
|
|
198
|
+
method: "POST",
|
|
199
|
+
headers: { "content-type": "application/json" },
|
|
200
|
+
body: JSON.stringify({ name: `Porulle ${topic}`, topic, delivery_url: callbackUrl, secret: store.webhookSecret }),
|
|
201
|
+
});
|
|
202
|
+
if (!result.ok)
|
|
203
|
+
return result;
|
|
204
|
+
}
|
|
205
|
+
return Ok({ registered: topics.length });
|
|
206
|
+
},
|
|
207
|
+
async refundExecute() { return Err({ code: "NOT_IMPLEMENTED", message: "WooCommerce refund execution is not implemented in this slice." }); },
|
|
208
|
+
});
|
|
209
|
+
}
|