@skalpgg/sdk 1.13.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
 
@@ -242,6 +242,32 @@ if (charge.status === 'open') await emailPaymentLink(charge.hostedUrl)
242
242
 
243
243
  The same `idempotencyKey` always returns the same charge, so retry with it after a timeout or a 5xx.
244
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
+
245
271
  ## Webhooks
246
272
 
247
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, 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 } 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.13.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;
@@ -152,6 +153,23 @@ export declare class Skalp {
152
153
  license: LicenseKeyInfo;
153
154
  }>;
154
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
+ };
155
173
  readonly webhooks: {
156
174
  list: () => Promise<WebhookEndpoint[]>;
157
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.13.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;
@@ -350,6 +352,29 @@ class Skalp {
350
352
  body: { key, hardwareId },
351
353
  }),
352
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
+ };
353
378
  webhooks = {
354
379
  list: () => this.#request('GET', '/v1/webhooks'),
355
380
  create: ({ url, events, productIds }) => this.#request('POST', '/v1/webhooks', { body: { url, events, productIds } }),
@@ -385,8 +410,11 @@ class Skalp {
385
410
  async #request(method, path, options = {}) {
386
411
  return (await this.#send(method, path, options)).data;
387
412
  }
388
- async #send(method, path, { body, query, auth = true } = {}) {
389
- 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) {
390
418
  throw new Error('Skalp: missing API key. Pass it to new Skalp(apiKey) or set SKALP_API_KEY.');
391
419
  }
392
420
  if (path.includes(INVALID_SEGMENT))
@@ -400,7 +428,9 @@ class Skalp {
400
428
  url.searchParams.set(name, String(value));
401
429
  }
402
430
  const headers = { accept: 'application/json', 'user-agent': USER_AGENT };
403
- if (auth)
431
+ if (store)
432
+ headers['x-store-token'] = this.#storeToken;
433
+ else if (auth)
404
434
  headers['x-api-key'] = this.#apiKey;
405
435
  if (body !== undefined)
406
436
  headers['content-type'] = 'application/json';
@@ -96,6 +96,8 @@ export interface Order {
96
96
  updatedAt: string;
97
97
  completedAt: string | null;
98
98
  metadata: Metadata;
99
+ externalRef: string | null;
100
+ basketIdent: string | null;
99
101
  /** One entry per product: a bundle or a cart order has several. */
100
102
  items?: Array<OrderItem>;
101
103
  replacements?: Array<OrderReplacement>;
@@ -987,6 +989,8 @@ export interface OrderPaidData {
987
989
  steamhex: string | null;
988
990
  identifier: string | null;
989
991
  metadata: Metadata;
992
+ externalRef: string | null;
993
+ basketIdent: string | null;
990
994
  /** The buyer's answers to the product's custom fields. */
991
995
  customFields: Record<string, string>;
992
996
  deliveryType?: string;
@@ -1292,6 +1296,44 @@ export interface CreditsGrantedData extends CreditEventCustomer {
1292
1296
  orderId: string | null;
1293
1297
  subscriptionId: string | null;
1294
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
+ }
1295
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 & {
1296
1338
  amountDue: number;
1297
1339
  nextPaymentAttempt: string | null;
@@ -1,8 +1,9 @@
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 } 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.13.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;
@@ -152,6 +153,23 @@ export declare class Skalp {
152
153
  license: LicenseKeyInfo;
153
154
  }>;
154
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
+ };
155
173
  readonly webhooks: {
156
174
  list: () => Promise<WebhookEndpoint[]>;
157
175
  create: ({ url, events, productIds }: CreateWebhookParams) => Promise<CreatedWebhookEndpoint>;
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '1.13.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;
@@ -344,6 +346,29 @@ export class Skalp {
344
346
  body: { key, hardwareId },
345
347
  }),
346
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
+ };
347
372
  webhooks = {
348
373
  list: () => this.#request('GET', '/v1/webhooks'),
349
374
  create: ({ url, events, productIds }) => this.#request('POST', '/v1/webhooks', { body: { url, events, productIds } }),
@@ -379,8 +404,11 @@ export class Skalp {
379
404
  async #request(method, path, options = {}) {
380
405
  return (await this.#send(method, path, options)).data;
381
406
  }
382
- async #send(method, path, { body, query, auth = true } = {}) {
383
- 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) {
384
412
  throw new Error('Skalp: missing API key. Pass it to new Skalp(apiKey) or set SKALP_API_KEY.');
385
413
  }
386
414
  if (path.includes(INVALID_SEGMENT))
@@ -394,7 +422,9 @@ export class Skalp {
394
422
  url.searchParams.set(name, String(value));
395
423
  }
396
424
  const headers = { accept: 'application/json', 'user-agent': USER_AGENT };
397
- if (auth)
425
+ if (store)
426
+ headers['x-store-token'] = this.#storeToken;
427
+ else if (auth)
398
428
  headers['x-api-key'] = this.#apiKey;
399
429
  if (body !== undefined)
400
430
  headers['content-type'] = 'application/json';
@@ -96,6 +96,8 @@ export interface Order {
96
96
  updatedAt: string;
97
97
  completedAt: string | null;
98
98
  metadata: Metadata;
99
+ externalRef: string | null;
100
+ basketIdent: string | null;
99
101
  /** One entry per product: a bundle or a cart order has several. */
100
102
  items?: Array<OrderItem>;
101
103
  replacements?: Array<OrderReplacement>;
@@ -987,6 +989,8 @@ export interface OrderPaidData {
987
989
  steamhex: string | null;
988
990
  identifier: string | null;
989
991
  metadata: Metadata;
992
+ externalRef: string | null;
993
+ basketIdent: string | null;
990
994
  /** The buyer's answers to the product's custom fields. */
991
995
  customFields: Record<string, string>;
992
996
  deliveryType?: string;
@@ -1292,6 +1296,44 @@ export interface CreditsGrantedData extends CreditEventCustomer {
1292
1296
  orderId: string | null;
1293
1297
  subscriptionId: string | null;
1294
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
+ }
1295
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 & {
1296
1338
  amountDue: number;
1297
1339
  nextPaymentAttempt: string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skalpgg/sdk",
3
- "version": "1.13.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",