@skalpgg/sdk 1.12.0 → 1.14.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 CHANGED
@@ -33,7 +33,7 @@ console.log(session.url)
33
33
 
34
34
  Send the buyer to `session.url`, then confirm the payment from the `order.paid` webhook.
35
35
 
36
- `new Skalp()` reads `SKALP_API_KEY` and `SKALP_WEBHOOK_SECRET`. You can also pass them in: `new Skalp('sk_live_xxx')` or `new Skalp({ apiKey, webhookSecret, baseUrl, timeout, maxRetries, fetch })`.
36
+ `new Skalp()` reads `SKALP_API_KEY` and `SKALP_WEBHOOK_SECRET`. You can also pass them in: `new Skalp('sk_live_xxx')` or `new Skalp({ apiKey, storeToken, webhookSecret, baseUrl, timeout, maxRetries, fetch })`.
37
37
 
38
38
  Create the key on the API keys page of your dashboard. Each key is bound to one store.
39
39
 
@@ -76,15 +76,22 @@ Create the key on the API keys page of your dashboard. Each key is bound to one
76
76
  | `queries.reply(id, { message })` / `queries.close(id)` / `queries.reopen(id)` | `queries:write` |
77
77
  | `blacklist.list({ type? })` / `blacklist.add({ type, value, note? })` / `blacklist.remove(id)` | `blacklist:read` / `blacklist:write` |
78
78
  | `whitelist.list({ type? })` / `whitelist.add({ type, value, note? })` / `whitelist.remove(id)` | `whitelist:read` / `whitelist:write` |
79
- | `subscriptions.createCheckout({ productId \| productSlug, externalRef?, customerEmail?, currency?, ads?, ... })` | `checkout:write` |
79
+ | `subscriptions.createCheckout({ productId \| productSlug, externalCustomerId?, customerEmail?, currency?, ads?, ... })` | `checkout:write` |
80
80
  | `subscriptions.getCheckout(id)` | `checkout:read` |
81
- | `subscriptions.list({ externalRef?, status?, updatedSince?, limit?, offset? })` | `subscriptions:read` |
81
+ | `subscriptions.list({ externalCustomerId?, status?, updatedSince?, limit?, offset? })` | `subscriptions:read` |
82
82
  | `subscriptions.get(id)` | `subscriptions:read` |
83
83
  | `subscriptions.changePlan(id, { productId \| productSlug })` | `subscriptions:write` |
84
- | `subscriptions.update(id, { externalRef })` | `subscriptions:write` |
84
+ | `subscriptions.update(id, { externalCustomerId })` | `subscriptions:write` |
85
85
  | `subscriptions.cancel(id)` | `subscriptions:write` |
86
86
  | `subscriptions.createUsageCharge(id, { amount, currency, description, idempotencyKey, periodStart, periodEnd })` | `subscriptions:write` |
87
87
  | `subscriptions.listInvoices(id)` | `subscriptions:read` |
88
+ | `usage.ingest(event \| events[])` | `usage:write` |
89
+ | `usage.summary({ meter, customer?, from?, to?, interval? })` | `usage:read` |
90
+ | `credits.get({ customerId \| externalCustomerId \| customerEmail })` | `usage:read` |
91
+ | `credits.transactions({ customer, meter?, limit?, offset? })` | `usage:read` |
92
+ | `credits.grant({ meter, customer, amount, idempotencyKey, expiresAt?, note? })` | `usage:write` |
93
+ | `meters.list()` | `usage:read` |
94
+ | `meters.create({ name, unit?, key? })` | `usage:write` |
88
95
  | `coins.createCheckout({ steamHex, coins, idempotencyKey?, returnUrl? })` | `coins:purchase` |
89
96
  | `coins.getCheckoutStatus(reference)` | `coins:read` |
90
97
  | `licenses.validate({ key, productId?, hardwareId? })` | `licenses:validate` |
