@shoplygg/node 0.1.0 → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shoply
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 CHANGED
@@ -75,4 +75,21 @@ await buyer.verify({ email, code });
75
75
  const me = await buyer.show();
76
76
  ```
77
77
 
78
+ ## OAuth
79
+
80
+ An app that sellers connect to their own stores gets a token by OAuth, and passes it as `apiKey`.
81
+
82
+ ```js
83
+ import Shoply, { oauth } from "@shoplygg/node";
84
+
85
+ const pkce = await oauth.pkce();
86
+ const url = oauth.authorizeUrl({ clientId, redirectUri, state, codeChallenge: pkce.challenge });
87
+
88
+ // Back at your redirect URL:
89
+ const token = await oauth.exchange({ clientId, clientSecret, code, redirectUri, codeVerifier: pkce.verifier });
90
+ const shoply = new Shoply({ apiKey: token.accessToken, storeId: token.storeId });
91
+ ```
92
+
93
+ How apps work: https://docs.shoply.gg/guides/oauth
94
+
78
95
  The whole guide: https://docs.shoply.gg/api-reference/node
@@ -21,6 +21,7 @@ export type KeyShowResult = {
21
21
  lastUsedAt: unknown;
22
22
  revokedAt: unknown;
23
23
  };
24
+ app: unknown;
24
25
  store: {
25
26
  id: string;
26
27
  name: string;
@@ -6867,6 +6868,16 @@ export type DisputesMarkSubmittedResult = {
6867
6868
  }[];
6868
6869
  };
6869
6870
 
6871
+ /** What add a file to a dispute's answer takes: `disputes.addFile`, the file and its fields. */
6872
+ export interface DisputesAddFileParams extends FileUpload {
6873
+ /**
6874
+ * What the file is: a chat with the buyer, a receipt, or something else.
6875
+ *
6876
+ * Left out, it is "other".
6877
+ */
6878
+ kind?: "communication" | "receipt" | "other";
6879
+ }
6880
+
6870
6881
  /** What add a file to a dispute's answer answers: `disputes.addFile`. */
6871
6882
  export type DisputesAddFileResult = unknown;
6872
6883
 
@@ -9816,6 +9827,8 @@ export interface ShoplyResourcesKey {
9816
9827
  *
9817
9828
  * What the key in the request is: its name, the permissions it carries, the addresses it accepts, and the store it belongs to with that store's ID. Make this your first call. Every other address needs the store's ID, and `api` in the answer is where that store's routes begin.
9818
9829
  *
9830
+ * An app's token is a key of the store it was approved for, and `app` says which app it is (null for the store's own keys): an app connected to many stores asks this to learn which store a token is for.
9831
+ *
9819
9832
  * Any live key may ask it, whatever its permissions.
9820
9833
  *
9821
9834
  * Any live API key may call this, whatever its permissions.
@@ -12097,7 +12110,7 @@ export interface ShoplyResourcesDisputes {
12097
12110
  *
12098
12111
  * @see https://docs.shoply.gg/api-reference/disputes/add-a-file-to-a-disputes-answer
12099
12112
  */
12100
- addFile(disputeId: string, params: FileUpload, options?: RequestOptions): Promise<DisputesAddFileResult>;
12113
+ addFile(disputeId: string, params: DisputesAddFileParams, options?: RequestOptions): Promise<DisputesAddFileResult>;
12101
12114
  /**
12102
12115
  * **Remove a file from a dispute's answer**
12103
12116
  *
@@ -12993,6 +13006,8 @@ export type WebhookEventName =
12993
13006
  | "dispute.won"
12994
13007
  | "dispute.lost"
12995
13008
  | "dispute.closed"
13009
+ | "app.connected"
13010
+ | "app.disconnected"
12996
13011
  | "fraud.checkout_blocked"
12997
13012
  | "webhook.test";
12998
13013
 
@@ -13256,6 +13271,18 @@ export interface WebhookEventData {
13256
13271
  * `data`: The dispute, as [List disputes](https://docs.shoply.gg/api-reference/disputes/list-disputes) answers it: `status` is how it reads on the dashboard, `providerStatus` what the provider last said, `dueAt` when it stops taking an answer.
13257
13272
  */
13258
13273
  "dispute.closed": DisputesListItem & Record<string, unknown>;
13274
+ /**
13275
+ * The store's owner approved an app, and the app's server swapped the approval for its token. An app approved again is connected again, and its old token stops working.
13276
+ *
13277
+ * `data`: `id` (the connection), `appId`, `name`, `maker`, `website`, `scopes` (what the owner approved), `connectedAt`, and for `app.disconnected` `disconnectedAt` and `reason`: `seller`, `app`, `deleted`, or `code_reused` (the app's approval was offered twice, so its token was ended).
13278
+ */
13279
+ "app.connected": Record<string, unknown>;
13280
+ /**
13281
+ * An app stopped reaching the store: the owner disconnected it, the app gave its token up, or its developer deleted it. The endpoints it made are removed with it.
13282
+ *
13283
+ * `data`: `id` (the connection), `appId`, `name`, `maker`, `website`, `scopes` (what the owner approved), `connectedAt`, and for `app.disconnected` `disconnectedAt` and `reason`: `seller`, `app`, `deleted`, or `code_reused` (the app's approval was offered twice, so its token was ended).
13284
+ */
13285
+ "app.disconnected": Record<string, unknown>;
13259
13286
  /**
13260
13287
  * A checkout was turned away by the blacklist, a blocked country, the VPN rule or the limit on unpaid orders. The same buyer turned away again for the same reason within ten minutes is not sent again.
13261
13288
  *
@@ -290,4 +290,4 @@ export const OPERATIONS = [
290
290
  ];
291
291
 
292
292
  /** Every webhook event, by name. */
293
- export const EVENTS = ["order.created","order.payment_started","order.paid","order.delivered","order.redelivered","order.email_failed","order.cancelled","order.refunded","order.disputed","order.chargeback","order.payment_submitted","order.rerouted","review.created","review.removed","review.flag_declined","stock.low","stock.out","product.created","product.updated","product.deleted","customer.created","customer.balance_changed","affiliate.created","affiliate.payout_requested","affiliate.payout_answered","affiliate.balance_changed","subscription.started","subscription.renewed","subscription.cancelled","subscription.ended","subscription.paused","subscription.resumed","subscription.charge_failed","cart.email_sent","cart.recovered","cart.unsubscribed","routing.processor_paused","routing.processor_resumed","dispute.opened","dispute.updated","dispute.won","dispute.lost","dispute.closed","fraud.checkout_blocked","webhook.test"];
293
+ export const EVENTS = ["order.created","order.payment_started","order.paid","order.delivered","order.redelivered","order.email_failed","order.cancelled","order.refunded","order.disputed","order.chargeback","order.payment_submitted","order.rerouted","review.created","review.removed","review.flag_declined","stock.low","stock.out","product.created","product.updated","product.deleted","customer.created","customer.balance_changed","affiliate.created","affiliate.payout_requested","affiliate.payout_answered","affiliate.balance_changed","subscription.started","subscription.renewed","subscription.cancelled","subscription.ended","subscription.paused","subscription.resumed","subscription.charge_failed","cart.email_sent","cart.recovered","cart.unsubscribed","routing.processor_paused","routing.processor_resumed","dispute.opened","dispute.updated","dispute.won","dispute.lost","dispute.closed","app.connected","app.disconnected","fraud.checkout_blocked","webhook.test"];
package/index.d.ts CHANGED
@@ -13,7 +13,10 @@ export * from "./generated/api.js";
13
13
  export declare const VERSION: string;
14
14
 
15
15
  export interface ClientOptions {
16
- /** `shoply_sk_...`, made under Developers, API Keys. Left out, SHOPLY_API_KEY from the environment. */
16
+ /**
17
+ * `shoply_sk_...`, made under Developers, API Keys, or an app's token (`shoply_at_...`) from
18
+ * `oauth.exchange()`. Left out, SHOPLY_API_KEY from the environment.
19
+ */
17
20
  apiKey?: string;
18
21
  /** The store's ID. Left out, it is asked of the key the first time it is needed. */
19
22
  storeId?: string;
@@ -118,6 +121,7 @@ export declare class Shoply {
118
121
  static readonly VERSION: string;
119
122
  static readonly EVENTS: readonly WebhookEventName[];
120
123
  static readonly webhooks: Webhooks;
124
+ static readonly oauth: OAuth;
121
125
  constructor(options?: ClientOptions);
122
126
  /** The store the key belongs to, asked once and remembered. */
123
127
  storeId(): Promise<string>;
@@ -183,4 +187,42 @@ export interface Webhooks {
183
187
 
184
188
  export declare const webhooks: Webhooks;
185
189
 
190
+ /** What a code is swapped for: a token of the seller's store, until they disconnect the app. */
191
+ export interface OAuthToken {
192
+ /** `shoply_at_...`: pass it as `apiKey`. */
193
+ accessToken: string;
194
+ tokenType: "Bearer";
195
+ /** What the seller approved: every permission the app asks for. */
196
+ scopes: string[];
197
+ /** The store it is for. */
198
+ storeId: string;
199
+ }
200
+
201
+ export interface OAuth {
202
+ /** The page to send a seller to. `state` is yours, sent back unchanged: check it. */
203
+ authorizeUrl(options: { clientId: string; redirectUri: string; state?: string; codeChallenge?: string; dashboardURL?: string }): string;
204
+ /** A PKCE pair: keep `verifier` until the code comes back, and send `challenge`. */
205
+ pkce(): Promise<{ verifier: string; challenge: string; method: "S256" }>;
206
+ /** A random `state`, to keep with the seller's session and compare when they come back. */
207
+ state(): string;
208
+ /**
209
+ * The code swapped for the token: with the client secret on a server, or with the PKCE
210
+ * verifier from a desktop or phone app. Throws a ShoplyError whose `code` is OAuth's word
211
+ * (`invalid_grant`, `invalid_client`).
212
+ */
213
+ exchange(options: {
214
+ clientId: string;
215
+ clientSecret?: string;
216
+ code: string;
217
+ redirectUri: string;
218
+ codeVerifier?: string;
219
+ baseURL?: string;
220
+ fetch?: typeof fetch;
221
+ }): Promise<OAuthToken>;
222
+ /** A token given up: it stops working at once. */
223
+ revoke(options: { clientId: string; clientSecret?: string; token: string; baseURL?: string; fetch?: typeof fetch }): Promise<void>;
224
+ }
225
+
226
+ export declare const oauth: OAuth;
227
+
186
228
  export default Shoply;
package/index.js CHANGED
@@ -8,11 +8,13 @@
8
8
  //
9
9
  // A route's id in the API reference is its method: `orders.show` is `shoply.orders.show()`.
10
10
  // The Customer API, which a buyer's own device asks with a token of theirs, is ShoplyCustomer.
11
+ // An app connected to a seller's store by OAuth passes its token as `apiKey`, and `oauth` has
12
+ // the steps that get one.
11
13
  // Docs: https://docs.shoply.gg/api-reference/node
12
14
 
13
15
  import { EVENTS, OPERATIONS } from "./generated/operations.js";
14
16
 
15
- export const VERSION = "0.1.0";
17
+ export const VERSION = "0.2.0";
16
18
 
17
19
  const API = "https://api.shoply.gg/v1";
18
20
 
@@ -267,6 +269,8 @@ function prepare(op, args) {
267
269
  if (op.upload) {
268
270
  form = new FormData();
269
271
  form.append(op.upload, toBlob(params.file, params.contentType), params.filename ?? params.file?.name ?? "upload");
272
+ // What the route takes beside the file (a dispute's file says its `kind`) is in the address.
273
+ query = Object.fromEntries(op.query.filter((name) => params[name] !== undefined).map((name) => [name, params[name]]));
270
274
  } else if (op.body) {
271
275
  query = {};
272
276
  body = {};
@@ -315,7 +319,7 @@ export class Shoply {
315
319
  #storeId;
316
320
 
317
321
  /**
318
- * @param options.apiKey `shoply_sk_...`. Left out, SHOPLY_API_KEY from the environment.
322
+ * @param options.apiKey `shoply_sk_...`, or an app's token (`shoply_at_...`). Left out, SHOPLY_API_KEY from the environment.
319
323
  * @param options.storeId The store's ID. Left out, it is asked of the key the first time it is needed.
320
324
  * @param options.timeout How long one try waits for an answer, in milliseconds. 60 seconds.
321
325
  * @param options.maxRetries How many more tries a request that can be repeated safely is given. 2.
@@ -330,8 +334,11 @@ export class Shoply {
330
334
 
331
335
  const apiKey = options.apiKey ?? globalThis.process?.env?.SHOPLY_API_KEY;
332
336
 
333
- if (typeof apiKey !== "string" || !apiKey.startsWith("shoply_sk_")) {
334
- throw new ShoplyError({ message: "Pass the store's secret API key as `apiKey` (shoply_sk_...), or set SHOPLY_API_KEY.", code: "api_key_required" });
337
+ if (typeof apiKey !== "string" || !(apiKey.startsWith("shoply_sk_") || apiKey.startsWith("shoply_at_"))) {
338
+ throw new ShoplyError({
339
+ message: "Pass the store's secret API key as `apiKey` (shoply_sk_...), or an app's token (shoply_at_...), or set SHOPLY_API_KEY.",
340
+ code: "api_key_required",
341
+ });
335
342
  }
336
343
 
337
344
  this.#storeId = options.storeId ? Promise.resolve(options.storeId) : null;
@@ -535,6 +542,131 @@ function same(a, b) {
535
542
 
536
543
  Shoply.webhooks = webhooks;
537
544
 
545
+ // ── OAuth ──────────────────────────────────────────────────────────────────────────────
546
+
547
+ const DASHBOARD = "https://dashboard.shoply.gg";
548
+
549
+ const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
550
+
551
+ /** An OAuth answer that was an error, as a ShoplyError: `code` is OAuth's own word (`invalid_grant`...). */
552
+ async function oauthPost(path, form, { clientId, clientSecret, baseURL, fetch: fetchFn }) {
553
+ const headers = { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", "User-Agent": userAgent() };
554
+
555
+ if (clientSecret) {
556
+ headers.Authorization = `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`;
557
+ } else {
558
+ form.client_id = clientId;
559
+ }
560
+
561
+ let answer;
562
+
563
+ try {
564
+ answer = await (fetchFn ?? globalThis.fetch)(`${String(baseURL ?? API).replace(/\/+$/, "")}${path}`, {
565
+ method: "POST",
566
+ headers,
567
+ body: new URLSearchParams(form).toString(),
568
+ });
569
+ } catch (cause) {
570
+ throw new ShoplyError({ message: "Shoply did not answer.", code: "connection_error", cause });
571
+ }
572
+
573
+ const text = await answer.text();
574
+ let body = null;
575
+
576
+ try {
577
+ body = text === "" ? {} : JSON.parse(text);
578
+ } catch {
579
+ body = null;
580
+ }
581
+
582
+ if (!answer.ok) {
583
+ throw new ShoplyError({
584
+ status: answer.status,
585
+ code: body?.error ?? (answer.status === 429 ? "rate_limited" : "oauth_error"),
586
+ message: body?.error_description ?? body?.message ?? `Shoply answered ${answer.status}.`,
587
+ retryAfter: Number(answer.headers.get("retry-after")) || null,
588
+ body,
589
+ });
590
+ }
591
+
592
+ return body ?? {};
593
+ }
594
+
595
+ /**
596
+ * Connecting an app to a seller's store, by OAuth's authorization code flow:
597
+ *
598
+ * 1. Send the seller to `authorizeUrl()`. With PKCE (always, for a desktop or phone app),
599
+ * make a pair with `pkce()` first, keep its verifier and send its challenge.
600
+ * 2. They come back to your redirect URL with `code` and your `state`. Check the state.
601
+ * 3. `exchange()` the code, on your server with the client secret, or with the verifier.
602
+ * 4. The token is a key of their store: `new Shoply({ apiKey: token })`. It works until the
603
+ * seller disconnects the app; `revoke()` gives it up.
604
+ */
605
+ export const oauth = {
606
+ /** The page to send a seller to. `state` is yours, sent back unchanged: check it. */
607
+ authorizeUrl({ clientId, redirectUri, state, codeChallenge, dashboardURL = DASHBOARD } = {}) {
608
+ if (!clientId || !redirectUri) throw new TypeError("Pass the app's clientId and the redirectUri the seller is sent back to.");
609
+
610
+ const url = new URL("/oauth/authorize/", dashboardURL);
611
+
612
+ url.searchParams.set("response_type", "code");
613
+ url.searchParams.set("client_id", clientId);
614
+ url.searchParams.set("redirect_uri", redirectUri);
615
+ if (state) url.searchParams.set("state", state);
616
+
617
+ if (codeChallenge) {
618
+ url.searchParams.set("code_challenge", codeChallenge);
619
+ url.searchParams.set("code_challenge_method", "S256");
620
+ }
621
+
622
+ return url.toString();
623
+ },
624
+
625
+ /** A PKCE pair: keep `verifier` until the code comes back, and send `challenge`. */
626
+ async pkce() {
627
+ const verifier = base64url(globalThis.crypto.getRandomValues(new Uint8Array(32)));
628
+ const challenge = base64url(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", encoder.encode(verifier))));
629
+
630
+ return { verifier, challenge, method: "S256" };
631
+ },
632
+
633
+ /** A random `state`, to keep with the seller's session and compare when they come back. */
634
+ state() {
635
+ return base64url(globalThis.crypto.getRandomValues(new Uint8Array(16)));
636
+ },
637
+
638
+ /**
639
+ * The code swapped for the token. A web app sends its client secret; a desktop or phone app
640
+ * sends the PKCE verifier and no secret. Throws a ShoplyError whose `code` is OAuth's word:
641
+ * `invalid_grant` (the code is wrong, used, or older than ten minutes), `invalid_client`.
642
+ */
643
+ async exchange({ clientId, clientSecret, code, redirectUri, codeVerifier, baseURL, fetch } = {}) {
644
+ if (!clientId || !code || !redirectUri) throw new TypeError("Pass clientId, the code and the redirectUri it came back to.");
645
+
646
+ const form = { grant_type: "authorization_code", code, redirect_uri: redirectUri };
647
+
648
+ if (codeVerifier) form.code_verifier = codeVerifier;
649
+
650
+ const body = await oauthPost("/oauth/token", form, { clientId, clientSecret, baseURL, fetch });
651
+
652
+ return {
653
+ accessToken: body.access_token,
654
+ tokenType: body.token_type,
655
+ scopes: String(body.scope ?? "").split(" ").filter(Boolean),
656
+ storeId: body.store_id,
657
+ };
658
+ },
659
+
660
+ /** A token given up: it stops working at once. Answered the same whether or not there was one. */
661
+ async revoke({ clientId, clientSecret, token, baseURL, fetch } = {}) {
662
+ if (!clientId || !token) throw new TypeError("Pass clientId and the token to give up.");
663
+
664
+ await oauthPost("/oauth/revoke", { token }, { clientId, clientSecret, baseURL, fetch });
665
+ },
666
+ };
667
+
668
+ Shoply.oauth = oauth;
669
+
538
670
  function userAgent() {
539
671
  const runtime = globalThis.process?.versions?.node ? `node/${globalThis.process.versions.node}` : "unknown";
540
672
 
package/package.json CHANGED
@@ -1,9 +1,16 @@
1
1
  {
2
2
  "name": "@shoplygg/node",
3
- "version": "0.1.0",
4
- "description": "Shoply's API from your own server: every route as a typed method, safe retries, pages, and checking webhooks.",
3
+ "version": "0.2.0",
4
+ "description": "Shoply's API from your own server: every route as a typed method, safe retries, pages, checking webhooks, and OAuth for apps.",
5
5
  "keywords": ["shoply", "api", "sdk", "ecommerce", "webhooks", "digital-goods"],
6
6
  "homepage": "https://docs.shoply.gg/api-reference/node",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/shoplygg/shoply-node.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/shoplygg/shoply-node/issues"
13
+ },
7
14
  "license": "MIT",
8
15
  "publishConfig": {
9
16
  "access": "public"
@@ -18,8 +25,11 @@
18
25
  }
19
26
  },
20
27
  "sideEffects": false,
21
- "files": ["index.js", "index.d.ts", "generated", "README.md"],
28
+ "files": ["index.js", "index.d.ts", "generated", "README.md", "LICENSE"],
22
29
  "engines": {
23
30
  "node": ">=20"
31
+ },
32
+ "scripts": {
33
+ "test": "node --test test/client.test.mjs"
24
34
  }
25
35
  }