@@ -199,6 +206,25 @@ await skalp.blacklist.add({ type: 'EMAIL', value: 'chargeback@example.com', note
199
206
 
200
207
  `type` is `EMAIL`, `IP`, `COUNTRY`, `ISP`, `ASN` or `HOST`. `blacklist.list` and `whitelist.list` return every rule as one array, not a page.
201
208
 
209
+ ## Credits and usage
210
+
211
+ Create a meter in the dashboard (or with `meters.create`), add credits to a product, then report usage as it happens:
212
+
213
+ ```ts
214
+ const { balance, access } = await skalp.usage.ingest({
215
+ meter: 'tokens',
216
+ externalCustomerId: user.id,
217
+ quantity: 1250,
218
+ idempotencyKey: requestId,
219
+ })
220
+
221
+ if (!access) return showTopUp()
222
+ ```
223
+
224
+ Pass your own user ID as `externalCustomerId` to `checkout.create` or `subscriptions.createCheckout` and the credits from that purchase land on that customer. `subscriptions.list` and `subscriptions.update` take it too, and `externalRef` still works as its older name. The first event for a new ID also needs `customerEmail`.
225
+
226
+ The same `idempotencyKey` is recorded once and comes back with `duplicate: true`. Send up to 1000 events as an array, and each one gets its own result or `error`. With `requireCredits: true` an event that would go below zero is refused with a 402 `INSUFFICIENT_CREDITS` and nothing is written. `credits.granted` and `credits.depleted` webhooks tell you when a balance changes hands.
227
+
202
228
  ## Usage charges
203
229
 
204
230
  ```ts
@@ -216,6 +242,32 @@ if (charge.status === 'open') await emailPaymentLink(charge.hostedUrl)
216
242
 
217
243
  The same `idempotencyKey` always returns the same charge, so retry with it after a timeout or a 5xx.
218
244
 
245
+ ## Headless baskets
246
+
247
+ Build your own cart on the Headless API and let Skalp take the payment. These calls use the store's public token (`pk_...`, from Integrations → Headless API) instead of the secret key, so they also run in the browser. Pass it as `storeToken` or set `SKALP_STORE_TOKEN`.
248
+
249
+ ```ts
250
+ const skalp = new Skalp({ storeToken: 'pk_live_xxx' })
251
+
252
+ const { ident } = await skalp.headless.baskets.create()
253
+ await skalp.headless.baskets.addItem(ident, { productId: 'prod_a', quantity: 2 })
254
+ await skalp.headless.baskets.addItem(ident, { productId: 'prod_b' })
255
+
256
+ const { url } = await skalp.headless.baskets.checkout(ident, {
257
+ externalRef: 'cart-42',
258
+ metadata: { customerId: 'cus_981' },
259
+ returnUrl: 'https://shop.example.com/thanks',
260
+ })
261
+ ```
262
+
263
+ Send the buyer to `url`. The other basket calls are `get`, `updateItem(ident, productId, { quantity })`, `removeItem`, `setCoupon(ident, code)` and `removeCoupon`; each returns the basket with server-side prices.
264
+
265
+ `externalRef` (up to 255 characters) and `metadata` (up to 10 string values) come back on the paid order: as `externalRef`, `basketIdent` and `metadata` in `order.paid`, `purchase.completed` and `orders.get`. They are attached only when the buyer pays for exactly the basket's items, and only one order can claim a basket. Once a basket is paid, `checkout` and every change answer 409 with `code: 'BASKET_COMPLETED'`, so start a new basket for the next order.
266
+
267
+ After a card, wallet, PayPal, crypto or paysafecard payment, the buyer goes back to `returnUrl` with `orderId` and `externalRef` added to its query string. Its host must be on the store's Allowed return domains (Integrations → Headless API), otherwise `checkout` answers 400 with `code: 'RETURN_URL_NOT_ALLOWED'`. It must be https; plain http works only for `localhost`.
268
+
269
+ The return URL is not proof of payment, since anyone can open it. Mark the order paid from the signed `order.paid` webhook or from `orders.get` with your secret key, and check that `basketIdent` or `externalRef` and the amount match your order.
270
+
219
271
  ## Webhooks
220
272
 
221
273
  Pass the raw request body, not parsed JSON, together with the request headers. `constructEvent` checks the `Skalp-Signature` header, an HMAC-SHA256 over the timestamp and the exact bytes Skalp sent, and rejects deliveries older than 5 minutes.
@@ -1,8 +1,9 @@
1
- import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint } from './types.js';
1
+ import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateMeterParams, CreditBalances, CreditGrantResult, CreditTransactionList, CustomerRef, GrantCreditsParams, ListCreditTransactionsParams, Meter, UsageError, UsageEvent, UsageResult, UsageSummary, UsageSummaryParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint, HeadlessBasket, HeadlessCheckout, HeadlessCheckoutParams } from './types.js';
2
2
  export type * from './types.js';
3
- export declare const VERSION = "1.12.0";
3
+ export declare const VERSION = "1.14.0";
4
4
  export interface SkalpOptions {
5
5
  apiKey?: string;
6
+ storeToken?: string;
6
7
  webhookSecret?: string;
7
8
  baseUrl?: string;
8
9
  timeout?: number;
@@ -33,7 +34,7 @@ export declare class Skalp {
33
34
  constructor(options?: string | SkalpOptions);
34
35
  readonly me: () => Promise<Me>;
35
36
  readonly checkout: {
36
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads }: CreateCheckoutParams) => Promise<CheckoutSession>;
37
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }: CreateCheckoutParams) => Promise<CheckoutSession>;
37
38
  get: (id: string) => Promise<CheckoutSessionStatus>;
38
39
  };
39
40
  readonly orders: {
@@ -82,6 +83,22 @@ export declare class Skalp {
82
83
  update: (id: string, { name, note }: UpdateCustomerParams) => Promise<Customer>;
83
84
  delete: (id: string) => Promise<Deleted>;
84
85
  };
86
+ readonly usage: {
87
+ ingest: {
88
+ (event: UsageEvent): Promise<UsageResult>;
89
+ (events: Array<UsageEvent>): Promise<Array<UsageResult | UsageError>>;
90
+ };
91
+ summary: ({ meter, from, to, interval, ...customer }: UsageSummaryParams) => Promise<UsageSummary>;
92
+ };
93
+ readonly credits: {
94
+ get: (customer: CustomerRef) => Promise<CreditBalances>;
95
+ transactions: ({ meter, limit, offset, ...customer }: ListCreditTransactionsParams) => Promise<CreditTransactionList>;
96
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }: GrantCreditsParams) => Promise<CreditGrantResult>;
97
+ };
98
+ readonly meters: {
99
+ list: () => Promise<Meter[]>;
100
+ create: ({ name, unit, key }: CreateMeterParams) => Promise<Meter>;
101
+ };
85
102
  readonly levels: {
86
103
  get: () => Promise<StoreLevels>;
87
104
  customer: (email: string) => Promise<CustomerLevel>;
@@ -116,12 +133,12 @@ export declare class Skalp {
116
133
  getCheckoutStatus: (reference: string) => Promise<CoinCheckoutStatus>;
117
134
  };
118
135
  readonly subscriptions: {
119
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, ads, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
136
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
120
137
  getCheckout: (id: string) => Promise<SubscriptionCheckoutStatus>;
121
- list: ({ externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
138
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
122
139
  get: (id: string) => Promise<Subscription>;
123
140
  changePlan: (id: string, { productId, productSlug }: ChangeSubscriptionPlanParams) => Promise<Subscription>;
124
- update: (id: string, { externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
141
+ update: (id: string, { externalCustomerId, externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
125
142
  cancel: (id: string) => Promise<Subscription>;
126
143
  createUsageCharge: (id: string, { amount, currency, description, idempotencyKey, periodStart, periodEnd }: CreateUsageChargeParams) => Promise<UsageCharge>;
127
144
  listInvoices: (id: string) => Promise<Invoice[]>;
@@ -136,6 +153,23 @@ export declare class Skalp {
136
153
  license: LicenseKeyInfo;
137
154
  }>;
138
155
  };
156
+ readonly headless: {
157
+ baskets: {
158
+ create: () => Promise<HeadlessBasket>;
159
+ get: (ident: string) => Promise<HeadlessBasket>;
160
+ addItem: (ident: string, { productId, quantity }: {
161
+ productId: string;
162
+ quantity?: number;
163
+ }) => Promise<HeadlessBasket>;
164
+ updateItem: (ident: string, productId: string, { quantity }: {
165
+ quantity: number;
166
+ }) => Promise<HeadlessBasket>;
167
+ removeItem: (ident: string, productId: string) => Promise<HeadlessBasket>;
168
+ setCoupon: (ident: string, code: string) => Promise<HeadlessBasket>;
169
+ removeCoupon: (ident: string) => Promise<HeadlessBasket>;
170
+ checkout: (ident: string, params?: HeadlessCheckoutParams) => Promise<HeadlessCheckout>;
171
+ };
172
+ };
139
173
  readonly webhooks: {
140
174
  list: () => Promise<WebhookEndpoint[]>;
141
175
  create: ({ url, events, productIds }: CreateWebhookParams) => Promise<CreatedWebhookEndpoint>;
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Skalp = exports.SkalpSignatureError = exports.SkalpConnectionError = exports.SkalpError = exports.VERSION = void 0;
4
- exports.VERSION = '1.12.0';
4
+ exports.VERSION = '1.14.0';
5
5
  const SIGNATURE_HEADER = 'skalp-signature';
6
6
  const SIGNATURE_TOLERANCE_SECONDS = 300;
7
7
  const PRODUCT_PAGE = 100;
@@ -118,6 +118,7 @@ function pick(source, keys) {
118
118
  }
119
119
  class Skalp {
120
120
  #apiKey;
121
+ #storeToken;
121
122
  #webhookSecret;
122
123
  #baseUrl;
123
124
  #timeout;
@@ -126,6 +127,7 @@ class Skalp {
126
127
  constructor(options = {}) {
127
128
  const o = typeof options === 'string' ? { apiKey: options } : options;
128
129
  this.#apiKey = o.apiKey ?? env('SKALP_API_KEY');
130
+ this.#storeToken = o.storeToken ?? env('SKALP_STORE_TOKEN');
129
131
  this.#webhookSecret = o.webhookSecret ?? env('SKALP_WEBHOOK_SECRET');
130
132
  this.#baseUrl = (o.baseUrl ?? env('SKALP_API_URL') ?? 'https://api.skalp.gg').replace(/\/+$/, '');
131
133
  this.#timeout = o.timeout && o.timeout > 0 ? o.timeout : DEFAULT_TIMEOUT_MS;
@@ -137,8 +139,8 @@ class Skalp {
137
139
  }
138
140
  me = () => this.#request('GET', '/v1/me');
139
141
  checkout = {
140
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads }) => this.#request('POST', '/v1/checkout/sessions', {
141
- body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player, ads },
142
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }) => this.#request('POST', '/v1/checkout/sessions', {
143
+ body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId },
142
144
  }),
143
145
  get: (id) => this.#request('GET', `/v1/checkout/sessions/${segment(id)}`),
144
146
  };
@@ -236,6 +238,33 @@ class Skalp {
236
238
  update: (id, { name, note }) => this.#request('PATCH', `/v1/customers/${segment(id)}`, { body: { name, note } }),
237
239
  delete: (id) => this.#request('DELETE', `/v1/customers/${segment(id)}`),
238
240
  };
241
+ usage = {
242
+ ingest: (async (events) => {
243
+ if (!Array.isArray(events)) {
244
+ return this.#request('POST', '/v1/usage/events', { body: usageEvent(events) });
245
+ }
246
+ const { data } = await this.#request('POST', '/v1/usage/events', {
247
+ body: { events: events.map(usageEvent) },
248
+ });
249
+ return data;
250
+ }),
251
+ summary: ({ meter, from, to, interval, ...customer }) => this.#request('GET', '/v1/usage', {
252
+ query: { meter, from: optionalDate(from), to: optionalDate(to), interval, ...customerQuery(customer) },
253
+ }),
254
+ };
255
+ credits = {
256
+ get: (customer) => this.#request('GET', '/v1/credits', { query: customerQuery(customer) }),
257
+ transactions: ({ meter, limit, offset, ...customer }) => this.#request('GET', '/v1/credits/transactions', {
258
+ query: { meter, limit, offset, ...customerQuery(customer) },
259
+ }),
260
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }) => this.#request('POST', '/v1/credits/grants', {
261
+ body: { meter, amount, idempotencyKey, expiresAt: optionalDate(expiresAt), note, metadata, ...customerQuery(customer) },
262
+ }),
263
+ };
264
+ meters = {
265
+ list: async () => (await this.#request('GET', '/v1/meters')).data,
266
+ create: ({ name, unit, key }) => this.#request('POST', '/v1/meters', { body: { name, unit, key } }),
267
+ };
239
268
  levels = {
240
269
  get: () => this.#request('GET', '/v1/levels'),
241
270
  customer: (email) => this.#request('GET', `/v1/levels/customers/${segment(email)}`),
@@ -271,12 +300,13 @@ class Skalp {
271
300
  getCheckoutStatus: (reference) => this.#request('GET', `/coins/checkout/${segment(reference)}/status`),
272
301
  };
273
302
  subscriptions = {
274
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, ads, }) => this.#request('POST', '/v1/subscriptions/checkout', {
275
- body: { productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, ads },
303
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }) => this.#request('POST', '/v1/subscriptions/checkout', {
304
+ body: { productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads },
276
305
  }),
277
306
  getCheckout: (id) => this.#request('GET', `/v1/subscriptions/checkout/${segment(id)}`),
278
- list: ({ externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
307
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
279
308
  query: {
309
+ externalCustomerId,
280
310
  externalRef,
281
311
  status,
282
312
  updatedSince: updatedSince instanceof Date ? updatedSince.toISOString() : updatedSince,
@@ -288,7 +318,7 @@ class Skalp {
288
318
  changePlan: (id, { productId, productSlug }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/plan`, {
289
319
  body: { productId, productSlug },
290
320
  }),
291
- update: (id, { externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalRef } }),
321
+ update: (id, { externalCustomerId, externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalCustomerId, externalRef } }),
292
322
  cancel: (id) => this.#request('DELETE', `/v1/subscriptions/${segment(id)}`),
293
323
  createUsageCharge: (id, { amount, currency, description, idempotencyKey, periodStart, periodEnd }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/usage-charges`, {
294
324
  body: {
@@ -322,6 +352,29 @@ class Skalp {
322
352
  body: { key, hardwareId },
323
353
  }),
324
354
  };
355
+ headless = {
356
+ baskets: {
357
+ create: () => this.#request('POST', '/headless/v1/baskets', { store: true }),
358
+ get: (ident) => this.#request('GET', `/headless/v1/baskets/${segment(ident)}`, { store: true }),
359
+ addItem: (ident, { productId, quantity }) => this.#request('POST', `/headless/v1/baskets/${segment(ident)}/items`, {
360
+ store: true,
361
+ body: { productId, quantity },
362
+ }),
363
+ updateItem: (ident, productId, { quantity }) => this.#request('PATCH', `/headless/v1/baskets/${segment(ident)}/items/${segment(productId)}`, {
364
+ store: true,
365
+ body: { quantity },
366
+ }),
367
+ removeItem: (ident, productId) => this.#request('DELETE', `/headless/v1/baskets/${segment(ident)}/items/${segment(productId)}`, {
368
+ store: true,
369
+ }),
370
+ setCoupon: (ident, code) => this.#request('PUT', `/headless/v1/baskets/${segment(ident)}/coupon`, { store: true, body: { code } }),
371
+ removeCoupon: (ident) => this.#request('DELETE', `/headless/v1/baskets/${segment(ident)}/coupon`, { store: true }),
372
+ checkout: (ident, params) => this.#request('POST', `/headless/v1/baskets/${segment(ident)}/checkout`, {
373
+ store: true,
374
+ body: params && pick(params, ['externalRef', 'metadata', 'returnUrl']),
375
+ }),
376
+ },
377
+ };
325
378
  webhooks = {
326
379
  list: () => this.#request('GET', '/v1/webhooks'),
327
380
  create: ({ url, events, productIds }) => this.#request('POST', '/v1/webhooks', { body: { url, events, productIds } }),
@@ -357,8 +410,11 @@ class Skalp {
357
410
  async #request(method, path, options = {}) {
358
411
  return (await this.#send(method, path, options)).data;
359
412
  }
360
- async #send(method, path, { body, query, auth = true } = {}) {
361
- if (auth && !this.#apiKey) {
413
+ async #send(method, path, { body, query, auth = true, store = false } = {}) {
414
+ if (store && !this.#storeToken) {
415
+ throw new Error('Skalp: missing store token. Pass storeToken to new Skalp() or set SKALP_STORE_TOKEN.');
416
+ }
417
+ if (auth && !store && !this.#apiKey) {
362
418
  throw new Error('Skalp: missing API key. Pass it to new Skalp(apiKey) or set SKALP_API_KEY.');
363
419
  }
364
420
  if (path.includes(INVALID_SEGMENT))
@@ -372,7 +428,9 @@ class Skalp {
372
428
  url.searchParams.set(name, String(value));
373
429
  }
374
430
  const headers = { accept: 'application/json', 'user-agent': USER_AGENT };
375
- if (auth)
431
+ if (store)
432
+ headers['x-store-token'] = this.#storeToken;
433
+ else if (auth)
376
434
  headers['x-api-key'] = this.#apiKey;
377
435
  if (body !== undefined)
378
436
  headers['content-type'] = 'application/json';
@@ -412,6 +470,20 @@ class Skalp {
412
470
  }
413
471
  }
414
472
  exports.Skalp = Skalp;
473
+ function customerQuery({ customerId, externalCustomerId, customerEmail }) {
474
+ return { customerId, externalCustomerId, customerEmail };
475
+ }
476
+ function usageEvent({ meter, quantity, idempotencyKey, timestamp, metadata, requireCredits, ...customer }) {
477
+ return {
478
+ meter,
479
+ quantity,
480
+ idempotencyKey,
481
+ timestamp: optionalDate(timestamp),
482
+ metadata,
483
+ requireCredits,
484
+ ...customerQuery(customer),
485
+ };
486
+ }
415
487
  function readSignature(source) {
416
488
  if (source == null || typeof source === 'string')
417
489
  return source ?? undefined;
@@ -40,6 +40,7 @@ export interface CreateCheckoutParams {
40
40
  customFields?: Record<string, string>;
41
41
  player?: PlayerInput;
42
42
  ads?: AdsInput;
43
+ externalCustomerId?: string;
43
44
  }
44
45
  export interface CheckoutSession {
45
46
  id: string;
@@ -95,6 +96,8 @@ export interface Order {
95
96
  updatedAt: string;
96
97
  completedAt: string | null;
97
98
  metadata: Metadata;
99
+ externalRef: string | null;
100
+ basketIdent: string | null;
98
101
  /** One entry per product: a bundle or a cart order has several. */
99
102
  items?: Array<OrderItem>;
100
103
  replacements?: Array<OrderReplacement>;
@@ -767,6 +770,7 @@ export interface CreateSubscriptionCheckoutParams {
767
770
  productId?: string;
768
771
  productSlug?: string;
769
772
  customerEmail?: string;
773
+ externalCustomerId?: string;
770
774
  externalRef?: string;
771
775
  metadata?: Metadata;
772
776
  currency?: 'EUR' | 'USD' | 'PLN' | 'BRL';
@@ -791,6 +795,7 @@ export interface Subscription {
791
795
  id: string;
792
796
  status: SubscriptionStatus;
793
797
  active: boolean;
798
+ externalCustomerId: string | null;
794
799
  externalRef: string | null;
795
800
  productId: string;
796
801
  productSlug: string;
@@ -813,10 +818,15 @@ export interface ChangeSubscriptionPlanParams {
813
818
  productId?: string;
814
819
  productSlug?: string;
815
820
  }
816
- export interface UpdateSubscriptionParams {
821
+ export type UpdateSubscriptionParams = {
822
+ externalCustomerId: string | null;
823
+ externalRef?: never;
824
+ } | {
817
825
  externalRef: string | null;
818
- }
826
+ externalCustomerId?: never;
827
+ };
819
828
  export interface ListSubscriptionsParams {
829
+ externalCustomerId?: string;
820
830
  externalRef?: string;
821
831
  status?: SubscriptionStatus;
822
832
  updatedSince?: string | Date;
@@ -979,6 +989,8 @@ export interface OrderPaidData {
979
989
  steamhex: string | null;
980
990
  identifier: string | null;
981
991
  metadata: Metadata;
992
+ externalRef: string | null;
993
+ basketIdent: string | null;
982
994
  /** The buyer's answers to the product's custom fields. */
983
995
  customFields: Record<string, string>;
984
996
  deliveryType?: string;
@@ -1145,6 +1157,183 @@ export interface CustomerLevelEventData {
1145
1157
  xp: number;
1146
1158
  tier: LevelTier;
1147
1159
  }
1160
+ export interface CustomerRef {
1161
+ customerId?: string;
1162
+ externalCustomerId?: string;
1163
+ customerEmail?: string;
1164
+ }
1165
+ export interface UsageEvent extends CustomerRef {
1166
+ meter: string;
1167
+ quantity?: number;
1168
+ idempotencyKey?: string;
1169
+ timestamp?: string | Date;
1170
+ metadata?: Record<string, string>;
1171
+ requireCredits?: boolean;
1172
+ }
1173
+ export interface UsageResult {
1174
+ id: string;
1175
+ duplicate: boolean;
1176
+ balance: number;
1177
+ access: boolean;
1178
+ }
1179
+ export interface UsageError {
1180
+ error: {
1181
+ code: string;
1182
+ message: string;
1183
+ };
1184
+ }
1185
+ export interface CreditOverage {
1186
+ price: number;
1187
+ units: number;
1188
+ currency: Currency;
1189
+ }
1190
+ export interface CreditBalance {
1191
+ meter: string;
1192
+ name: string;
1193
+ unit: string;
1194
+ balance: number;
1195
+ granted: number;
1196
+ used: number;
1197
+ expiresNext: {
1198
+ amount: number;
1199
+ at: string;
1200
+ } | null;
1201
+ access: boolean;
1202
+ overage: CreditOverage | null;
1203
+ }
1204
+ export interface CreditBalances {
1205
+ customerId: string | null;
1206
+ data: Array<CreditBalance>;
1207
+ }
1208
+ export type CreditTransactionType = 'grant' | 'usage' | 'adjustment' | 'expiration' | 'revocation' | 'overage' | 'overage_reversal';
1209
+ export interface CreditTransaction {
1210
+ id: string;
1211
+ type: CreditTransactionType;
1212
+ meter: string;
1213
+ amount: number;
1214
+ balanceAfter: number;
1215
+ note: string | null;
1216
+ metadata: Record<string, unknown>;
1217
+ idempotencyKey: string | null;
1218
+ grantId: string | null;
1219
+ orderId: string | null;
1220
+ subscriptionId: string | null;
1221
+ occurredAt: string;
1222
+ createdAt: string;
1223
+ }
1224
+ export interface CreditTransactionList {
1225
+ data: Array<CreditTransaction>;
1226
+ total: number;
1227
+ limit: number;
1228
+ offset: number;
1229
+ }
1230
+ export interface ListCreditTransactionsParams extends CustomerRef {
1231
+ meter?: string;
1232
+ limit?: number;
1233
+ offset?: number;
1234
+ }
1235
+ export interface GrantCreditsParams extends CustomerRef {
1236
+ meter: string;
1237
+ amount: number;
1238
+ idempotencyKey: string;
1239
+ expiresAt?: string | Date;
1240
+ note?: string;
1241
+ metadata?: Record<string, string>;
1242
+ }
1243
+ export interface CreditGrantResult {
1244
+ id: string;
1245
+ grantId: string | null;
1246
+ duplicate: boolean;
1247
+ amount: number;
1248
+ balance: number;
1249
+ access: boolean;
1250
+ }
1251
+ export interface UsageSummaryParams extends Partial<CustomerRef> {
1252
+ meter: string;
1253
+ from?: string | Date;
1254
+ to?: string | Date;
1255
+ interval?: 'hour' | 'day' | 'month';
1256
+ }
1257
+ export interface UsageSummary {
1258
+ meter: string;
1259
+ interval: 'hour' | 'day' | 'month';
1260
+ from: string;
1261
+ to: string;
1262
+ total: number;
1263
+ events: number;
1264
+ data: Array<{
1265
+ start: string;
1266
+ quantity: number;
1267
+ events: number;
1268
+ }>;
1269
+ }
1270
+ export interface Meter {
1271
+ id: string;
1272
+ key: string;
1273
+ name: string;
1274
+ unit: string;
1275
+ archived: boolean;
1276
+ createdAt: string;
1277
+ }
1278
+ export interface CreateMeterParams {
1279
+ name: string;
1280
+ unit?: string;
1281
+ key?: string;
1282
+ }
1283
+ export interface CreditEventCustomer {
1284
+ customerId: string;
1285
+ externalCustomerId: string | null;
1286
+ customerEmail: string | null;
1287
+ meter: string;
1288
+ meterId: string;
1289
+ balance: number;
1290
+ }
1291
+ export interface CreditsGrantedData extends CreditEventCustomer {
1292
+ grantId: string;
1293
+ amount: number;
1294
+ source: 'order' | 'subscription' | 'manual' | 'api';
1295
+ expiresAt: string | null;
1296
+ orderId: string | null;
1297
+ subscriptionId: string | null;
1298
+ }
1299
+ export interface HeadlessMoney {
1300
+ amount: string;
1301
+ currency: Currency;
1302
+ }
1303
+ export interface HeadlessBasketItem {
1304
+ productId: string;
1305
+ name: string;
1306
+ image?: string | null;
1307
+ quantity: number;
1308
+ quantityLimits: {
1309
+ min: number;
1310
+ max: number;
1311
+ };
1312
+ unitPrice: HeadlessMoney;
1313
+ subtotal: HeadlessMoney;
1314
+ total: HeadlessMoney;
1315
+ }
1316
+ export interface HeadlessBasket {
1317
+ ident: string;
1318
+ items: Array<HeadlessBasketItem>;
1319
+ coupon: {
1320
+ code: string;
1321
+ applied: boolean;
1322
+ error?: string;
1323
+ } | null;
1324
+ subtotal: HeadlessMoney;
1325
+ discount: HeadlessMoney;
1326
+ total: HeadlessMoney;
1327
+ expiresAt: string;
1328
+ }
1329
+ export interface HeadlessCheckoutParams {
1330
+ externalRef?: string;
1331
+ metadata?: Record<string, string>;
1332
+ returnUrl?: string;
1333
+ }
1334
+ export interface HeadlessCheckout {
1335
+ url: string;
1336
+ }
1148
1337
  export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.canceled', OrderEventData> | Envelope<'order.replaced', OrderReplacedData> | Envelope<'order.paid' | 'purchase.completed', OrderPaidData> | Envelope<'order.refunded', OrderRefundedData> | Envelope<'order.disputed' | 'account.suspend', OrderDisputedData> | Envelope<'account.restore', AccountRestoreData> | Envelope<'subscription.created' | 'subscription.updated' | 'subscription.trial_started' | 'subscription.trial_ended', SubscriptionEventData> | Envelope<'subscription.upcoming', SubscriptionEventData & {
1149
1338
  amountDue: number;
1150
1339
  nextPaymentAttempt: string | null;
@@ -1169,6 +1358,6 @@ export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.can
1169
1358
  disputeId: string;
1170
1359
  disputeStatus: 'open' | 'won' | 'lost';
1171
1360
  disputeReason: string | null;
1172
- }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'webhook.test', WebhookTestData>;
1361
+ }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'credits.granted', CreditsGrantedData> | Envelope<'credits.depleted', CreditEventCustomer> | Envelope<'webhook.test', WebhookTestData>;
1173
1362
  export type SkalpEventType = SkalpEvent['type'];
1174
1363
  export {};
@@ -1,8 +1,9 @@
1
- import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint } from './types.js';
1
+ import type { AccessRule, AddAccessRuleParams, AddSerialsParams, AddSerialsResult, AppealFeedbackParams, ChangeSubscriptionPlanParams, CheckoutSession, CheckoutSessionStatus, CoinCheckout, CoinCheckoutStatus, Coupon, CreateCheckoutParams, CreateCoinCheckoutParams, CreateCouponParams, CreateCustomerParams, CreateMeterParams, CreditBalances, CreditGrantResult, CreditTransactionList, CustomerRef, GrantCreditsParams, ListCreditTransactionsParams, Meter, UsageError, UsageEvent, UsageResult, UsageSummary, UsageSummaryParams, CreateProductGroupParams, CreateProductParams, CreateStoreCategoryParams, CreateSubscriptionCheckoutParams, CreateUsageChargeParams, CreateWebhookParams, CreatedWebhookEndpoint, Customer, CustomerDetails, CustomerLevel, LevelProductRule, LevelProducts, CustomerList, Deleted, Feedback, FeedbackList, HeartbeatParams, Invoice, LicenseKeyInfo, LicenseValidation, LicenseVerification, ListAccessRulesParams, ListCustomersParams, ListFeedbackParams, ListOrdersParams, ListProductsParams, ListQueriesParams, ListSerialsParams, ListSubscriptionsParams, Me, Order, OrderKeysReplaced, OrderList, Product, ProductGroup, ProductStock, ReplaceOrderKeysParams, ReplyParams, SerialList, SkalpEvent, StoreLevels, StoreCategory, StoreCategoryWithCount, Subscription, SubscriptionCheckout, SubscriptionCheckoutStatus, SubscriptionList, SupportQueryDetails, SupportQueryList, ResetLicenseDevicesParams, UpdateCouponParams, UpdateCustomerParams, UpdateSubscriptionParams, UpdateProductGroupParams, UpdateProductParams, UpdateStoreCategoryParams, UsageCharge, ValidateLicenseParams, VerifyLicenseParams, WebhookEndpoint, HeadlessBasket, HeadlessCheckout, HeadlessCheckoutParams } from './types.js';
2
2
  export type * from './types.js';
3
- export declare const VERSION = "1.12.0";
3
+ export declare const VERSION = "1.14.0";
4
4
  export interface SkalpOptions {
5
5
  apiKey?: string;
6
+ storeToken?: string;
6
7
  webhookSecret?: string;
7
8
  baseUrl?: string;
8
9
  timeout?: number;
@@ -33,7 +34,7 @@ export declare class Skalp {
33
34
  constructor(options?: string | SkalpOptions);
34
35
  readonly me: () => Promise<Me>;
35
36
  readonly checkout: {
36
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads }: CreateCheckoutParams) => Promise<CheckoutSession>;
37
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }: CreateCheckoutParams) => Promise<CheckoutSession>;
37
38
  get: (id: string) => Promise<CheckoutSessionStatus>;
38
39
  };
39
40
  readonly orders: {
@@ -82,6 +83,22 @@ export declare class Skalp {
82
83
  update: (id: string, { name, note }: UpdateCustomerParams) => Promise<Customer>;
83
84
  delete: (id: string) => Promise<Deleted>;
84
85
  };
86
+ readonly usage: {
87
+ ingest: {
88
+ (event: UsageEvent): Promise<UsageResult>;
89
+ (events: Array<UsageEvent>): Promise<Array<UsageResult | UsageError>>;
90
+ };
91
+ summary: ({ meter, from, to, interval, ...customer }: UsageSummaryParams) => Promise<UsageSummary>;
92
+ };
93
+ readonly credits: {
94
+ get: (customer: CustomerRef) => Promise<CreditBalances>;
95
+ transactions: ({ meter, limit, offset, ...customer }: ListCreditTransactionsParams) => Promise<CreditTransactionList>;
96
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }: GrantCreditsParams) => Promise<CreditGrantResult>;
97
+ };
98
+ readonly meters: {
99
+ list: () => Promise<Meter[]>;
100
+ create: ({ name, unit, key }: CreateMeterParams) => Promise<Meter>;
101
+ };
85
102
  readonly levels: {
86
103
  get: () => Promise<StoreLevels>;
87
104
  customer: (email: string) => Promise<CustomerLevel>;
@@ -116,12 +133,12 @@ export declare class Skalp {
116
133
  getCheckoutStatus: (reference: string) => Promise<CoinCheckoutStatus>;
117
134
  };
118
135
  readonly subscriptions: {
119
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, ads, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
136
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }: CreateSubscriptionCheckoutParams) => Promise<SubscriptionCheckout>;
120
137
  getCheckout: (id: string) => Promise<SubscriptionCheckoutStatus>;
121
- list: ({ externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
138
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset }?: ListSubscriptionsParams) => Promise<SubscriptionList>;
122
139
  get: (id: string) => Promise<Subscription>;
123
140
  changePlan: (id: string, { productId, productSlug }: ChangeSubscriptionPlanParams) => Promise<Subscription>;
124
- update: (id: string, { externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
141
+ update: (id: string, { externalCustomerId, externalRef }: UpdateSubscriptionParams) => Promise<Subscription>;
125
142
  cancel: (id: string) => Promise<Subscription>;
126
143
  createUsageCharge: (id: string, { amount, currency, description, idempotencyKey, periodStart, periodEnd }: CreateUsageChargeParams) => Promise<UsageCharge>;
127
144
  listInvoices: (id: string) => Promise<Invoice[]>;
@@ -136,6 +153,23 @@ export declare class Skalp {
136
153
  license: LicenseKeyInfo;
137
154
  }>;
138
155
  };
156
+ readonly headless: {
157
+ baskets: {
158
+ create: () => Promise<HeadlessBasket>;
159
+ get: (ident: string) => Promise<HeadlessBasket>;
160
+ addItem: (ident: string, { productId, quantity }: {
161
+ productId: string;
162
+ quantity?: number;
163
+ }) => Promise<HeadlessBasket>;
164
+ updateItem: (ident: string, productId: string, { quantity }: {
165
+ quantity: number;
166
+ }) => Promise<HeadlessBasket>;
167
+ removeItem: (ident: string, productId: string) => Promise<HeadlessBasket>;
168
+ setCoupon: (ident: string, code: string) => Promise<HeadlessBasket>;
169
+ removeCoupon: (ident: string) => Promise<HeadlessBasket>;
170
+ checkout: (ident: string, params?: HeadlessCheckoutParams) => Promise<HeadlessCheckout>;
171
+ };
172
+ };
139
173
  readonly webhooks: {
140
174
  list: () => Promise<WebhookEndpoint[]>;
141
175
  create: ({ url, events, productIds }: CreateWebhookParams) => Promise<CreatedWebhookEndpoint>;
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '1.12.0';
1
+ export const VERSION = '1.14.0';
2
2
  const SIGNATURE_HEADER = 'skalp-signature';
3
3
  const SIGNATURE_TOLERANCE_SECONDS = 300;
4
4
  const PRODUCT_PAGE = 100;
@@ -112,6 +112,7 @@ function pick(source, keys) {
112
112
  }
113
113
  export class Skalp {
114
114
  #apiKey;
115
+ #storeToken;
115
116
  #webhookSecret;
116
117
  #baseUrl;
117
118
  #timeout;
@@ -120,6 +121,7 @@ export class Skalp {
120
121
  constructor(options = {}) {
121
122
  const o = typeof options === 'string' ? { apiKey: options } : options;
122
123
  this.#apiKey = o.apiKey ?? env('SKALP_API_KEY');
124
+ this.#storeToken = o.storeToken ?? env('SKALP_STORE_TOKEN');
123
125
  this.#webhookSecret = o.webhookSecret ?? env('SKALP_WEBHOOK_SECRET');
124
126
  this.#baseUrl = (o.baseUrl ?? env('SKALP_API_URL') ?? 'https://api.skalp.gg').replace(/\/+$/, '');
125
127
  this.#timeout = o.timeout && o.timeout > 0 ? o.timeout : DEFAULT_TIMEOUT_MS;
@@ -131,8 +133,8 @@ export class Skalp {
131
133
  }
132
134
  me = () => this.#request('GET', '/v1/me');
133
135
  checkout = {
134
- create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads }) => this.#request('POST', '/v1/checkout/sessions', {
135
- body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player, ads },
136
+ create: ({ productId, quantity, customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId }) => this.#request('POST', '/v1/checkout/sessions', {
137
+ body: { items: [{ productId, quantity }], customerEmail, metadata, couponCode, returnUrl, customFields, player, ads, externalCustomerId },
136
138
  }),
137
139
  get: (id) => this.#request('GET', `/v1/checkout/sessions/${segment(id)}`),
138
140
  };
@@ -230,6 +232,33 @@ export class Skalp {
230
232
  update: (id, { name, note }) => this.#request('PATCH', `/v1/customers/${segment(id)}`, { body: { name, note } }),
231
233
  delete: (id) => this.#request('DELETE', `/v1/customers/${segment(id)}`),
232
234
  };
235
+ usage = {
236
+ ingest: (async (events) => {
237
+ if (!Array.isArray(events)) {
238
+ return this.#request('POST', '/v1/usage/events', { body: usageEvent(events) });
239
+ }
240
+ const { data } = await this.#request('POST', '/v1/usage/events', {
241
+ body: { events: events.map(usageEvent) },
242
+ });
243
+ return data;
244
+ }),
245
+ summary: ({ meter, from, to, interval, ...customer }) => this.#request('GET', '/v1/usage', {
246
+ query: { meter, from: optionalDate(from), to: optionalDate(to), interval, ...customerQuery(customer) },
247
+ }),
248
+ };
249
+ credits = {
250
+ get: (customer) => this.#request('GET', '/v1/credits', { query: customerQuery(customer) }),
251
+ transactions: ({ meter, limit, offset, ...customer }) => this.#request('GET', '/v1/credits/transactions', {
252
+ query: { meter, limit, offset, ...customerQuery(customer) },
253
+ }),
254
+ grant: ({ meter, amount, idempotencyKey, expiresAt, note, metadata, ...customer }) => this.#request('POST', '/v1/credits/grants', {
255
+ body: { meter, amount, idempotencyKey, expiresAt: optionalDate(expiresAt), note, metadata, ...customerQuery(customer) },
256
+ }),
257
+ };
258
+ meters = {
259
+ list: async () => (await this.#request('GET', '/v1/meters')).data,
260
+ create: ({ name, unit, key }) => this.#request('POST', '/v1/meters', { body: { name, unit, key } }),
261
+ };
233
262
  levels = {
234
263
  get: () => this.#request('GET', '/v1/levels'),
235
264
  customer: (email) => this.#request('GET', `/v1/levels/customers/${segment(email)}`),
@@ -265,12 +294,13 @@ export class Skalp {
265
294
  getCheckoutStatus: (reference) => this.#request('GET', `/coins/checkout/${segment(reference)}/status`),
266
295
  };
267
296
  subscriptions = {
268
- createCheckout: ({ productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, ads, }) => this.#request('POST', '/v1/subscriptions/checkout', {
269
- body: { productId, productSlug, customerEmail, externalRef, metadata, currency, returnUrl, ads },
297
+ createCheckout: ({ productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads, }) => this.#request('POST', '/v1/subscriptions/checkout', {
298
+ body: { productId, productSlug, customerEmail, externalCustomerId, externalRef, metadata, currency, returnUrl, ads },
270
299
  }),
271
300
  getCheckout: (id) => this.#request('GET', `/v1/subscriptions/checkout/${segment(id)}`),
272
- list: ({ externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
301
+ list: ({ externalCustomerId, externalRef, status, updatedSince, limit, offset } = {}) => this.#request('GET', '/v1/subscriptions', {
273
302
  query: {
303
+ externalCustomerId,
274
304
  externalRef,
275
305
  status,
276
306
  updatedSince: updatedSince instanceof Date ? updatedSince.toISOString() : updatedSince,
@@ -282,7 +312,7 @@ export class Skalp {
282
312
  changePlan: (id, { productId, productSlug }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/plan`, {
283
313
  body: { productId, productSlug },
284
314
  }),
285
- update: (id, { externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalRef } }),
315
+ update: (id, { externalCustomerId, externalRef }) => this.#request('PATCH', `/v1/subscriptions/${segment(id)}`, { body: { externalCustomerId, externalRef } }),
286
316
  cancel: (id) => this.#request('DELETE', `/v1/subscriptions/${segment(id)}`),
287
317
  createUsageCharge: (id, { amount, currency, description, idempotencyKey, periodStart, periodEnd }) => this.#request('POST', `/v1/subscriptions/${segment(id)}/usage-charges`, {
288
318
  body: {
@@ -316,6 +346,29 @@ export class Skalp {
316
346
  body: { key, hardwareId },
317
347
  }),
318
348
  };
349
+ headless = {
350
+ baskets: {
351
+ create: () => this.#request('POST', '/headless/v1/baskets', { store: true }),
352
+ get: (ident) => this.#request('GET', `/headless/v1/baskets/${segment(ident)}`, { store: true }),
353
+ addItem: (ident, { productId, quantity }) => this.#request('POST', `/headless/v1/baskets/${segment(ident)}/items`, {
354
+ store: true,
355
+ body: { productId, quantity },
356
+ }),
357
+ updateItem: (ident, productId, { quantity }) => this.#request('PATCH', `/headless/v1/baskets/${segment(ident)}/items/${segment(productId)}`, {
358
+ store: true,
359
+ body: { quantity },
360
+ }),
361
+ removeItem: (ident, productId) => this.#request('DELETE', `/headless/v1/baskets/${segment(ident)}/items/${segment(productId)}`, {
362
+ store: true,
363
+ }),
364
+ setCoupon: (ident, code) => this.#request('PUT', `/headless/v1/baskets/${segment(ident)}/coupon`, { store: true, body: { code } }),
365
+ removeCoupon: (ident) => this.#request('DELETE', `/headless/v1/baskets/${segment(ident)}/coupon`, { store: true }),
366
+ checkout: (ident, params) => this.#request('POST', `/headless/v1/baskets/${segment(ident)}/checkout`, {
367
+ store: true,
368
+ body: params && pick(params, ['externalRef', 'metadata', 'returnUrl']),
369
+ }),
370
+ },
371
+ };
319
372
  webhooks = {
320
373
  list: () => this.#request('GET', '/v1/webhooks'),
321
374
  create: ({ url, events, productIds }) => this.#request('POST', '/v1/webhooks', { body: { url, events, productIds } }),
@@ -351,8 +404,11 @@ export class Skalp {
351
404
  async #request(method, path, options = {}) {
352
405
  return (await this.#send(method, path, options)).data;
353
406
  }
354
- async #send(method, path, { body, query, auth = true } = {}) {
355
- if (auth && !this.#apiKey) {
407
+ async #send(method, path, { body, query, auth = true, store = false } = {}) {
408
+ if (store && !this.#storeToken) {
409
+ throw new Error('Skalp: missing store token. Pass storeToken to new Skalp() or set SKALP_STORE_TOKEN.');
410
+ }
411
+ if (auth && !store && !this.#apiKey) {
356
412
  throw new Error('Skalp: missing API key. Pass it to new Skalp(apiKey) or set SKALP_API_KEY.');
357
413
  }
358
414
  if (path.includes(INVALID_SEGMENT))
@@ -366,7 +422,9 @@ export class Skalp {
366
422
  url.searchParams.set(name, String(value));
367
423
  }
368
424
  const headers = { accept: 'application/json', 'user-agent': USER_AGENT };
369
- if (auth)
425
+ if (store)
426
+ headers['x-store-token'] = this.#storeToken;
427
+ else if (auth)
370
428
  headers['x-api-key'] = this.#apiKey;
371
429
  if (body !== undefined)
372
430
  headers['content-type'] = 'application/json';
@@ -405,6 +463,20 @@ export class Skalp {
405
463
  }
406
464
  }
407
465
  }
466
+ function customerQuery({ customerId, externalCustomerId, customerEmail }) {
467
+ return { customerId, externalCustomerId, customerEmail };
468
+ }
469
+ function usageEvent({ meter, quantity, idempotencyKey, timestamp, metadata, requireCredits, ...customer }) {
470
+ return {
471
+ meter,
472
+ quantity,
473
+ idempotencyKey,
474
+ timestamp: optionalDate(timestamp),
475
+ metadata,
476
+ requireCredits,
477
+ ...customerQuery(customer),
478
+ };
479
+ }
408
480
  function readSignature(source) {
409
481
  if (source == null || typeof source === 'string')
410
482
  return source ?? undefined;
@@ -40,6 +40,7 @@ export interface CreateCheckoutParams {
40
40
  customFields?: Record<string, string>;
41
41
  player?: PlayerInput;
42
42
  ads?: AdsInput;
43
+ externalCustomerId?: string;
43
44
  }
44
45
  export interface CheckoutSession {
45
46
  id: string;
@@ -95,6 +96,8 @@ export interface Order {
95
96
  updatedAt: string;
96
97
  completedAt: string | null;
97
98
  metadata: Metadata;
99
+ externalRef: string | null;
100
+ basketIdent: string | null;
98
101
  /** One entry per product: a bundle or a cart order has several. */
99
102
  items?: Array<OrderItem>;
100
103
  replacements?: Array<OrderReplacement>;
@@ -767,6 +770,7 @@ export interface CreateSubscriptionCheckoutParams {
767
770
  productId?: string;
768
771
  productSlug?: string;
769
772
  customerEmail?: string;
773
+ externalCustomerId?: string;
770
774
  externalRef?: string;
771
775
  metadata?: Metadata;
772
776
  currency?: 'EUR' | 'USD' | 'PLN' | 'BRL';
@@ -791,6 +795,7 @@ export interface Subscription {
791
795
  id: string;
792
796
  status: SubscriptionStatus;
793
797
  active: boolean;
798
+ externalCustomerId: string | null;
794
799
  externalRef: string | null;
795
800
  productId: string;
796
801
  productSlug: string;
@@ -813,10 +818,15 @@ export interface ChangeSubscriptionPlanParams {
813
818
  productId?: string;
814
819
  productSlug?: string;
815
820
  }
816
- export interface UpdateSubscriptionParams {
821
+ export type UpdateSubscriptionParams = {
822
+ externalCustomerId: string | null;
823
+ externalRef?: never;
824
+ } | {
817
825
  externalRef: string | null;
818
- }
826
+ externalCustomerId?: never;
827
+ };
819
828
  export interface ListSubscriptionsParams {
829
+ externalCustomerId?: string;
820
830
  externalRef?: string;
821
831
  status?: SubscriptionStatus;
822
832
  updatedSince?: string | Date;
@@ -979,6 +989,8 @@ export interface OrderPaidData {
979
989
  steamhex: string | null;
980
990
  identifier: string | null;
981
991
  metadata: Metadata;
992
+ externalRef: string | null;
993
+ basketIdent: string | null;
982
994
  /** The buyer's answers to the product's custom fields. */
983
995
  customFields: Record<string, string>;
984
996
  deliveryType?: string;
@@ -1145,6 +1157,183 @@ export interface CustomerLevelEventData {
1145
1157
  xp: number;
1146
1158
  tier: LevelTier;
1147
1159
  }
1160
+ export interface CustomerRef {
1161
+ customerId?: string;
1162
+ externalCustomerId?: string;
1163
+ customerEmail?: string;
1164
+ }
1165
+ export interface UsageEvent extends CustomerRef {
1166
+ meter: string;
1167
+ quantity?: number;
1168
+ idempotencyKey?: string;
1169
+ timestamp?: string | Date;
1170
+ metadata?: Record<string, string>;
1171
+ requireCredits?: boolean;
1172
+ }
1173
+ export interface UsageResult {
1174
+ id: string;
1175
+ duplicate: boolean;
1176
+ balance: number;
1177
+ access: boolean;
1178
+ }
1179
+ export interface UsageError {
1180
+ error: {
1181
+ code: string;
1182
+ message: string;
1183
+ };
1184
+ }
1185
+ export interface CreditOverage {
1186
+ price: number;
1187
+ units: number;
1188
+ currency: Currency;
1189
+ }
1190
+ export interface CreditBalance {
1191
+ meter: string;
1192
+ name: string;
1193
+ unit: string;
1194
+ balance: number;
1195
+ granted: number;
1196
+ used: number;
1197
+ expiresNext: {
1198
+ amount: number;
1199
+ at: string;
1200
+ } | null;
1201
+ access: boolean;
1202
+ overage: CreditOverage | null;
1203
+ }
1204
+ export interface CreditBalances {
1205
+ customerId: string | null;
1206
+ data: Array<CreditBalance>;
1207
+ }
1208
+ export type CreditTransactionType = 'grant' | 'usage' | 'adjustment' | 'expiration' | 'revocation' | 'overage' | 'overage_reversal';
1209
+ export interface CreditTransaction {
1210
+ id: string;
1211
+ type: CreditTransactionType;
1212
+ meter: string;
1213
+ amount: number;
1214
+ balanceAfter: number;
1215
+ note: string | null;
1216
+ metadata: Record<string, unknown>;
1217
+ idempotencyKey: string | null;
1218
+ grantId: string | null;
1219
+ orderId: string | null;
1220
+ subscriptionId: string | null;
1221
+ occurredAt: string;
1222
+ createdAt: string;
1223
+ }
1224
+ export interface CreditTransactionList {
1225
+ data: Array<CreditTransaction>;
1226
+ total: number;
1227
+ limit: number;
1228
+ offset: number;
1229
+ }
1230
+ export interface ListCreditTransactionsParams extends CustomerRef {
1231
+ meter?: string;
1232
+ limit?: number;
1233
+ offset?: number;
1234
+ }
1235
+ export interface GrantCreditsParams extends CustomerRef {
1236
+ meter: string;
1237
+ amount: number;
1238
+ idempotencyKey: string;
1239
+ expiresAt?: string | Date;
1240
+ note?: string;
1241
+ metadata?: Record<string, string>;
1242
+ }
1243
+ export interface CreditGrantResult {
1244
+ id: string;
1245
+ grantId: string | null;
1246
+ duplicate: boolean;
1247
+ amount: number;
1248
+ balance: number;
1249
+ access: boolean;
1250
+ }
1251
+ export interface UsageSummaryParams extends Partial<CustomerRef> {
1252
+ meter: string;
1253
+ from?: string | Date;
1254
+ to?: string | Date;
1255
+ interval?: 'hour' | 'day' | 'month';
1256
+ }
1257
+ export interface UsageSummary {
1258
+ meter: string;
1259
+ interval: 'hour' | 'day' | 'month';
1260
+ from: string;
1261
+ to: string;
1262
+ total: number;
1263
+ events: number;
1264
+ data: Array<{
1265
+ start: string;
1266
+ quantity: number;
1267
+ events: number;
1268
+ }>;
1269
+ }
1270
+ export interface Meter {
1271
+ id: string;
1272
+ key: string;
1273
+ name: string;
1274
+ unit: string;
1275
+ archived: boolean;
1276
+ createdAt: string;
1277
+ }
1278
+ export interface CreateMeterParams {
1279
+ name: string;
1280
+ unit?: string;
1281
+ key?: string;
1282
+ }
1283
+ export interface CreditEventCustomer {
1284
+ customerId: string;
1285
+ externalCustomerId: string | null;
1286
+ customerEmail: string | null;
1287
+ meter: string;
1288
+ meterId: string;
1289
+ balance: number;
1290
+ }
1291
+ export interface CreditsGrantedData extends CreditEventCustomer {
1292
+ grantId: string;
1293
+ amount: number;
1294
+ source: 'order' | 'subscription' | 'manual' | 'api';
1295
+ expiresAt: string | null;
1296
+ orderId: string | null;
1297
+ subscriptionId: string | null;
1298
+ }
1299
+ export interface HeadlessMoney {
1300
+ amount: string;
1301
+ currency: Currency;
1302
+ }
1303
+ export interface HeadlessBasketItem {
1304
+ productId: string;
1305
+ name: string;
1306
+ image?: string | null;
1307
+ quantity: number;
1308
+ quantityLimits: {
1309
+ min: number;
1310
+ max: number;
1311
+ };
1312
+ unitPrice: HeadlessMoney;
1313
+ subtotal: HeadlessMoney;
1314
+ total: HeadlessMoney;
1315
+ }
1316
+ export interface HeadlessBasket {
1317
+ ident: string;
1318
+ items: Array<HeadlessBasketItem>;
1319
+ coupon: {
1320
+ code: string;
1321
+ applied: boolean;
1322
+ error?: string;
1323
+ } | null;
1324
+ subtotal: HeadlessMoney;
1325
+ discount: HeadlessMoney;
1326
+ total: HeadlessMoney;
1327
+ expiresAt: string;
1328
+ }
1329
+ export interface HeadlessCheckoutParams {
1330
+ externalRef?: string;
1331
+ metadata?: Record<string, string>;
1332
+ returnUrl?: string;
1333
+ }
1334
+ export interface HeadlessCheckout {
1335
+ url: string;
1336
+ }
1148
1337
  export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.canceled', OrderEventData> | Envelope<'order.replaced', OrderReplacedData> | Envelope<'order.paid' | 'purchase.completed', OrderPaidData> | Envelope<'order.refunded', OrderRefundedData> | Envelope<'order.disputed' | 'account.suspend', OrderDisputedData> | Envelope<'account.restore', AccountRestoreData> | Envelope<'subscription.created' | 'subscription.updated' | 'subscription.trial_started' | 'subscription.trial_ended', SubscriptionEventData> | Envelope<'subscription.upcoming', SubscriptionEventData & {
1149
1338
  amountDue: number;
1150
1339
  nextPaymentAttempt: string | null;
@@ -1169,6 +1358,6 @@ export type SkalpEvent = Envelope<'order.created' | 'order.updated' | 'order.can
1169
1358
  disputeId: string;
1170
1359
  disputeStatus: 'open' | 'won' | 'lost';
1171
1360
  disputeReason: string | null;
1172
- }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'webhook.test', WebhookTestData>;
1361
+ }> | Envelope<'product.created' | 'product.updated', ProductEventData> | Envelope<'product.stock', ProductStockData> | Envelope<'query.created' | 'query.replied', QueryEventData> | Envelope<'feedback.received', FeedbackReceivedData> | Envelope<'customer.level_up' | 'customer.level_down', CustomerLevelEventData> | Envelope<'credits.granted', CreditsGrantedData> | Envelope<'credits.depleted', CreditEventCustomer> | Envelope<'webhook.test', WebhookTestData>;
1173
1362
  export type SkalpEventType = SkalpEvent['type'];
1174
1363
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skalpgg/sdk",
3
- "version": "1.12.0",
3
+ "version": "1.14.0",
4
4
  "description": "Official Skalp SDK for Node.js and edge runtimes: checkout, subscriptions, catalog and key stock, webhooks and license verification.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://skalp.gg/docs/sdk",