@dodopayments/astro 0.2.2 → 0.2.4
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/dist/index.cjs +1526 -1475
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1526 -1475
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
package/dist/index.cjs
CHANGED
|
@@ -3961,7 +3961,7 @@ const unknownType = ZodUnknown.create;
|
|
|
3961
3961
|
ZodNever.create;
|
|
3962
3962
|
const arrayType = ZodArray.create;
|
|
3963
3963
|
const objectType = ZodObject.create;
|
|
3964
|
-
ZodUnion.create;
|
|
3964
|
+
const unionType = ZodUnion.create;
|
|
3965
3965
|
const discriminatedUnionType = ZodDiscriminatedUnion.create;
|
|
3966
3966
|
ZodIntersection.create;
|
|
3967
3967
|
ZodTuple.create;
|
|
@@ -4180,7 +4180,7 @@ const safeJSON = (text) => {
|
|
|
4180
4180
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
4181
4181
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
4182
4182
|
|
|
4183
|
-
const VERSION = '2.
|
|
4183
|
+
const VERSION = '2.4.6'; // x-release-please-version
|
|
4184
4184
|
|
|
4185
4185
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
4186
4186
|
/**
|
|
@@ -4930,6 +4930,9 @@ class CheckoutSessions extends APIResource {
|
|
|
4930
4930
|
create(body, options) {
|
|
4931
4931
|
return this._client.post('/checkouts', { body, ...options });
|
|
4932
4932
|
}
|
|
4933
|
+
retrieve(id, options) {
|
|
4934
|
+
return this._client.get(path `/checkouts/${id}`, options);
|
|
4935
|
+
}
|
|
4933
4936
|
}
|
|
4934
4937
|
|
|
4935
4938
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
@@ -5608,1434 +5611,325 @@ let Headers$1 = class Headers extends APIResource {
|
|
|
5608
5611
|
}
|
|
5609
5612
|
};
|
|
5610
5613
|
|
|
5611
|
-
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
5622
|
-
}
|
|
5623
|
-
/**
|
|
5624
|
-
* Get a webhook by id
|
|
5625
|
-
*/
|
|
5626
|
-
retrieve(webhookID, options) {
|
|
5627
|
-
return this._client.get(path `/webhooks/${webhookID}`, options);
|
|
5614
|
+
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
5615
|
+
|
|
5616
|
+
var dist = {};
|
|
5617
|
+
|
|
5618
|
+
var timing_safe_equal = {};
|
|
5619
|
+
|
|
5620
|
+
Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
|
|
5621
|
+
timing_safe_equal.timingSafeEqual = void 0;
|
|
5622
|
+
function assert(expr, msg = "") {
|
|
5623
|
+
if (!expr) {
|
|
5624
|
+
throw new Error(msg);
|
|
5628
5625
|
}
|
|
5629
|
-
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
|
|
5626
|
+
}
|
|
5627
|
+
function timingSafeEqual(a, b) {
|
|
5628
|
+
if (a.byteLength !== b.byteLength) {
|
|
5629
|
+
return false;
|
|
5634
5630
|
}
|
|
5635
|
-
|
|
5636
|
-
|
|
5637
|
-
*/
|
|
5638
|
-
list(query = {}, options) {
|
|
5639
|
-
return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
|
|
5631
|
+
if (!(a instanceof DataView)) {
|
|
5632
|
+
a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
|
|
5640
5633
|
}
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
*/
|
|
5644
|
-
delete(webhookID, options) {
|
|
5645
|
-
return this._client.delete(path `/webhooks/${webhookID}`, {
|
|
5646
|
-
...options,
|
|
5647
|
-
headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
|
|
5648
|
-
});
|
|
5634
|
+
if (!(b instanceof DataView)) {
|
|
5635
|
+
b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
|
|
5649
5636
|
}
|
|
5650
|
-
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
|
|
5654
|
-
|
|
5637
|
+
assert(a instanceof DataView);
|
|
5638
|
+
assert(b instanceof DataView);
|
|
5639
|
+
const length = a.byteLength;
|
|
5640
|
+
let out = 0;
|
|
5641
|
+
let i = -1;
|
|
5642
|
+
while (++i < length) {
|
|
5643
|
+
out |= a.getUint8(i) ^ b.getUint8(i);
|
|
5655
5644
|
}
|
|
5656
|
-
|
|
5657
|
-
|
|
5645
|
+
return out === 0;
|
|
5646
|
+
}
|
|
5647
|
+
timing_safe_equal.timingSafeEqual = timingSafeEqual;
|
|
5658
5648
|
|
|
5659
|
-
|
|
5649
|
+
var base64$1 = {};
|
|
5650
|
+
|
|
5651
|
+
// Copyright (C) 2016 Dmitry Chestnykh
|
|
5652
|
+
// MIT License. See LICENSE file for details.
|
|
5653
|
+
var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
|
|
5654
|
+
var extendStatics = function (d, b) {
|
|
5655
|
+
extendStatics = Object.setPrototypeOf ||
|
|
5656
|
+
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
|
5657
|
+
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
|
5658
|
+
return extendStatics(d, b);
|
|
5659
|
+
};
|
|
5660
|
+
return function (d, b) {
|
|
5661
|
+
extendStatics(d, b);
|
|
5662
|
+
function __() { this.constructor = d; }
|
|
5663
|
+
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
5664
|
+
};
|
|
5665
|
+
})();
|
|
5666
|
+
Object.defineProperty(base64$1, "__esModule", { value: true });
|
|
5660
5667
|
/**
|
|
5661
|
-
*
|
|
5662
|
-
*
|
|
5663
|
-
* Trims beginning and trailing whitespace.
|
|
5664
|
-
*
|
|
5665
|
-
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
|
5668
|
+
* Package base64 implements Base64 encoding and decoding.
|
|
5666
5669
|
*/
|
|
5667
|
-
|
|
5668
|
-
|
|
5669
|
-
|
|
5670
|
-
|
|
5671
|
-
if (typeof globalThis.Deno !== 'undefined') {
|
|
5672
|
-
return globalThis.Deno.env?.get?.(env)?.trim();
|
|
5673
|
-
}
|
|
5674
|
-
return undefined;
|
|
5675
|
-
};
|
|
5676
|
-
|
|
5677
|
-
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
5678
|
-
var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
|
|
5679
|
-
const environments = {
|
|
5680
|
-
live_mode: 'https://live.dodopayments.com',
|
|
5681
|
-
test_mode: 'https://test.dodopayments.com',
|
|
5682
|
-
};
|
|
5670
|
+
// Invalid character used in decoding to indicate
|
|
5671
|
+
// that the character to decode is out of range of
|
|
5672
|
+
// alphabet and cannot be decoded.
|
|
5673
|
+
var INVALID_BYTE = 256;
|
|
5683
5674
|
/**
|
|
5684
|
-
*
|
|
5675
|
+
* Implements standard Base64 encoding.
|
|
5676
|
+
*
|
|
5677
|
+
* Operates in constant time.
|
|
5685
5678
|
*/
|
|
5686
|
-
class
|
|
5687
|
-
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
|
|
5696
|
-
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
|
|
5697
|
-
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
|
|
5698
|
-
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
5699
|
-
*/
|
|
5700
|
-
constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
|
|
5701
|
-
_DodoPayments_instances.add(this);
|
|
5702
|
-
_DodoPayments_encoder.set(this, void 0);
|
|
5703
|
-
this.checkoutSessions = new CheckoutSessions(this);
|
|
5704
|
-
this.payments = new Payments(this);
|
|
5705
|
-
this.subscriptions = new Subscriptions(this);
|
|
5706
|
-
this.invoices = new Invoices(this);
|
|
5707
|
-
this.licenses = new Licenses(this);
|
|
5708
|
-
this.licenseKeys = new LicenseKeys(this);
|
|
5709
|
-
this.licenseKeyInstances = new LicenseKeyInstances(this);
|
|
5710
|
-
this.customers = new Customers(this);
|
|
5711
|
-
this.refunds = new Refunds(this);
|
|
5712
|
-
this.disputes = new Disputes(this);
|
|
5713
|
-
this.payouts = new Payouts(this);
|
|
5714
|
-
this.webhookEvents = new WebhookEvents(this);
|
|
5715
|
-
this.products = new Products(this);
|
|
5716
|
-
this.misc = new Misc(this);
|
|
5717
|
-
this.discounts = new Discounts(this);
|
|
5718
|
-
this.addons = new Addons(this);
|
|
5719
|
-
this.brands = new Brands(this);
|
|
5720
|
-
this.webhooks = new Webhooks$1(this);
|
|
5721
|
-
this.usageEvents = new UsageEvents(this);
|
|
5722
|
-
this.meters = new Meters(this);
|
|
5723
|
-
if (bearerToken === undefined) {
|
|
5724
|
-
throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
|
|
5679
|
+
var Coder = /** @class */ (function () {
|
|
5680
|
+
// TODO(dchest): methods to encode chunk-by-chunk.
|
|
5681
|
+
function Coder(_paddingCharacter) {
|
|
5682
|
+
if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
|
|
5683
|
+
this._paddingCharacter = _paddingCharacter;
|
|
5684
|
+
}
|
|
5685
|
+
Coder.prototype.encodedLength = function (length) {
|
|
5686
|
+
if (!this._paddingCharacter) {
|
|
5687
|
+
return (length * 8 + 5) / 6 | 0;
|
|
5725
5688
|
}
|
|
5726
|
-
|
|
5727
|
-
|
|
5728
|
-
|
|
5729
|
-
|
|
5730
|
-
|
|
5731
|
-
|
|
5732
|
-
|
|
5733
|
-
|
|
5689
|
+
return (length + 2) / 3 * 4 | 0;
|
|
5690
|
+
};
|
|
5691
|
+
Coder.prototype.encode = function (data) {
|
|
5692
|
+
var out = "";
|
|
5693
|
+
var i = 0;
|
|
5694
|
+
for (; i < data.length - 2; i += 3) {
|
|
5695
|
+
var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
|
|
5696
|
+
out += this._encodeByte((c >>> 3 * 6) & 63);
|
|
5697
|
+
out += this._encodeByte((c >>> 2 * 6) & 63);
|
|
5698
|
+
out += this._encodeByte((c >>> 1 * 6) & 63);
|
|
5699
|
+
out += this._encodeByte((c >>> 0 * 6) & 63);
|
|
5734
5700
|
}
|
|
5735
|
-
|
|
5736
|
-
|
|
5737
|
-
|
|
5738
|
-
|
|
5739
|
-
|
|
5740
|
-
|
|
5741
|
-
|
|
5742
|
-
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
|
|
5743
|
-
parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
|
|
5744
|
-
defaultLogLevel;
|
|
5745
|
-
this.fetchOptions = options.fetchOptions;
|
|
5746
|
-
this.maxRetries = options.maxRetries ?? 2;
|
|
5747
|
-
this.fetch = options.fetch ?? getDefaultFetch();
|
|
5748
|
-
__classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
|
|
5749
|
-
this._options = options;
|
|
5750
|
-
this.bearerToken = bearerToken;
|
|
5751
|
-
}
|
|
5752
|
-
/**
|
|
5753
|
-
* Create a new client instance re-using the same options given to the current client with optional overriding.
|
|
5754
|
-
*/
|
|
5755
|
-
withOptions(options) {
|
|
5756
|
-
const client = new this.constructor({
|
|
5757
|
-
...this._options,
|
|
5758
|
-
environment: options.environment ? options.environment : undefined,
|
|
5759
|
-
baseURL: options.environment ? undefined : this.baseURL,
|
|
5760
|
-
maxRetries: this.maxRetries,
|
|
5761
|
-
timeout: this.timeout,
|
|
5762
|
-
logger: this.logger,
|
|
5763
|
-
logLevel: this.logLevel,
|
|
5764
|
-
fetch: this.fetch,
|
|
5765
|
-
fetchOptions: this.fetchOptions,
|
|
5766
|
-
bearerToken: this.bearerToken,
|
|
5767
|
-
...options,
|
|
5768
|
-
});
|
|
5769
|
-
return client;
|
|
5770
|
-
}
|
|
5771
|
-
defaultQuery() {
|
|
5772
|
-
return this._options.defaultQuery;
|
|
5773
|
-
}
|
|
5774
|
-
validateHeaders({ values, nulls }) {
|
|
5775
|
-
return;
|
|
5776
|
-
}
|
|
5777
|
-
async authHeaders(opts) {
|
|
5778
|
-
return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
|
|
5779
|
-
}
|
|
5780
|
-
/**
|
|
5781
|
-
* Basic re-implementation of `qs.stringify` for primitive types.
|
|
5782
|
-
*/
|
|
5783
|
-
stringifyQuery(query) {
|
|
5784
|
-
return Object.entries(query)
|
|
5785
|
-
.filter(([_, value]) => typeof value !== 'undefined')
|
|
5786
|
-
.map(([key, value]) => {
|
|
5787
|
-
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
5788
|
-
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
5701
|
+
var left = data.length - i;
|
|
5702
|
+
if (left > 0) {
|
|
5703
|
+
var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
|
|
5704
|
+
out += this._encodeByte((c >>> 3 * 6) & 63);
|
|
5705
|
+
out += this._encodeByte((c >>> 2 * 6) & 63);
|
|
5706
|
+
if (left === 2) {
|
|
5707
|
+
out += this._encodeByte((c >>> 1 * 6) & 63);
|
|
5789
5708
|
}
|
|
5790
|
-
|
|
5791
|
-
|
|
5709
|
+
else {
|
|
5710
|
+
out += this._paddingCharacter || "";
|
|
5792
5711
|
}
|
|
5793
|
-
|
|
5794
|
-
})
|
|
5795
|
-
.join('&');
|
|
5796
|
-
}
|
|
5797
|
-
getUserAgent() {
|
|
5798
|
-
return `${this.constructor.name}/JS ${VERSION}`;
|
|
5799
|
-
}
|
|
5800
|
-
defaultIdempotencyKey() {
|
|
5801
|
-
return `stainless-node-retry-${uuid4()}`;
|
|
5802
|
-
}
|
|
5803
|
-
makeStatusError(status, error, message, headers) {
|
|
5804
|
-
return APIError.generate(status, error, message, headers);
|
|
5805
|
-
}
|
|
5806
|
-
buildURL(path, query, defaultBaseURL) {
|
|
5807
|
-
const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
|
|
5808
|
-
const url = isAbsoluteURL(path) ?
|
|
5809
|
-
new URL(path)
|
|
5810
|
-
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
5811
|
-
const defaultQuery = this.defaultQuery();
|
|
5812
|
-
if (!isEmptyObj(defaultQuery)) {
|
|
5813
|
-
query = { ...defaultQuery, ...query };
|
|
5814
|
-
}
|
|
5815
|
-
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
|
5816
|
-
url.search = this.stringifyQuery(query);
|
|
5712
|
+
out += this._paddingCharacter || "";
|
|
5817
5713
|
}
|
|
5818
|
-
return
|
|
5819
|
-
}
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
async prepareOptions(options) { }
|
|
5824
|
-
/**
|
|
5825
|
-
* Used as a callback for mutating the given `RequestInit` object.
|
|
5826
|
-
*
|
|
5827
|
-
* This is useful for cases where you want to add certain headers based off of
|
|
5828
|
-
* the request properties, e.g. `method` or `url`.
|
|
5829
|
-
*/
|
|
5830
|
-
async prepareRequest(request, { url, options }) { }
|
|
5831
|
-
get(path, opts) {
|
|
5832
|
-
return this.methodRequest('get', path, opts);
|
|
5833
|
-
}
|
|
5834
|
-
post(path, opts) {
|
|
5835
|
-
return this.methodRequest('post', path, opts);
|
|
5836
|
-
}
|
|
5837
|
-
patch(path, opts) {
|
|
5838
|
-
return this.methodRequest('patch', path, opts);
|
|
5839
|
-
}
|
|
5840
|
-
put(path, opts) {
|
|
5841
|
-
return this.methodRequest('put', path, opts);
|
|
5842
|
-
}
|
|
5843
|
-
delete(path, opts) {
|
|
5844
|
-
return this.methodRequest('delete', path, opts);
|
|
5845
|
-
}
|
|
5846
|
-
methodRequest(method, path, opts) {
|
|
5847
|
-
return this.request(Promise.resolve(opts).then((opts) => {
|
|
5848
|
-
return { method, path, ...opts };
|
|
5849
|
-
}));
|
|
5850
|
-
}
|
|
5851
|
-
request(options, remainingRetries = null) {
|
|
5852
|
-
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
|
|
5853
|
-
}
|
|
5854
|
-
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
|
|
5855
|
-
const options = await optionsInput;
|
|
5856
|
-
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
5857
|
-
if (retriesRemaining == null) {
|
|
5858
|
-
retriesRemaining = maxRetries;
|
|
5714
|
+
return out;
|
|
5715
|
+
};
|
|
5716
|
+
Coder.prototype.maxDecodedLength = function (length) {
|
|
5717
|
+
if (!this._paddingCharacter) {
|
|
5718
|
+
return (length * 6 + 7) / 8 | 0;
|
|
5859
5719
|
}
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
const startTime = Date.now();
|
|
5869
|
-
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
|
|
5870
|
-
retryOfRequestLogID,
|
|
5871
|
-
method: options.method,
|
|
5872
|
-
url,
|
|
5873
|
-
options,
|
|
5874
|
-
headers: req.headers,
|
|
5875
|
-
}));
|
|
5876
|
-
if (options.signal?.aborted) {
|
|
5877
|
-
throw new APIUserAbortError();
|
|
5720
|
+
return length / 4 * 3 | 0;
|
|
5721
|
+
};
|
|
5722
|
+
Coder.prototype.decodedLength = function (s) {
|
|
5723
|
+
return this.maxDecodedLength(s.length - this._getPaddingLength(s));
|
|
5724
|
+
};
|
|
5725
|
+
Coder.prototype.decode = function (s) {
|
|
5726
|
+
if (s.length === 0) {
|
|
5727
|
+
return new Uint8Array(0);
|
|
5878
5728
|
}
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
|
|
5882
|
-
|
|
5883
|
-
|
|
5884
|
-
|
|
5885
|
-
|
|
5886
|
-
|
|
5887
|
-
|
|
5888
|
-
|
|
5889
|
-
|
|
5890
|
-
|
|
5891
|
-
|
|
5892
|
-
|
|
5893
|
-
|
|
5894
|
-
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
durationMs: headersTime - startTime,
|
|
5899
|
-
message: response.message,
|
|
5900
|
-
}));
|
|
5901
|
-
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
|
|
5902
|
-
}
|
|
5903
|
-
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
|
|
5904
|
-
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
|
|
5905
|
-
retryOfRequestLogID,
|
|
5906
|
-
url,
|
|
5907
|
-
durationMs: headersTime - startTime,
|
|
5908
|
-
message: response.message,
|
|
5909
|
-
}));
|
|
5910
|
-
if (isTimeout) {
|
|
5911
|
-
throw new APIConnectionTimeoutError();
|
|
5912
|
-
}
|
|
5913
|
-
throw new APIConnectionError({ cause: response });
|
|
5729
|
+
var paddingLength = this._getPaddingLength(s);
|
|
5730
|
+
var length = s.length - paddingLength;
|
|
5731
|
+
var out = new Uint8Array(this.maxDecodedLength(length));
|
|
5732
|
+
var op = 0;
|
|
5733
|
+
var i = 0;
|
|
5734
|
+
var haveBad = 0;
|
|
5735
|
+
var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
|
|
5736
|
+
for (; i < length - 4; i += 4) {
|
|
5737
|
+
v0 = this._decodeChar(s.charCodeAt(i + 0));
|
|
5738
|
+
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
5739
|
+
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
5740
|
+
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
5741
|
+
out[op++] = (v0 << 2) | (v1 >>> 4);
|
|
5742
|
+
out[op++] = (v1 << 4) | (v2 >>> 2);
|
|
5743
|
+
out[op++] = (v2 << 6) | v3;
|
|
5744
|
+
haveBad |= v0 & INVALID_BYTE;
|
|
5745
|
+
haveBad |= v1 & INVALID_BYTE;
|
|
5746
|
+
haveBad |= v2 & INVALID_BYTE;
|
|
5747
|
+
haveBad |= v3 & INVALID_BYTE;
|
|
5914
5748
|
}
|
|
5915
|
-
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
5920
|
-
|
|
5921
|
-
await CancelReadableStream(response.body);
|
|
5922
|
-
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
5923
|
-
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
5924
|
-
retryOfRequestLogID,
|
|
5925
|
-
url: response.url,
|
|
5926
|
-
status: response.status,
|
|
5927
|
-
headers: response.headers,
|
|
5928
|
-
durationMs: headersTime - startTime,
|
|
5929
|
-
}));
|
|
5930
|
-
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
|
|
5931
|
-
}
|
|
5932
|
-
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
|
|
5933
|
-
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
5934
|
-
const errText = await response.text().catch((err) => castToError(err).message);
|
|
5935
|
-
const errJSON = safeJSON(errText);
|
|
5936
|
-
const errMessage = errJSON ? undefined : errText;
|
|
5937
|
-
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
5938
|
-
retryOfRequestLogID,
|
|
5939
|
-
url: response.url,
|
|
5940
|
-
status: response.status,
|
|
5941
|
-
headers: response.headers,
|
|
5942
|
-
message: errMessage,
|
|
5943
|
-
durationMs: Date.now() - startTime,
|
|
5944
|
-
}));
|
|
5945
|
-
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
|
|
5946
|
-
throw err;
|
|
5749
|
+
if (i < length - 1) {
|
|
5750
|
+
v0 = this._decodeChar(s.charCodeAt(i));
|
|
5751
|
+
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
5752
|
+
out[op++] = (v0 << 2) | (v1 >>> 4);
|
|
5753
|
+
haveBad |= v0 & INVALID_BYTE;
|
|
5754
|
+
haveBad |= v1 & INVALID_BYTE;
|
|
5947
5755
|
}
|
|
5948
|
-
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
status: response.status,
|
|
5953
|
-
headers: response.headers,
|
|
5954
|
-
durationMs: headersTime - startTime,
|
|
5955
|
-
}));
|
|
5956
|
-
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
|
|
5957
|
-
}
|
|
5958
|
-
getAPIList(path, Page, opts) {
|
|
5959
|
-
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
5960
|
-
}
|
|
5961
|
-
requestAPIList(Page, options) {
|
|
5962
|
-
const request = this.makeRequest(options, null, undefined);
|
|
5963
|
-
return new PagePromise(this, request, Page);
|
|
5964
|
-
}
|
|
5965
|
-
async fetchWithTimeout(url, init, ms, controller) {
|
|
5966
|
-
const { signal, method, ...options } = init || {};
|
|
5967
|
-
if (signal)
|
|
5968
|
-
signal.addEventListener('abort', () => controller.abort());
|
|
5969
|
-
const timeout = setTimeout(() => controller.abort(), ms);
|
|
5970
|
-
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
|
|
5971
|
-
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
|
|
5972
|
-
const fetchOptions = {
|
|
5973
|
-
signal: controller.signal,
|
|
5974
|
-
...(isReadableBody ? { duplex: 'half' } : {}),
|
|
5975
|
-
method: 'GET',
|
|
5976
|
-
...options,
|
|
5977
|
-
};
|
|
5978
|
-
if (method) {
|
|
5979
|
-
// Custom methods like 'patch' need to be uppercased
|
|
5980
|
-
// See https://github.com/nodejs/undici/issues/2294
|
|
5981
|
-
fetchOptions.method = method.toUpperCase();
|
|
5756
|
+
if (i < length - 2) {
|
|
5757
|
+
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
5758
|
+
out[op++] = (v1 << 4) | (v2 >>> 2);
|
|
5759
|
+
haveBad |= v2 & INVALID_BYTE;
|
|
5982
5760
|
}
|
|
5983
|
-
|
|
5984
|
-
|
|
5985
|
-
|
|
5761
|
+
if (i < length - 3) {
|
|
5762
|
+
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
5763
|
+
out[op++] = (v2 << 6) | v3;
|
|
5764
|
+
haveBad |= v3 & INVALID_BYTE;
|
|
5986
5765
|
}
|
|
5987
|
-
|
|
5988
|
-
|
|
5766
|
+
if (haveBad !== 0) {
|
|
5767
|
+
throw new Error("Base64Coder: incorrect characters for decoding");
|
|
5989
5768
|
}
|
|
5990
|
-
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
|
|
5998
|
-
|
|
5999
|
-
|
|
6000
|
-
|
|
6001
|
-
|
|
6002
|
-
//
|
|
6003
|
-
|
|
6004
|
-
|
|
6005
|
-
//
|
|
6006
|
-
|
|
6007
|
-
|
|
6008
|
-
//
|
|
6009
|
-
if
|
|
6010
|
-
|
|
6011
|
-
|
|
6012
|
-
|
|
6013
|
-
|
|
6014
|
-
|
|
6015
|
-
//
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
|
|
6019
|
-
|
|
6020
|
-
|
|
6021
|
-
|
|
6022
|
-
|
|
6023
|
-
|
|
6024
|
-
|
|
6025
|
-
|
|
6026
|
-
|
|
6027
|
-
|
|
6028
|
-
|
|
5769
|
+
return out;
|
|
5770
|
+
};
|
|
5771
|
+
// Standard encoding have the following encoded/decoded ranges,
|
|
5772
|
+
// which we need to convert between.
|
|
5773
|
+
//
|
|
5774
|
+
// ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
|
|
5775
|
+
// Index: 0 - 25 26 - 51 52 - 61 62 63
|
|
5776
|
+
// ASCII: 65 - 90 97 - 122 48 - 57 43 47
|
|
5777
|
+
//
|
|
5778
|
+
// Encode 6 bits in b into a new character.
|
|
5779
|
+
Coder.prototype._encodeByte = function (b) {
|
|
5780
|
+
// Encoding uses constant time operations as follows:
|
|
5781
|
+
//
|
|
5782
|
+
// 1. Define comparison of A with B using (A - B) >>> 8:
|
|
5783
|
+
// if A > B, then result is positive integer
|
|
5784
|
+
// if A <= B, then result is 0
|
|
5785
|
+
//
|
|
5786
|
+
// 2. Define selection of C or 0 using bitwise AND: X & C:
|
|
5787
|
+
// if X == 0, then result is 0
|
|
5788
|
+
// if X != 0, then result is C
|
|
5789
|
+
//
|
|
5790
|
+
// 3. Start with the smallest comparison (b >= 0), which is always
|
|
5791
|
+
// true, so set the result to the starting ASCII value (65).
|
|
5792
|
+
//
|
|
5793
|
+
// 4. Continue comparing b to higher ASCII values, and selecting
|
|
5794
|
+
// zero if comparison isn't true, otherwise selecting a value
|
|
5795
|
+
// to add to result, which:
|
|
5796
|
+
//
|
|
5797
|
+
// a) undoes the previous addition
|
|
5798
|
+
// b) provides new value to add
|
|
5799
|
+
//
|
|
5800
|
+
var result = b;
|
|
5801
|
+
// b >= 0
|
|
5802
|
+
result += 65;
|
|
5803
|
+
// b > 25
|
|
5804
|
+
result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
|
|
5805
|
+
// b > 51
|
|
5806
|
+
result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
|
|
5807
|
+
// b > 61
|
|
5808
|
+
result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
|
|
5809
|
+
// b > 62
|
|
5810
|
+
result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
|
|
5811
|
+
return String.fromCharCode(result);
|
|
5812
|
+
};
|
|
5813
|
+
// Decode a character code into a byte.
|
|
5814
|
+
// Must return 256 if character is out of alphabet range.
|
|
5815
|
+
Coder.prototype._decodeChar = function (c) {
|
|
5816
|
+
// Decoding works similar to encoding: using the same comparison
|
|
5817
|
+
// function, but now it works on ranges: result is always incremented
|
|
5818
|
+
// by value, but this value becomes zero if the range is not
|
|
5819
|
+
// satisfied.
|
|
5820
|
+
//
|
|
5821
|
+
// Decoding starts with invalid value, 256, which is then
|
|
5822
|
+
// subtracted when the range is satisfied. If none of the ranges
|
|
5823
|
+
// apply, the function returns 256, which is then checked by
|
|
5824
|
+
// the caller to throw error.
|
|
5825
|
+
var result = INVALID_BYTE; // start with invalid character
|
|
5826
|
+
// c == 43 (c > 42 and c < 44)
|
|
5827
|
+
result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
|
|
5828
|
+
// c == 47 (c > 46 and c < 48)
|
|
5829
|
+
result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
|
|
5830
|
+
// c > 47 and c < 58
|
|
5831
|
+
result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
|
|
5832
|
+
// c > 64 and c < 91
|
|
5833
|
+
result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
|
|
5834
|
+
// c > 96 and c < 123
|
|
5835
|
+
result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
|
|
5836
|
+
return result;
|
|
5837
|
+
};
|
|
5838
|
+
Coder.prototype._getPaddingLength = function (s) {
|
|
5839
|
+
var paddingLength = 0;
|
|
5840
|
+
if (this._paddingCharacter) {
|
|
5841
|
+
for (var i = s.length - 1; i >= 0; i--) {
|
|
5842
|
+
if (s[i] !== this._paddingCharacter) {
|
|
5843
|
+
break;
|
|
5844
|
+
}
|
|
5845
|
+
paddingLength++;
|
|
6029
5846
|
}
|
|
6030
|
-
|
|
6031
|
-
|
|
5847
|
+
if (s.length < 4 || paddingLength > 2) {
|
|
5848
|
+
throw new Error("Base64Coder: incorrect padding");
|
|
6032
5849
|
}
|
|
6033
5850
|
}
|
|
6034
|
-
|
|
6035
|
-
|
|
6036
|
-
|
|
6037
|
-
|
|
6038
|
-
|
|
6039
|
-
|
|
6040
|
-
|
|
6041
|
-
|
|
6042
|
-
}
|
|
6043
|
-
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
6044
|
-
const initialRetryDelay = 0.5;
|
|
6045
|
-
const maxRetryDelay = 8.0;
|
|
6046
|
-
const numRetries = maxRetries - retriesRemaining;
|
|
6047
|
-
// Apply exponential backoff, but not more than the max.
|
|
6048
|
-
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
|
6049
|
-
// Apply some jitter, take up to at most 25 percent of the retry time.
|
|
6050
|
-
const jitter = 1 - Math.random() * 0.25;
|
|
6051
|
-
return sleepSeconds * jitter * 1000;
|
|
6052
|
-
}
|
|
6053
|
-
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
|
|
6054
|
-
const options = { ...inputOptions };
|
|
6055
|
-
const { method, path, query, defaultBaseURL } = options;
|
|
6056
|
-
const url = this.buildURL(path, query, defaultBaseURL);
|
|
6057
|
-
if ('timeout' in options)
|
|
6058
|
-
validatePositiveInteger('timeout', options.timeout);
|
|
6059
|
-
options.timeout = options.timeout ?? this.timeout;
|
|
6060
|
-
const { bodyHeaders, body } = this.buildBody({ options });
|
|
6061
|
-
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
|
|
6062
|
-
const req = {
|
|
6063
|
-
method,
|
|
6064
|
-
headers: reqHeaders,
|
|
6065
|
-
...(options.signal && { signal: options.signal }),
|
|
6066
|
-
...(globalThis.ReadableStream &&
|
|
6067
|
-
body instanceof globalThis.ReadableStream && { duplex: 'half' }),
|
|
6068
|
-
...(body && { body }),
|
|
6069
|
-
...(this.fetchOptions ?? {}),
|
|
6070
|
-
...(options.fetchOptions ?? {}),
|
|
6071
|
-
};
|
|
6072
|
-
return { req, url, timeout: options.timeout };
|
|
6073
|
-
}
|
|
6074
|
-
async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
|
|
6075
|
-
let idempotencyHeaders = {};
|
|
6076
|
-
if (this.idempotencyHeader && method !== 'get') {
|
|
6077
|
-
if (!options.idempotencyKey)
|
|
6078
|
-
options.idempotencyKey = this.defaultIdempotencyKey();
|
|
6079
|
-
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
|
|
6080
|
-
}
|
|
6081
|
-
const headers = buildHeaders([
|
|
6082
|
-
idempotencyHeaders,
|
|
6083
|
-
{
|
|
6084
|
-
Accept: 'application/json',
|
|
6085
|
-
'User-Agent': this.getUserAgent(),
|
|
6086
|
-
'X-Stainless-Retry-Count': String(retryCount),
|
|
6087
|
-
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
|
|
6088
|
-
...getPlatformHeaders(),
|
|
6089
|
-
},
|
|
6090
|
-
await this.authHeaders(options),
|
|
6091
|
-
this._options.defaultHeaders,
|
|
6092
|
-
bodyHeaders,
|
|
6093
|
-
options.headers,
|
|
6094
|
-
]);
|
|
6095
|
-
this.validateHeaders(headers);
|
|
6096
|
-
return headers.values;
|
|
6097
|
-
}
|
|
6098
|
-
buildBody({ options: { body, headers: rawHeaders } }) {
|
|
6099
|
-
if (!body) {
|
|
6100
|
-
return { bodyHeaders: undefined, body: undefined };
|
|
6101
|
-
}
|
|
6102
|
-
const headers = buildHeaders([rawHeaders]);
|
|
6103
|
-
if (
|
|
6104
|
-
// Pass raw type verbatim
|
|
6105
|
-
ArrayBuffer.isView(body) ||
|
|
6106
|
-
body instanceof ArrayBuffer ||
|
|
6107
|
-
body instanceof DataView ||
|
|
6108
|
-
(typeof body === 'string' &&
|
|
6109
|
-
// Preserve legacy string encoding behavior for now
|
|
6110
|
-
headers.values.has('content-type')) ||
|
|
6111
|
-
// `Blob` is superset of `File`
|
|
6112
|
-
(globalThis.Blob && body instanceof globalThis.Blob) ||
|
|
6113
|
-
// `FormData` -> `multipart/form-data`
|
|
6114
|
-
body instanceof FormData ||
|
|
6115
|
-
// `URLSearchParams` -> `application/x-www-form-urlencoded`
|
|
6116
|
-
body instanceof URLSearchParams ||
|
|
6117
|
-
// Send chunked stream (each chunk has own `length`)
|
|
6118
|
-
(globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
|
|
6119
|
-
return { bodyHeaders: undefined, body: body };
|
|
6120
|
-
}
|
|
6121
|
-
else if (typeof body === 'object' &&
|
|
6122
|
-
(Symbol.asyncIterator in body ||
|
|
6123
|
-
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
|
|
6124
|
-
return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
|
|
6125
|
-
}
|
|
6126
|
-
else {
|
|
6127
|
-
return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
|
|
6128
|
-
}
|
|
6129
|
-
}
|
|
5851
|
+
return paddingLength;
|
|
5852
|
+
};
|
|
5853
|
+
return Coder;
|
|
5854
|
+
}());
|
|
5855
|
+
base64$1.Coder = Coder;
|
|
5856
|
+
var stdCoder = new Coder();
|
|
5857
|
+
function encode(data) {
|
|
5858
|
+
return stdCoder.encode(data);
|
|
6130
5859
|
}
|
|
6131
|
-
|
|
6132
|
-
|
|
6133
|
-
|
|
6134
|
-
|
|
6135
|
-
|
|
6136
|
-
|
|
6137
|
-
|
|
6138
|
-
|
|
6139
|
-
|
|
6140
|
-
|
|
6141
|
-
|
|
6142
|
-
|
|
6143
|
-
|
|
6144
|
-
|
|
6145
|
-
|
|
6146
|
-
DodoPayments.InternalServerError = InternalServerError;
|
|
6147
|
-
DodoPayments.PermissionDeniedError = PermissionDeniedError;
|
|
6148
|
-
DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
|
|
6149
|
-
DodoPayments.toFile = toFile;
|
|
6150
|
-
DodoPayments.CheckoutSessions = CheckoutSessions;
|
|
6151
|
-
DodoPayments.Payments = Payments;
|
|
6152
|
-
DodoPayments.Subscriptions = Subscriptions;
|
|
6153
|
-
DodoPayments.Invoices = Invoices;
|
|
6154
|
-
DodoPayments.Licenses = Licenses;
|
|
6155
|
-
DodoPayments.LicenseKeys = LicenseKeys;
|
|
6156
|
-
DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
|
|
6157
|
-
DodoPayments.Customers = Customers;
|
|
6158
|
-
DodoPayments.Refunds = Refunds;
|
|
6159
|
-
DodoPayments.Disputes = Disputes;
|
|
6160
|
-
DodoPayments.Payouts = Payouts;
|
|
6161
|
-
DodoPayments.WebhookEvents = WebhookEvents;
|
|
6162
|
-
DodoPayments.Products = Products;
|
|
6163
|
-
DodoPayments.Misc = Misc;
|
|
6164
|
-
DodoPayments.Discounts = Discounts;
|
|
6165
|
-
DodoPayments.Addons = Addons;
|
|
6166
|
-
DodoPayments.Brands = Brands;
|
|
6167
|
-
DodoPayments.Webhooks = Webhooks$1;
|
|
6168
|
-
DodoPayments.UsageEvents = UsageEvents;
|
|
6169
|
-
DodoPayments.Meters = Meters;
|
|
6170
|
-
|
|
6171
|
-
// src/checkout/checkout.ts
|
|
6172
|
-
var checkoutQuerySchema = objectType({
|
|
6173
|
-
productId: stringType(),
|
|
6174
|
-
quantity: stringType().optional(),
|
|
6175
|
-
// Customer fields
|
|
6176
|
-
fullName: stringType().optional(),
|
|
6177
|
-
firstName: stringType().optional(),
|
|
6178
|
-
lastName: stringType().optional(),
|
|
6179
|
-
email: stringType().optional(),
|
|
6180
|
-
country: stringType().optional(),
|
|
6181
|
-
addressLine: stringType().optional(),
|
|
6182
|
-
city: stringType().optional(),
|
|
6183
|
-
state: stringType().optional(),
|
|
6184
|
-
zipCode: stringType().optional(),
|
|
6185
|
-
// Disable flags
|
|
6186
|
-
disableFullName: stringType().optional(),
|
|
6187
|
-
disableFirstName: stringType().optional(),
|
|
6188
|
-
disableLastName: stringType().optional(),
|
|
6189
|
-
disableEmail: stringType().optional(),
|
|
6190
|
-
disableCountry: stringType().optional(),
|
|
6191
|
-
disableAddressLine: stringType().optional(),
|
|
6192
|
-
disableCity: stringType().optional(),
|
|
6193
|
-
disableState: stringType().optional(),
|
|
6194
|
-
disableZipCode: stringType().optional(),
|
|
6195
|
-
// Advanced controls
|
|
6196
|
-
paymentCurrency: stringType().optional(),
|
|
6197
|
-
showCurrencySelector: stringType().optional(),
|
|
6198
|
-
paymentAmount: stringType().optional(),
|
|
6199
|
-
showDiscounts: stringType().optional()
|
|
6200
|
-
// Metadata (allow any key starting with metadata_)
|
|
6201
|
-
// We'll handle metadata separately in the handler
|
|
6202
|
-
}).catchall(unknownType());
|
|
6203
|
-
var dynamicCheckoutBodySchema = objectType({
|
|
6204
|
-
// For subscription
|
|
6205
|
-
product_id: stringType().optional(),
|
|
6206
|
-
quantity: numberType().optional(),
|
|
6207
|
-
// For one-time payment
|
|
6208
|
-
product_cart: arrayType(
|
|
6209
|
-
objectType({
|
|
6210
|
-
product_id: stringType(),
|
|
6211
|
-
quantity: numberType()
|
|
6212
|
-
})
|
|
6213
|
-
).optional(),
|
|
6214
|
-
// Common fields
|
|
6215
|
-
billing: objectType({
|
|
6216
|
-
city: stringType(),
|
|
6217
|
-
country: stringType(),
|
|
6218
|
-
state: stringType(),
|
|
6219
|
-
street: stringType(),
|
|
6220
|
-
zipcode: stringType()
|
|
6221
|
-
}),
|
|
6222
|
-
customer: objectType({
|
|
6223
|
-
customer_id: stringType().optional(),
|
|
6224
|
-
email: stringType().optional(),
|
|
6225
|
-
name: stringType().optional()
|
|
6226
|
-
}),
|
|
6227
|
-
discount_id: stringType().optional(),
|
|
6228
|
-
addons: arrayType(
|
|
6229
|
-
objectType({
|
|
6230
|
-
addon_id: stringType(),
|
|
6231
|
-
quantity: numberType()
|
|
6232
|
-
})
|
|
6233
|
-
).optional(),
|
|
6234
|
-
metadata: recordType(stringType(), stringType()).optional(),
|
|
6235
|
-
currency: stringType().optional()
|
|
6236
|
-
// Allow any additional fields (for future compatibility)
|
|
6237
|
-
}).catchall(unknownType());
|
|
6238
|
-
var checkoutSessionProductCartItemSchema = objectType({
|
|
6239
|
-
product_id: stringType().min(1, "Product ID is required"),
|
|
6240
|
-
quantity: numberType().int().positive("Quantity must be a positive integer")
|
|
6241
|
-
});
|
|
6242
|
-
var checkoutSessionCustomerSchema = objectType({
|
|
6243
|
-
email: stringType().email().optional(),
|
|
6244
|
-
name: stringType().min(1).optional(),
|
|
6245
|
-
phone_number: stringType().optional()
|
|
6246
|
-
}).optional();
|
|
6247
|
-
var checkoutSessionBillingAddressSchema = objectType({
|
|
6248
|
-
street: stringType().optional(),
|
|
6249
|
-
city: stringType().optional(),
|
|
6250
|
-
state: stringType().optional(),
|
|
6251
|
-
country: stringType().length(2, "Country must be a 2-letter ISO code"),
|
|
6252
|
-
zipcode: stringType().optional()
|
|
6253
|
-
}).optional();
|
|
6254
|
-
var paymentMethodTypeSchema = enumType([
|
|
6255
|
-
"credit",
|
|
6256
|
-
"debit",
|
|
6257
|
-
"upi_collect",
|
|
6258
|
-
"upi_intent",
|
|
6259
|
-
"apple_pay",
|
|
6260
|
-
"google_pay",
|
|
6261
|
-
"amazon_pay",
|
|
6262
|
-
"klarna",
|
|
6263
|
-
"affirm",
|
|
6264
|
-
"afterpay_clearpay",
|
|
6265
|
-
"sepa",
|
|
6266
|
-
"ach"
|
|
6267
|
-
]);
|
|
6268
|
-
var checkoutSessionCustomizationSchema = objectType({
|
|
6269
|
-
theme: enumType(["light", "dark", "system"]).optional(),
|
|
6270
|
-
show_order_details: booleanType().optional(),
|
|
6271
|
-
show_on_demand_tag: booleanType().optional()
|
|
6272
|
-
}).optional();
|
|
6273
|
-
var checkoutSessionFeatureFlagsSchema = objectType({
|
|
6274
|
-
allow_currency_selection: booleanType().optional(),
|
|
6275
|
-
allow_discount_code: booleanType().optional(),
|
|
6276
|
-
allow_phone_number_collection: booleanType().optional(),
|
|
6277
|
-
allow_tax_id: booleanType().optional(),
|
|
6278
|
-
always_create_new_customer: booleanType().optional()
|
|
6279
|
-
}).optional();
|
|
6280
|
-
var checkoutSessionSubscriptionDataSchema = objectType({
|
|
6281
|
-
trial_period_days: numberType().int().nonnegative().optional()
|
|
6282
|
-
}).optional();
|
|
6283
|
-
var checkoutSessionPayloadSchema = objectType({
|
|
6284
|
-
// Required fields
|
|
6285
|
-
product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
|
|
6286
|
-
// Optional fields
|
|
6287
|
-
customer: checkoutSessionCustomerSchema,
|
|
6288
|
-
billing_address: checkoutSessionBillingAddressSchema,
|
|
6289
|
-
return_url: stringType().url().optional(),
|
|
6290
|
-
allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
|
|
6291
|
-
billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
|
|
6292
|
-
show_saved_payment_methods: booleanType().optional(),
|
|
6293
|
-
confirm: booleanType().optional(),
|
|
6294
|
-
discount_code: stringType().optional(),
|
|
6295
|
-
metadata: recordType(stringType(), stringType()).optional(),
|
|
6296
|
-
customization: checkoutSessionCustomizationSchema,
|
|
6297
|
-
feature_flags: checkoutSessionFeatureFlagsSchema,
|
|
6298
|
-
subscription_data: checkoutSessionSubscriptionDataSchema
|
|
6299
|
-
});
|
|
6300
|
-
var checkoutSessionResponseSchema = objectType({
|
|
6301
|
-
session_id: stringType().min(1, "Session ID is required"),
|
|
6302
|
-
checkout_url: stringType().url("Invalid checkout URL")
|
|
6303
|
-
});
|
|
6304
|
-
var createCheckoutSession = async (payload, config) => {
|
|
6305
|
-
const validation = checkoutSessionPayloadSchema.safeParse(payload);
|
|
6306
|
-
if (!validation.success) {
|
|
6307
|
-
throw new Error(
|
|
6308
|
-
`Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
|
|
6309
|
-
);
|
|
6310
|
-
}
|
|
6311
|
-
const dodopayments = new DodoPayments({
|
|
6312
|
-
bearerToken: config.bearerToken,
|
|
6313
|
-
environment: config.environment
|
|
6314
|
-
});
|
|
6315
|
-
try {
|
|
6316
|
-
const sdkPayload = {
|
|
6317
|
-
...validation.data,
|
|
6318
|
-
...validation.data.billing_address && {
|
|
6319
|
-
billing_address: {
|
|
6320
|
-
...validation.data.billing_address,
|
|
6321
|
-
country: validation.data.billing_address.country
|
|
6322
|
-
}
|
|
6323
|
-
}
|
|
6324
|
-
};
|
|
6325
|
-
const session = await dodopayments.checkoutSessions.create(
|
|
6326
|
-
sdkPayload
|
|
6327
|
-
);
|
|
6328
|
-
const responseValidation = checkoutSessionResponseSchema.safeParse(session);
|
|
6329
|
-
if (!responseValidation.success) {
|
|
6330
|
-
throw new Error(
|
|
6331
|
-
`Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
|
|
6332
|
-
);
|
|
6333
|
-
}
|
|
6334
|
-
return responseValidation.data;
|
|
6335
|
-
} catch (error) {
|
|
6336
|
-
if (error instanceof Error) {
|
|
6337
|
-
console.error("Dodo Payments Checkout Session API Error:", {
|
|
6338
|
-
message: error.message,
|
|
6339
|
-
payload: validation.data,
|
|
6340
|
-
config: {
|
|
6341
|
-
environment: config.environment,
|
|
6342
|
-
hasBearerToken: !!config.bearerToken
|
|
6343
|
-
}
|
|
6344
|
-
});
|
|
6345
|
-
throw new Error(`Failed to create checkout session: ${error.message}`);
|
|
5860
|
+
base64$1.encode = encode;
|
|
5861
|
+
function decode(s) {
|
|
5862
|
+
return stdCoder.decode(s);
|
|
5863
|
+
}
|
|
5864
|
+
base64$1.decode = decode;
|
|
5865
|
+
/**
|
|
5866
|
+
* Implements URL-safe Base64 encoding.
|
|
5867
|
+
* (Same as Base64, but '+' is replaced with '-', and '/' with '_').
|
|
5868
|
+
*
|
|
5869
|
+
* Operates in constant time.
|
|
5870
|
+
*/
|
|
5871
|
+
var URLSafeCoder = /** @class */ (function (_super) {
|
|
5872
|
+
__extends(URLSafeCoder, _super);
|
|
5873
|
+
function URLSafeCoder() {
|
|
5874
|
+
return _super !== null && _super.apply(this, arguments) || this;
|
|
6346
5875
|
}
|
|
6347
|
-
|
|
6348
|
-
|
|
6349
|
-
|
|
6350
|
-
|
|
6351
|
-
|
|
5876
|
+
// URL-safe encoding have the following encoded/decoded ranges:
|
|
5877
|
+
//
|
|
5878
|
+
// ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
|
|
5879
|
+
// Index: 0 - 25 26 - 51 52 - 61 62 63
|
|
5880
|
+
// ASCII: 65 - 90 97 - 122 48 - 57 45 95
|
|
5881
|
+
//
|
|
5882
|
+
URLSafeCoder.prototype._encodeByte = function (b) {
|
|
5883
|
+
var result = b;
|
|
5884
|
+
// b >= 0
|
|
5885
|
+
result += 65;
|
|
5886
|
+
// b > 25
|
|
5887
|
+
result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
|
|
5888
|
+
// b > 51
|
|
5889
|
+
result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
|
|
5890
|
+
// b > 61
|
|
5891
|
+
result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
|
|
5892
|
+
// b > 62
|
|
5893
|
+
result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
|
|
5894
|
+
return String.fromCharCode(result);
|
|
5895
|
+
};
|
|
5896
|
+
URLSafeCoder.prototype._decodeChar = function (c) {
|
|
5897
|
+
var result = INVALID_BYTE;
|
|
5898
|
+
// c == 45 (c > 44 and c < 46)
|
|
5899
|
+
result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
|
|
5900
|
+
// c == 95 (c > 94 and c < 96)
|
|
5901
|
+
result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
|
|
5902
|
+
// c > 47 and c < 58
|
|
5903
|
+
result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
|
|
5904
|
+
// c > 64 and c < 91
|
|
5905
|
+
result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
|
|
5906
|
+
// c > 96 and c < 123
|
|
5907
|
+
result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
|
|
5908
|
+
return result;
|
|
5909
|
+
};
|
|
5910
|
+
return URLSafeCoder;
|
|
5911
|
+
}(Coder));
|
|
5912
|
+
base64$1.URLSafeCoder = URLSafeCoder;
|
|
5913
|
+
var urlSafeCoder = new URLSafeCoder();
|
|
5914
|
+
function encodeURLSafe(data) {
|
|
5915
|
+
return urlSafeCoder.encode(data);
|
|
5916
|
+
}
|
|
5917
|
+
base64$1.encodeURLSafe = encodeURLSafe;
|
|
5918
|
+
function decodeURLSafe(s) {
|
|
5919
|
+
return urlSafeCoder.decode(s);
|
|
5920
|
+
}
|
|
5921
|
+
base64$1.decodeURLSafe = decodeURLSafe;
|
|
5922
|
+
base64$1.encodedLength = function (length) {
|
|
5923
|
+
return stdCoder.encodedLength(length);
|
|
6352
5924
|
};
|
|
6353
|
-
|
|
6354
|
-
|
|
6355
|
-
|
|
6356
|
-
|
|
6357
|
-
|
|
6358
|
-
bearerToken,
|
|
6359
|
-
environment,
|
|
6360
|
-
type = "static"
|
|
6361
|
-
}) => {
|
|
6362
|
-
if (type === "session") {
|
|
6363
|
-
if (!sessionPayload) {
|
|
6364
|
-
throw new Error("sessionPayload is required when type is 'session'");
|
|
6365
|
-
}
|
|
6366
|
-
const session = await createCheckoutSession(sessionPayload, {
|
|
6367
|
-
bearerToken,
|
|
6368
|
-
environment
|
|
6369
|
-
});
|
|
6370
|
-
return session.checkout_url;
|
|
6371
|
-
}
|
|
6372
|
-
const inputData = type === "dynamic" ? body : queryParams;
|
|
6373
|
-
let parseResult;
|
|
6374
|
-
if (type === "dynamic") {
|
|
6375
|
-
parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
|
|
6376
|
-
} else {
|
|
6377
|
-
parseResult = checkoutQuerySchema.safeParse(inputData);
|
|
6378
|
-
}
|
|
6379
|
-
const { success, data, error } = parseResult;
|
|
6380
|
-
if (!success) {
|
|
6381
|
-
throw new Error(
|
|
6382
|
-
`Invalid ${type === "dynamic" ? "body" : "query parameters"}.
|
|
6383
|
-
${error.message}`
|
|
6384
|
-
);
|
|
6385
|
-
}
|
|
6386
|
-
if (type !== "dynamic") {
|
|
6387
|
-
const {
|
|
6388
|
-
productId,
|
|
6389
|
-
quantity: quantity2,
|
|
6390
|
-
fullName,
|
|
6391
|
-
firstName,
|
|
6392
|
-
lastName,
|
|
6393
|
-
email,
|
|
6394
|
-
country,
|
|
6395
|
-
addressLine,
|
|
6396
|
-
city,
|
|
6397
|
-
state,
|
|
6398
|
-
zipCode,
|
|
6399
|
-
disableFullName,
|
|
6400
|
-
disableFirstName,
|
|
6401
|
-
disableLastName,
|
|
6402
|
-
disableEmail,
|
|
6403
|
-
disableCountry,
|
|
6404
|
-
disableAddressLine,
|
|
6405
|
-
disableCity,
|
|
6406
|
-
disableState,
|
|
6407
|
-
disableZipCode,
|
|
6408
|
-
paymentCurrency,
|
|
6409
|
-
showCurrencySelector,
|
|
6410
|
-
paymentAmount,
|
|
6411
|
-
showDiscounts
|
|
6412
|
-
// metadata handled below
|
|
6413
|
-
} = data;
|
|
6414
|
-
const dodopayments2 = new DodoPayments({
|
|
6415
|
-
bearerToken,
|
|
6416
|
-
environment
|
|
6417
|
-
});
|
|
6418
|
-
if (!productId) throw new Error("Missing required field: productId");
|
|
6419
|
-
try {
|
|
6420
|
-
await dodopayments2.products.retrieve(productId);
|
|
6421
|
-
} catch (err) {
|
|
6422
|
-
console.error(err);
|
|
6423
|
-
throw new Error("Product not found");
|
|
6424
|
-
}
|
|
6425
|
-
const url = new URL(
|
|
6426
|
-
`${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
|
|
6427
|
-
);
|
|
6428
|
-
url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
|
|
6429
|
-
if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
|
|
6430
|
-
if (fullName) url.searchParams.set("fullName", String(fullName));
|
|
6431
|
-
if (firstName) url.searchParams.set("firstName", String(firstName));
|
|
6432
|
-
if (lastName) url.searchParams.set("lastName", String(lastName));
|
|
6433
|
-
if (email) url.searchParams.set("email", String(email));
|
|
6434
|
-
if (country) url.searchParams.set("country", String(country));
|
|
6435
|
-
if (addressLine) url.searchParams.set("addressLine", String(addressLine));
|
|
6436
|
-
if (city) url.searchParams.set("city", String(city));
|
|
6437
|
-
if (state) url.searchParams.set("state", String(state));
|
|
6438
|
-
if (zipCode) url.searchParams.set("zipCode", String(zipCode));
|
|
6439
|
-
if (disableFullName === "true")
|
|
6440
|
-
url.searchParams.set("disableFullName", "true");
|
|
6441
|
-
if (disableFirstName === "true")
|
|
6442
|
-
url.searchParams.set("disableFirstName", "true");
|
|
6443
|
-
if (disableLastName === "true")
|
|
6444
|
-
url.searchParams.set("disableLastName", "true");
|
|
6445
|
-
if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
|
|
6446
|
-
if (disableCountry === "true")
|
|
6447
|
-
url.searchParams.set("disableCountry", "true");
|
|
6448
|
-
if (disableAddressLine === "true")
|
|
6449
|
-
url.searchParams.set("disableAddressLine", "true");
|
|
6450
|
-
if (disableCity === "true") url.searchParams.set("disableCity", "true");
|
|
6451
|
-
if (disableState === "true") url.searchParams.set("disableState", "true");
|
|
6452
|
-
if (disableZipCode === "true")
|
|
6453
|
-
url.searchParams.set("disableZipCode", "true");
|
|
6454
|
-
if (paymentCurrency)
|
|
6455
|
-
url.searchParams.set("paymentCurrency", String(paymentCurrency));
|
|
6456
|
-
if (showCurrencySelector)
|
|
6457
|
-
url.searchParams.set(
|
|
6458
|
-
"showCurrencySelector",
|
|
6459
|
-
String(showCurrencySelector)
|
|
6460
|
-
);
|
|
6461
|
-
if (paymentAmount)
|
|
6462
|
-
url.searchParams.set("paymentAmount", String(paymentAmount));
|
|
6463
|
-
if (showDiscounts)
|
|
6464
|
-
url.searchParams.set("showDiscounts", String(showDiscounts));
|
|
6465
|
-
for (const [key, value] of Object.entries(queryParams || {})) {
|
|
6466
|
-
if (key.startsWith("metadata_") && value && typeof value !== "object") {
|
|
6467
|
-
url.searchParams.set(key, String(value));
|
|
6468
|
-
}
|
|
6469
|
-
}
|
|
6470
|
-
return url.toString();
|
|
6471
|
-
}
|
|
6472
|
-
const dyn = data;
|
|
6473
|
-
const {
|
|
6474
|
-
product_id,
|
|
6475
|
-
product_cart,
|
|
6476
|
-
quantity,
|
|
6477
|
-
billing,
|
|
6478
|
-
customer,
|
|
6479
|
-
addons,
|
|
6480
|
-
metadata,
|
|
6481
|
-
allowed_payment_method_types,
|
|
6482
|
-
billing_currency,
|
|
6483
|
-
discount_code,
|
|
6484
|
-
on_demand,
|
|
6485
|
-
return_url: bodyReturnUrl,
|
|
6486
|
-
show_saved_payment_methods,
|
|
6487
|
-
tax_id,
|
|
6488
|
-
trial_period_days
|
|
6489
|
-
} = dyn;
|
|
6490
|
-
const dodopayments = new DodoPayments({
|
|
6491
|
-
bearerToken,
|
|
6492
|
-
environment
|
|
6493
|
-
});
|
|
6494
|
-
let isSubscription = false;
|
|
6495
|
-
let productIdToFetch = product_id;
|
|
6496
|
-
if (!product_id && product_cart && product_cart.length > 0) {
|
|
6497
|
-
productIdToFetch = product_cart[0].product_id;
|
|
6498
|
-
}
|
|
6499
|
-
if (!productIdToFetch)
|
|
6500
|
-
throw new Error(
|
|
6501
|
-
"Missing required field: product_id or product_cart[0].product_id"
|
|
6502
|
-
);
|
|
6503
|
-
let product;
|
|
6504
|
-
try {
|
|
6505
|
-
product = await dodopayments.products.retrieve(productIdToFetch);
|
|
6506
|
-
} catch (err) {
|
|
6507
|
-
console.error(err);
|
|
6508
|
-
throw new Error("Product not found");
|
|
6509
|
-
}
|
|
6510
|
-
isSubscription = Boolean(product.is_recurring);
|
|
6511
|
-
if (isSubscription && !product_id)
|
|
6512
|
-
throw new Error("Missing required field: product_id for subscription");
|
|
6513
|
-
if (!billing) throw new Error("Missing required field: billing");
|
|
6514
|
-
if (!customer) throw new Error("Missing required field: customer");
|
|
6515
|
-
if (isSubscription) {
|
|
6516
|
-
const subscriptionPayload = {
|
|
6517
|
-
billing,
|
|
6518
|
-
customer,
|
|
6519
|
-
product_id,
|
|
6520
|
-
quantity: quantity ? Number(quantity) : 1
|
|
6521
|
-
};
|
|
6522
|
-
if (metadata) subscriptionPayload.metadata = metadata;
|
|
6523
|
-
if (discount_code) subscriptionPayload.discount_code = discount_code;
|
|
6524
|
-
if (addons) subscriptionPayload.addons = addons;
|
|
6525
|
-
if (allowed_payment_method_types)
|
|
6526
|
-
subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
|
|
6527
|
-
if (billing_currency)
|
|
6528
|
-
subscriptionPayload.billing_currency = billing_currency;
|
|
6529
|
-
if (on_demand) subscriptionPayload.on_demand = on_demand;
|
|
6530
|
-
subscriptionPayload.payment_link = true;
|
|
6531
|
-
if (bodyReturnUrl) {
|
|
6532
|
-
subscriptionPayload.return_url = bodyReturnUrl;
|
|
6533
|
-
} else if (returnUrl) {
|
|
6534
|
-
subscriptionPayload.return_url = returnUrl;
|
|
6535
|
-
}
|
|
6536
|
-
if (show_saved_payment_methods)
|
|
6537
|
-
subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
|
|
6538
|
-
if (tax_id) subscriptionPayload.tax_id = tax_id;
|
|
6539
|
-
if (trial_period_days)
|
|
6540
|
-
subscriptionPayload.trial_period_days = trial_period_days;
|
|
6541
|
-
let subscription;
|
|
6542
|
-
try {
|
|
6543
|
-
subscription = await dodopayments.subscriptions.create(subscriptionPayload);
|
|
6544
|
-
} catch (err) {
|
|
6545
|
-
console.error("Error when creating subscription", err);
|
|
6546
|
-
throw new Error(err instanceof Error ? err.message : String(err));
|
|
6547
|
-
}
|
|
6548
|
-
if (!subscription || !subscription.payment_link) {
|
|
6549
|
-
throw new Error(
|
|
6550
|
-
"No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
|
|
6551
|
-
);
|
|
6552
|
-
}
|
|
6553
|
-
return subscription.payment_link;
|
|
6554
|
-
} else {
|
|
6555
|
-
let cart = product_cart;
|
|
6556
|
-
if (!cart && product_id) {
|
|
6557
|
-
cart = [
|
|
6558
|
-
{ product_id, quantity: quantity ? Number(quantity) : 1 }
|
|
6559
|
-
];
|
|
6560
|
-
}
|
|
6561
|
-
if (!cart || cart.length === 0)
|
|
6562
|
-
throw new Error("Missing required field: product_cart or product_id");
|
|
6563
|
-
const paymentPayload = {
|
|
6564
|
-
billing,
|
|
6565
|
-
customer,
|
|
6566
|
-
product_cart: cart
|
|
6567
|
-
};
|
|
6568
|
-
if (metadata) paymentPayload.metadata = metadata;
|
|
6569
|
-
paymentPayload.payment_link = true;
|
|
6570
|
-
if (allowed_payment_method_types)
|
|
6571
|
-
paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
|
|
6572
|
-
if (billing_currency) paymentPayload.billing_currency = billing_currency;
|
|
6573
|
-
if (discount_code) paymentPayload.discount_code = discount_code;
|
|
6574
|
-
if (bodyReturnUrl) {
|
|
6575
|
-
paymentPayload.return_url = bodyReturnUrl;
|
|
6576
|
-
} else if (returnUrl) {
|
|
6577
|
-
paymentPayload.return_url = returnUrl;
|
|
6578
|
-
}
|
|
6579
|
-
if (show_saved_payment_methods)
|
|
6580
|
-
paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
|
|
6581
|
-
if (tax_id) paymentPayload.tax_id = tax_id;
|
|
6582
|
-
let payment;
|
|
6583
|
-
try {
|
|
6584
|
-
payment = await dodopayments.payments.create(paymentPayload);
|
|
6585
|
-
} catch (err) {
|
|
6586
|
-
console.error("Error when creating payment link", err);
|
|
6587
|
-
throw new Error(err instanceof Error ? err.message : String(err));
|
|
6588
|
-
}
|
|
6589
|
-
if (!payment || !payment.payment_link) {
|
|
6590
|
-
throw new Error(
|
|
6591
|
-
"No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
|
|
6592
|
-
);
|
|
6593
|
-
}
|
|
6594
|
-
return payment.payment_link;
|
|
6595
|
-
}
|
|
5925
|
+
base64$1.maxDecodedLength = function (length) {
|
|
5926
|
+
return stdCoder.maxDecodedLength(length);
|
|
5927
|
+
};
|
|
5928
|
+
base64$1.decodedLength = function (s) {
|
|
5929
|
+
return stdCoder.decodedLength(s);
|
|
6596
5930
|
};
|
|
6597
5931
|
|
|
6598
|
-
|
|
6599
|
-
const getHandler = async ({ request }) => {
|
|
6600
|
-
const { searchParams } = new URL(request.url);
|
|
6601
|
-
const queryParams = Object.fromEntries(searchParams);
|
|
6602
|
-
if (!queryParams.productId) {
|
|
6603
|
-
return new Response("Please provide productId query parameter", {
|
|
6604
|
-
status: 400,
|
|
6605
|
-
});
|
|
6606
|
-
}
|
|
6607
|
-
const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
|
|
6608
|
-
if (!success) {
|
|
6609
|
-
if (error.errors.some((e) => e.path.toString() === "productId")) {
|
|
6610
|
-
return new Response("Please provide productId query parameter", {
|
|
6611
|
-
status: 400,
|
|
6612
|
-
});
|
|
6613
|
-
}
|
|
6614
|
-
return new Response(`Invalid query parameters.\n ${error.message}`, {
|
|
6615
|
-
status: 400,
|
|
6616
|
-
});
|
|
6617
|
-
}
|
|
6618
|
-
let url = "";
|
|
6619
|
-
try {
|
|
6620
|
-
url = await buildCheckoutUrl({ queryParams: data, ...config });
|
|
6621
|
-
}
|
|
6622
|
-
catch (error) {
|
|
6623
|
-
return new Response(error.message, { status: 400 });
|
|
6624
|
-
}
|
|
6625
|
-
return Response.json({ checkout_url: url });
|
|
6626
|
-
};
|
|
6627
|
-
const postHandler = async ({ request }) => {
|
|
6628
|
-
let body;
|
|
6629
|
-
try {
|
|
6630
|
-
body = await request.json();
|
|
6631
|
-
}
|
|
6632
|
-
catch (e) {
|
|
6633
|
-
return new Response("Invalid JSON body", { status: 400 });
|
|
6634
|
-
}
|
|
6635
|
-
if (config.type === "dynamic") {
|
|
6636
|
-
// Handle dynamic checkout
|
|
6637
|
-
const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
|
|
6638
|
-
if (!success) {
|
|
6639
|
-
return new Response(`Invalid request body.\n ${error.message}`, {
|
|
6640
|
-
status: 400,
|
|
6641
|
-
});
|
|
6642
|
-
}
|
|
6643
|
-
let url = "";
|
|
6644
|
-
try {
|
|
6645
|
-
url = await buildCheckoutUrl({
|
|
6646
|
-
body: data,
|
|
6647
|
-
...config,
|
|
6648
|
-
type: "dynamic",
|
|
6649
|
-
});
|
|
6650
|
-
}
|
|
6651
|
-
catch (error) {
|
|
6652
|
-
return new Response(error.message, { status: 400 });
|
|
6653
|
-
}
|
|
6654
|
-
return Response.json({ checkout_url: url });
|
|
6655
|
-
}
|
|
6656
|
-
else {
|
|
6657
|
-
// Handle checkout session
|
|
6658
|
-
const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
|
|
6659
|
-
if (!success) {
|
|
6660
|
-
return new Response(`Invalid checkout session payload.\n ${error.message}`, {
|
|
6661
|
-
status: 400,
|
|
6662
|
-
});
|
|
6663
|
-
}
|
|
6664
|
-
let url = "";
|
|
6665
|
-
try {
|
|
6666
|
-
url = await buildCheckoutUrl({
|
|
6667
|
-
sessionPayload: data,
|
|
6668
|
-
...config,
|
|
6669
|
-
type: "session",
|
|
6670
|
-
});
|
|
6671
|
-
}
|
|
6672
|
-
catch (error) {
|
|
6673
|
-
return new Response(error.message, { status: 400 });
|
|
6674
|
-
}
|
|
6675
|
-
return Response.json({ checkout_url: url });
|
|
6676
|
-
}
|
|
6677
|
-
};
|
|
6678
|
-
return (context) => {
|
|
6679
|
-
if (context.request.method === "POST") {
|
|
6680
|
-
return postHandler(context);
|
|
6681
|
-
}
|
|
6682
|
-
return getHandler(context);
|
|
6683
|
-
};
|
|
6684
|
-
};
|
|
6685
|
-
|
|
6686
|
-
const CustomerPortal = ({ bearerToken, environment, }) => {
|
|
6687
|
-
const getHandler = async ({ request }) => {
|
|
6688
|
-
const { searchParams } = new URL(request.url);
|
|
6689
|
-
const customerId = searchParams.get("customer_id");
|
|
6690
|
-
const params = {
|
|
6691
|
-
send_email: false,
|
|
6692
|
-
};
|
|
6693
|
-
const sendEmail = Boolean(searchParams.get("send_email"));
|
|
6694
|
-
if (sendEmail) {
|
|
6695
|
-
params.send_email = sendEmail;
|
|
6696
|
-
}
|
|
6697
|
-
if (!customerId) {
|
|
6698
|
-
return new Response("Missing customerId in query parameters", {
|
|
6699
|
-
status: 400,
|
|
6700
|
-
});
|
|
6701
|
-
}
|
|
6702
|
-
const dodopayments = new DodoPayments({
|
|
6703
|
-
bearerToken,
|
|
6704
|
-
environment,
|
|
6705
|
-
});
|
|
6706
|
-
try {
|
|
6707
|
-
const session = await dodopayments.customers.customerPortal.create(customerId, params);
|
|
6708
|
-
return Response.redirect(session.link, 307);
|
|
6709
|
-
}
|
|
6710
|
-
catch (error) {
|
|
6711
|
-
console.error("Error creating customer portal session:", error);
|
|
6712
|
-
return new Response(`Failed to create customer portal session: ${error.message}`, {
|
|
6713
|
-
status: 500,
|
|
6714
|
-
});
|
|
6715
|
-
}
|
|
6716
|
-
};
|
|
6717
|
-
return getHandler;
|
|
6718
|
-
};
|
|
6719
|
-
|
|
6720
|
-
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
6721
|
-
|
|
6722
|
-
var dist = {};
|
|
6723
|
-
|
|
6724
|
-
var timing_safe_equal = {};
|
|
6725
|
-
|
|
6726
|
-
Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
|
|
6727
|
-
timing_safe_equal.timingSafeEqual = void 0;
|
|
6728
|
-
function assert(expr, msg = "") {
|
|
6729
|
-
if (!expr) {
|
|
6730
|
-
throw new Error(msg);
|
|
6731
|
-
}
|
|
6732
|
-
}
|
|
6733
|
-
function timingSafeEqual(a, b) {
|
|
6734
|
-
if (a.byteLength !== b.byteLength) {
|
|
6735
|
-
return false;
|
|
6736
|
-
}
|
|
6737
|
-
if (!(a instanceof DataView)) {
|
|
6738
|
-
a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
|
|
6739
|
-
}
|
|
6740
|
-
if (!(b instanceof DataView)) {
|
|
6741
|
-
b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
|
|
6742
|
-
}
|
|
6743
|
-
assert(a instanceof DataView);
|
|
6744
|
-
assert(b instanceof DataView);
|
|
6745
|
-
const length = a.byteLength;
|
|
6746
|
-
let out = 0;
|
|
6747
|
-
let i = -1;
|
|
6748
|
-
while (++i < length) {
|
|
6749
|
-
out |= a.getUint8(i) ^ b.getUint8(i);
|
|
6750
|
-
}
|
|
6751
|
-
return out === 0;
|
|
6752
|
-
}
|
|
6753
|
-
timing_safe_equal.timingSafeEqual = timingSafeEqual;
|
|
6754
|
-
|
|
6755
|
-
var base64$1 = {};
|
|
6756
|
-
|
|
6757
|
-
// Copyright (C) 2016 Dmitry Chestnykh
|
|
6758
|
-
// MIT License. See LICENSE file for details.
|
|
6759
|
-
var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
|
|
6760
|
-
var extendStatics = function (d, b) {
|
|
6761
|
-
extendStatics = Object.setPrototypeOf ||
|
|
6762
|
-
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
|
6763
|
-
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
|
6764
|
-
return extendStatics(d, b);
|
|
6765
|
-
};
|
|
6766
|
-
return function (d, b) {
|
|
6767
|
-
extendStatics(d, b);
|
|
6768
|
-
function __() { this.constructor = d; }
|
|
6769
|
-
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
6770
|
-
};
|
|
6771
|
-
})();
|
|
6772
|
-
Object.defineProperty(base64$1, "__esModule", { value: true });
|
|
6773
|
-
/**
|
|
6774
|
-
* Package base64 implements Base64 encoding and decoding.
|
|
6775
|
-
*/
|
|
6776
|
-
// Invalid character used in decoding to indicate
|
|
6777
|
-
// that the character to decode is out of range of
|
|
6778
|
-
// alphabet and cannot be decoded.
|
|
6779
|
-
var INVALID_BYTE = 256;
|
|
6780
|
-
/**
|
|
6781
|
-
* Implements standard Base64 encoding.
|
|
6782
|
-
*
|
|
6783
|
-
* Operates in constant time.
|
|
6784
|
-
*/
|
|
6785
|
-
var Coder = /** @class */ (function () {
|
|
6786
|
-
// TODO(dchest): methods to encode chunk-by-chunk.
|
|
6787
|
-
function Coder(_paddingCharacter) {
|
|
6788
|
-
if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
|
|
6789
|
-
this._paddingCharacter = _paddingCharacter;
|
|
6790
|
-
}
|
|
6791
|
-
Coder.prototype.encodedLength = function (length) {
|
|
6792
|
-
if (!this._paddingCharacter) {
|
|
6793
|
-
return (length * 8 + 5) / 6 | 0;
|
|
6794
|
-
}
|
|
6795
|
-
return (length + 2) / 3 * 4 | 0;
|
|
6796
|
-
};
|
|
6797
|
-
Coder.prototype.encode = function (data) {
|
|
6798
|
-
var out = "";
|
|
6799
|
-
var i = 0;
|
|
6800
|
-
for (; i < data.length - 2; i += 3) {
|
|
6801
|
-
var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
|
|
6802
|
-
out += this._encodeByte((c >>> 3 * 6) & 63);
|
|
6803
|
-
out += this._encodeByte((c >>> 2 * 6) & 63);
|
|
6804
|
-
out += this._encodeByte((c >>> 1 * 6) & 63);
|
|
6805
|
-
out += this._encodeByte((c >>> 0 * 6) & 63);
|
|
6806
|
-
}
|
|
6807
|
-
var left = data.length - i;
|
|
6808
|
-
if (left > 0) {
|
|
6809
|
-
var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
|
|
6810
|
-
out += this._encodeByte((c >>> 3 * 6) & 63);
|
|
6811
|
-
out += this._encodeByte((c >>> 2 * 6) & 63);
|
|
6812
|
-
if (left === 2) {
|
|
6813
|
-
out += this._encodeByte((c >>> 1 * 6) & 63);
|
|
6814
|
-
}
|
|
6815
|
-
else {
|
|
6816
|
-
out += this._paddingCharacter || "";
|
|
6817
|
-
}
|
|
6818
|
-
out += this._paddingCharacter || "";
|
|
6819
|
-
}
|
|
6820
|
-
return out;
|
|
6821
|
-
};
|
|
6822
|
-
Coder.prototype.maxDecodedLength = function (length) {
|
|
6823
|
-
if (!this._paddingCharacter) {
|
|
6824
|
-
return (length * 6 + 7) / 8 | 0;
|
|
6825
|
-
}
|
|
6826
|
-
return length / 4 * 3 | 0;
|
|
6827
|
-
};
|
|
6828
|
-
Coder.prototype.decodedLength = function (s) {
|
|
6829
|
-
return this.maxDecodedLength(s.length - this._getPaddingLength(s));
|
|
6830
|
-
};
|
|
6831
|
-
Coder.prototype.decode = function (s) {
|
|
6832
|
-
if (s.length === 0) {
|
|
6833
|
-
return new Uint8Array(0);
|
|
6834
|
-
}
|
|
6835
|
-
var paddingLength = this._getPaddingLength(s);
|
|
6836
|
-
var length = s.length - paddingLength;
|
|
6837
|
-
var out = new Uint8Array(this.maxDecodedLength(length));
|
|
6838
|
-
var op = 0;
|
|
6839
|
-
var i = 0;
|
|
6840
|
-
var haveBad = 0;
|
|
6841
|
-
var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
|
|
6842
|
-
for (; i < length - 4; i += 4) {
|
|
6843
|
-
v0 = this._decodeChar(s.charCodeAt(i + 0));
|
|
6844
|
-
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
6845
|
-
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
6846
|
-
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
6847
|
-
out[op++] = (v0 << 2) | (v1 >>> 4);
|
|
6848
|
-
out[op++] = (v1 << 4) | (v2 >>> 2);
|
|
6849
|
-
out[op++] = (v2 << 6) | v3;
|
|
6850
|
-
haveBad |= v0 & INVALID_BYTE;
|
|
6851
|
-
haveBad |= v1 & INVALID_BYTE;
|
|
6852
|
-
haveBad |= v2 & INVALID_BYTE;
|
|
6853
|
-
haveBad |= v3 & INVALID_BYTE;
|
|
6854
|
-
}
|
|
6855
|
-
if (i < length - 1) {
|
|
6856
|
-
v0 = this._decodeChar(s.charCodeAt(i));
|
|
6857
|
-
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
6858
|
-
out[op++] = (v0 << 2) | (v1 >>> 4);
|
|
6859
|
-
haveBad |= v0 & INVALID_BYTE;
|
|
6860
|
-
haveBad |= v1 & INVALID_BYTE;
|
|
6861
|
-
}
|
|
6862
|
-
if (i < length - 2) {
|
|
6863
|
-
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
6864
|
-
out[op++] = (v1 << 4) | (v2 >>> 2);
|
|
6865
|
-
haveBad |= v2 & INVALID_BYTE;
|
|
6866
|
-
}
|
|
6867
|
-
if (i < length - 3) {
|
|
6868
|
-
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
6869
|
-
out[op++] = (v2 << 6) | v3;
|
|
6870
|
-
haveBad |= v3 & INVALID_BYTE;
|
|
6871
|
-
}
|
|
6872
|
-
if (haveBad !== 0) {
|
|
6873
|
-
throw new Error("Base64Coder: incorrect characters for decoding");
|
|
6874
|
-
}
|
|
6875
|
-
return out;
|
|
6876
|
-
};
|
|
6877
|
-
// Standard encoding have the following encoded/decoded ranges,
|
|
6878
|
-
// which we need to convert between.
|
|
6879
|
-
//
|
|
6880
|
-
// ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
|
|
6881
|
-
// Index: 0 - 25 26 - 51 52 - 61 62 63
|
|
6882
|
-
// ASCII: 65 - 90 97 - 122 48 - 57 43 47
|
|
6883
|
-
//
|
|
6884
|
-
// Encode 6 bits in b into a new character.
|
|
6885
|
-
Coder.prototype._encodeByte = function (b) {
|
|
6886
|
-
// Encoding uses constant time operations as follows:
|
|
6887
|
-
//
|
|
6888
|
-
// 1. Define comparison of A with B using (A - B) >>> 8:
|
|
6889
|
-
// if A > B, then result is positive integer
|
|
6890
|
-
// if A <= B, then result is 0
|
|
6891
|
-
//
|
|
6892
|
-
// 2. Define selection of C or 0 using bitwise AND: X & C:
|
|
6893
|
-
// if X == 0, then result is 0
|
|
6894
|
-
// if X != 0, then result is C
|
|
6895
|
-
//
|
|
6896
|
-
// 3. Start with the smallest comparison (b >= 0), which is always
|
|
6897
|
-
// true, so set the result to the starting ASCII value (65).
|
|
6898
|
-
//
|
|
6899
|
-
// 4. Continue comparing b to higher ASCII values, and selecting
|
|
6900
|
-
// zero if comparison isn't true, otherwise selecting a value
|
|
6901
|
-
// to add to result, which:
|
|
6902
|
-
//
|
|
6903
|
-
// a) undoes the previous addition
|
|
6904
|
-
// b) provides new value to add
|
|
6905
|
-
//
|
|
6906
|
-
var result = b;
|
|
6907
|
-
// b >= 0
|
|
6908
|
-
result += 65;
|
|
6909
|
-
// b > 25
|
|
6910
|
-
result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
|
|
6911
|
-
// b > 51
|
|
6912
|
-
result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
|
|
6913
|
-
// b > 61
|
|
6914
|
-
result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
|
|
6915
|
-
// b > 62
|
|
6916
|
-
result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
|
|
6917
|
-
return String.fromCharCode(result);
|
|
6918
|
-
};
|
|
6919
|
-
// Decode a character code into a byte.
|
|
6920
|
-
// Must return 256 if character is out of alphabet range.
|
|
6921
|
-
Coder.prototype._decodeChar = function (c) {
|
|
6922
|
-
// Decoding works similar to encoding: using the same comparison
|
|
6923
|
-
// function, but now it works on ranges: result is always incremented
|
|
6924
|
-
// by value, but this value becomes zero if the range is not
|
|
6925
|
-
// satisfied.
|
|
6926
|
-
//
|
|
6927
|
-
// Decoding starts with invalid value, 256, which is then
|
|
6928
|
-
// subtracted when the range is satisfied. If none of the ranges
|
|
6929
|
-
// apply, the function returns 256, which is then checked by
|
|
6930
|
-
// the caller to throw error.
|
|
6931
|
-
var result = INVALID_BYTE; // start with invalid character
|
|
6932
|
-
// c == 43 (c > 42 and c < 44)
|
|
6933
|
-
result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
|
|
6934
|
-
// c == 47 (c > 46 and c < 48)
|
|
6935
|
-
result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
|
|
6936
|
-
// c > 47 and c < 58
|
|
6937
|
-
result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
|
|
6938
|
-
// c > 64 and c < 91
|
|
6939
|
-
result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
|
|
6940
|
-
// c > 96 and c < 123
|
|
6941
|
-
result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
|
|
6942
|
-
return result;
|
|
6943
|
-
};
|
|
6944
|
-
Coder.prototype._getPaddingLength = function (s) {
|
|
6945
|
-
var paddingLength = 0;
|
|
6946
|
-
if (this._paddingCharacter) {
|
|
6947
|
-
for (var i = s.length - 1; i >= 0; i--) {
|
|
6948
|
-
if (s[i] !== this._paddingCharacter) {
|
|
6949
|
-
break;
|
|
6950
|
-
}
|
|
6951
|
-
paddingLength++;
|
|
6952
|
-
}
|
|
6953
|
-
if (s.length < 4 || paddingLength > 2) {
|
|
6954
|
-
throw new Error("Base64Coder: incorrect padding");
|
|
6955
|
-
}
|
|
6956
|
-
}
|
|
6957
|
-
return paddingLength;
|
|
6958
|
-
};
|
|
6959
|
-
return Coder;
|
|
6960
|
-
}());
|
|
6961
|
-
base64$1.Coder = Coder;
|
|
6962
|
-
var stdCoder = new Coder();
|
|
6963
|
-
function encode(data) {
|
|
6964
|
-
return stdCoder.encode(data);
|
|
6965
|
-
}
|
|
6966
|
-
base64$1.encode = encode;
|
|
6967
|
-
function decode(s) {
|
|
6968
|
-
return stdCoder.decode(s);
|
|
6969
|
-
}
|
|
6970
|
-
base64$1.decode = decode;
|
|
6971
|
-
/**
|
|
6972
|
-
* Implements URL-safe Base64 encoding.
|
|
6973
|
-
* (Same as Base64, but '+' is replaced with '-', and '/' with '_').
|
|
6974
|
-
*
|
|
6975
|
-
* Operates in constant time.
|
|
6976
|
-
*/
|
|
6977
|
-
var URLSafeCoder = /** @class */ (function (_super) {
|
|
6978
|
-
__extends(URLSafeCoder, _super);
|
|
6979
|
-
function URLSafeCoder() {
|
|
6980
|
-
return _super !== null && _super.apply(this, arguments) || this;
|
|
6981
|
-
}
|
|
6982
|
-
// URL-safe encoding have the following encoded/decoded ranges:
|
|
6983
|
-
//
|
|
6984
|
-
// ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
|
|
6985
|
-
// Index: 0 - 25 26 - 51 52 - 61 62 63
|
|
6986
|
-
// ASCII: 65 - 90 97 - 122 48 - 57 45 95
|
|
6987
|
-
//
|
|
6988
|
-
URLSafeCoder.prototype._encodeByte = function (b) {
|
|
6989
|
-
var result = b;
|
|
6990
|
-
// b >= 0
|
|
6991
|
-
result += 65;
|
|
6992
|
-
// b > 25
|
|
6993
|
-
result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
|
|
6994
|
-
// b > 51
|
|
6995
|
-
result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
|
|
6996
|
-
// b > 61
|
|
6997
|
-
result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
|
|
6998
|
-
// b > 62
|
|
6999
|
-
result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
|
|
7000
|
-
return String.fromCharCode(result);
|
|
7001
|
-
};
|
|
7002
|
-
URLSafeCoder.prototype._decodeChar = function (c) {
|
|
7003
|
-
var result = INVALID_BYTE;
|
|
7004
|
-
// c == 45 (c > 44 and c < 46)
|
|
7005
|
-
result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
|
|
7006
|
-
// c == 95 (c > 94 and c < 96)
|
|
7007
|
-
result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
|
|
7008
|
-
// c > 47 and c < 58
|
|
7009
|
-
result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
|
|
7010
|
-
// c > 64 and c < 91
|
|
7011
|
-
result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
|
|
7012
|
-
// c > 96 and c < 123
|
|
7013
|
-
result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
|
|
7014
|
-
return result;
|
|
7015
|
-
};
|
|
7016
|
-
return URLSafeCoder;
|
|
7017
|
-
}(Coder));
|
|
7018
|
-
base64$1.URLSafeCoder = URLSafeCoder;
|
|
7019
|
-
var urlSafeCoder = new URLSafeCoder();
|
|
7020
|
-
function encodeURLSafe(data) {
|
|
7021
|
-
return urlSafeCoder.encode(data);
|
|
7022
|
-
}
|
|
7023
|
-
base64$1.encodeURLSafe = encodeURLSafe;
|
|
7024
|
-
function decodeURLSafe(s) {
|
|
7025
|
-
return urlSafeCoder.decode(s);
|
|
7026
|
-
}
|
|
7027
|
-
base64$1.decodeURLSafe = decodeURLSafe;
|
|
7028
|
-
base64$1.encodedLength = function (length) {
|
|
7029
|
-
return stdCoder.encodedLength(length);
|
|
7030
|
-
};
|
|
7031
|
-
base64$1.maxDecodedLength = function (length) {
|
|
7032
|
-
return stdCoder.maxDecodedLength(length);
|
|
7033
|
-
};
|
|
7034
|
-
base64$1.decodedLength = function (s) {
|
|
7035
|
-
return stdCoder.decodedLength(s);
|
|
7036
|
-
};
|
|
7037
|
-
|
|
7038
|
-
var sha256$1 = {exports: {}};
|
|
5932
|
+
var sha256$1 = {exports: {}};
|
|
7039
5933
|
|
|
7040
5934
|
(function (module) {
|
|
7041
5935
|
(function (root, factory) {
|
|
@@ -7477,96 +6371,1253 @@ class ExtendableError extends Error {
|
|
|
7477
6371
|
this.name = "ExtendableError";
|
|
7478
6372
|
this.stack = new Error(message).stack;
|
|
7479
6373
|
}
|
|
7480
|
-
}
|
|
7481
|
-
class WebhookVerificationError extends ExtendableError {
|
|
7482
|
-
constructor(message) {
|
|
7483
|
-
super(message);
|
|
7484
|
-
Object.setPrototypeOf(this, WebhookVerificationError.prototype);
|
|
7485
|
-
this.name = "WebhookVerificationError";
|
|
6374
|
+
}
|
|
6375
|
+
class WebhookVerificationError extends ExtendableError {
|
|
6376
|
+
constructor(message) {
|
|
6377
|
+
super(message);
|
|
6378
|
+
Object.setPrototypeOf(this, WebhookVerificationError.prototype);
|
|
6379
|
+
this.name = "WebhookVerificationError";
|
|
6380
|
+
}
|
|
6381
|
+
}
|
|
6382
|
+
var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
|
|
6383
|
+
class Webhook {
|
|
6384
|
+
constructor(secret, options) {
|
|
6385
|
+
if (!secret) {
|
|
6386
|
+
throw new Error("Secret can't be empty.");
|
|
6387
|
+
}
|
|
6388
|
+
if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
|
|
6389
|
+
if (secret instanceof Uint8Array) {
|
|
6390
|
+
this.key = secret;
|
|
6391
|
+
}
|
|
6392
|
+
else {
|
|
6393
|
+
this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
|
|
6394
|
+
}
|
|
6395
|
+
}
|
|
6396
|
+
else {
|
|
6397
|
+
if (typeof secret !== "string") {
|
|
6398
|
+
throw new Error("Expected secret to be of type string");
|
|
6399
|
+
}
|
|
6400
|
+
if (secret.startsWith(Webhook.prefix)) {
|
|
6401
|
+
secret = secret.substring(Webhook.prefix.length);
|
|
6402
|
+
}
|
|
6403
|
+
this.key = base64.decode(secret);
|
|
6404
|
+
}
|
|
6405
|
+
}
|
|
6406
|
+
verify(payload, headers_) {
|
|
6407
|
+
const headers = {};
|
|
6408
|
+
for (const key of Object.keys(headers_)) {
|
|
6409
|
+
headers[key.toLowerCase()] = headers_[key];
|
|
6410
|
+
}
|
|
6411
|
+
const msgId = headers["webhook-id"];
|
|
6412
|
+
const msgSignature = headers["webhook-signature"];
|
|
6413
|
+
const msgTimestamp = headers["webhook-timestamp"];
|
|
6414
|
+
if (!msgSignature || !msgId || !msgTimestamp) {
|
|
6415
|
+
throw new WebhookVerificationError("Missing required headers");
|
|
6416
|
+
}
|
|
6417
|
+
const timestamp = this.verifyTimestamp(msgTimestamp);
|
|
6418
|
+
const computedSignature = this.sign(msgId, timestamp, payload);
|
|
6419
|
+
const expectedSignature = computedSignature.split(",")[1];
|
|
6420
|
+
const passedSignatures = msgSignature.split(" ");
|
|
6421
|
+
const encoder = new globalThis.TextEncoder();
|
|
6422
|
+
for (const versionedSignature of passedSignatures) {
|
|
6423
|
+
const [version, signature] = versionedSignature.split(",");
|
|
6424
|
+
if (version !== "v1") {
|
|
6425
|
+
continue;
|
|
6426
|
+
}
|
|
6427
|
+
if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
|
|
6428
|
+
return JSON.parse(payload.toString());
|
|
6429
|
+
}
|
|
6430
|
+
}
|
|
6431
|
+
throw new WebhookVerificationError("No matching signature found");
|
|
6432
|
+
}
|
|
6433
|
+
sign(msgId, timestamp, payload) {
|
|
6434
|
+
if (typeof payload === "string") ;
|
|
6435
|
+
else if (payload.constructor.name === "Buffer") {
|
|
6436
|
+
payload = payload.toString();
|
|
6437
|
+
}
|
|
6438
|
+
else {
|
|
6439
|
+
throw new Error("Expected payload to be of type string or Buffer.");
|
|
6440
|
+
}
|
|
6441
|
+
const encoder = new TextEncoder();
|
|
6442
|
+
const timestampNumber = Math.floor(timestamp.getTime() / 1000);
|
|
6443
|
+
const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
|
|
6444
|
+
const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
|
|
6445
|
+
return `v1,${expectedSignature}`;
|
|
6446
|
+
}
|
|
6447
|
+
verifyTimestamp(timestampHeader) {
|
|
6448
|
+
const now = Math.floor(Date.now() / 1000);
|
|
6449
|
+
const timestamp = parseInt(timestampHeader, 10);
|
|
6450
|
+
if (isNaN(timestamp)) {
|
|
6451
|
+
throw new WebhookVerificationError("Invalid Signature Headers");
|
|
6452
|
+
}
|
|
6453
|
+
if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
6454
|
+
throw new WebhookVerificationError("Message timestamp too old");
|
|
6455
|
+
}
|
|
6456
|
+
if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
6457
|
+
throw new WebhookVerificationError("Message timestamp too new");
|
|
6458
|
+
}
|
|
6459
|
+
return new Date(timestamp * 1000);
|
|
6460
|
+
}
|
|
6461
|
+
}
|
|
6462
|
+
Webhook_1 = dist.Webhook = Webhook;
|
|
6463
|
+
Webhook.prefix = "whsec_";
|
|
6464
|
+
|
|
6465
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
6466
|
+
let Webhooks$1 = class Webhooks extends APIResource {
|
|
6467
|
+
constructor() {
|
|
6468
|
+
super(...arguments);
|
|
6469
|
+
this.headers = new Headers$1(this._client);
|
|
6470
|
+
}
|
|
6471
|
+
/**
|
|
6472
|
+
* Create a new webhook
|
|
6473
|
+
*/
|
|
6474
|
+
create(body, options) {
|
|
6475
|
+
return this._client.post('/webhooks', { body, ...options });
|
|
6476
|
+
}
|
|
6477
|
+
/**
|
|
6478
|
+
* Get a webhook by id
|
|
6479
|
+
*/
|
|
6480
|
+
retrieve(webhookID, options) {
|
|
6481
|
+
return this._client.get(path `/webhooks/${webhookID}`, options);
|
|
6482
|
+
}
|
|
6483
|
+
/**
|
|
6484
|
+
* Patch a webhook by id
|
|
6485
|
+
*/
|
|
6486
|
+
update(webhookID, body, options) {
|
|
6487
|
+
return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
|
|
6488
|
+
}
|
|
6489
|
+
/**
|
|
6490
|
+
* List all webhooks
|
|
6491
|
+
*/
|
|
6492
|
+
list(query = {}, options) {
|
|
6493
|
+
return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
|
|
6494
|
+
}
|
|
6495
|
+
/**
|
|
6496
|
+
* Delete a webhook by id
|
|
6497
|
+
*/
|
|
6498
|
+
delete(webhookID, options) {
|
|
6499
|
+
return this._client.delete(path `/webhooks/${webhookID}`, {
|
|
6500
|
+
...options,
|
|
6501
|
+
headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
|
|
6502
|
+
});
|
|
6503
|
+
}
|
|
6504
|
+
/**
|
|
6505
|
+
* Get webhook secret by id
|
|
6506
|
+
*/
|
|
6507
|
+
retrieveSecret(webhookID, options) {
|
|
6508
|
+
return this._client.get(path `/webhooks/${webhookID}/secret`, options);
|
|
6509
|
+
}
|
|
6510
|
+
unsafeUnwrap(body) {
|
|
6511
|
+
return JSON.parse(body);
|
|
6512
|
+
}
|
|
6513
|
+
unwrap(body, { headers, key }) {
|
|
6514
|
+
if (headers !== undefined) {
|
|
6515
|
+
const keyStr = key === undefined ? this._client.webhookKey : key;
|
|
6516
|
+
if (keyStr === null)
|
|
6517
|
+
throw new Error('Webhook key must not be null in order to unwrap');
|
|
6518
|
+
const wh = new Webhook_1(keyStr);
|
|
6519
|
+
wh.verify(body, headers);
|
|
6520
|
+
}
|
|
6521
|
+
return JSON.parse(body);
|
|
6522
|
+
}
|
|
6523
|
+
};
|
|
6524
|
+
Webhooks$1.Headers = Headers$1;
|
|
6525
|
+
|
|
6526
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
6527
|
+
/**
|
|
6528
|
+
* Read an environment variable.
|
|
6529
|
+
*
|
|
6530
|
+
* Trims beginning and trailing whitespace.
|
|
6531
|
+
*
|
|
6532
|
+
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
|
6533
|
+
*/
|
|
6534
|
+
const readEnv = (env) => {
|
|
6535
|
+
if (typeof globalThis.process !== 'undefined') {
|
|
6536
|
+
return globalThis.process.env?.[env]?.trim() ?? undefined;
|
|
6537
|
+
}
|
|
6538
|
+
if (typeof globalThis.Deno !== 'undefined') {
|
|
6539
|
+
return globalThis.Deno.env?.get?.(env)?.trim();
|
|
6540
|
+
}
|
|
6541
|
+
return undefined;
|
|
6542
|
+
};
|
|
6543
|
+
|
|
6544
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
6545
|
+
var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
|
|
6546
|
+
const environments = {
|
|
6547
|
+
live_mode: 'https://live.dodopayments.com',
|
|
6548
|
+
test_mode: 'https://test.dodopayments.com',
|
|
6549
|
+
};
|
|
6550
|
+
/**
|
|
6551
|
+
* API Client for interfacing with the Dodo Payments API.
|
|
6552
|
+
*/
|
|
6553
|
+
class DodoPayments {
|
|
6554
|
+
/**
|
|
6555
|
+
* API Client for interfacing with the Dodo Payments API.
|
|
6556
|
+
*
|
|
6557
|
+
* @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
|
|
6558
|
+
* @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
|
|
6559
|
+
* @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
|
|
6560
|
+
* @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
|
|
6561
|
+
* @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
|
|
6562
|
+
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
|
|
6563
|
+
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
|
|
6564
|
+
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
|
|
6565
|
+
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
|
|
6566
|
+
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
6567
|
+
*/
|
|
6568
|
+
constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null, ...opts } = {}) {
|
|
6569
|
+
_DodoPayments_instances.add(this);
|
|
6570
|
+
_DodoPayments_encoder.set(this, void 0);
|
|
6571
|
+
this.checkoutSessions = new CheckoutSessions(this);
|
|
6572
|
+
this.payments = new Payments(this);
|
|
6573
|
+
this.subscriptions = new Subscriptions(this);
|
|
6574
|
+
this.invoices = new Invoices(this);
|
|
6575
|
+
this.licenses = new Licenses(this);
|
|
6576
|
+
this.licenseKeys = new LicenseKeys(this);
|
|
6577
|
+
this.licenseKeyInstances = new LicenseKeyInstances(this);
|
|
6578
|
+
this.customers = new Customers(this);
|
|
6579
|
+
this.refunds = new Refunds(this);
|
|
6580
|
+
this.disputes = new Disputes(this);
|
|
6581
|
+
this.payouts = new Payouts(this);
|
|
6582
|
+
this.products = new Products(this);
|
|
6583
|
+
this.misc = new Misc(this);
|
|
6584
|
+
this.discounts = new Discounts(this);
|
|
6585
|
+
this.addons = new Addons(this);
|
|
6586
|
+
this.brands = new Brands(this);
|
|
6587
|
+
this.webhooks = new Webhooks$1(this);
|
|
6588
|
+
this.webhookEvents = new WebhookEvents(this);
|
|
6589
|
+
this.usageEvents = new UsageEvents(this);
|
|
6590
|
+
this.meters = new Meters(this);
|
|
6591
|
+
if (bearerToken === undefined) {
|
|
6592
|
+
throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
|
|
6593
|
+
}
|
|
6594
|
+
const options = {
|
|
6595
|
+
bearerToken,
|
|
6596
|
+
webhookKey,
|
|
6597
|
+
...opts,
|
|
6598
|
+
baseURL,
|
|
6599
|
+
environment: opts.environment ?? 'live_mode',
|
|
6600
|
+
};
|
|
6601
|
+
if (baseURL && opts.environment) {
|
|
6602
|
+
throw new DodoPaymentsError('Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null');
|
|
6603
|
+
}
|
|
6604
|
+
this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
|
|
6605
|
+
this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
|
|
6606
|
+
this.logger = options.logger ?? console;
|
|
6607
|
+
const defaultLogLevel = 'warn';
|
|
6608
|
+
// Set default logLevel early so that we can log a warning in parseLogLevel.
|
|
6609
|
+
this.logLevel = defaultLogLevel;
|
|
6610
|
+
this.logLevel =
|
|
6611
|
+
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
|
|
6612
|
+
parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
|
|
6613
|
+
defaultLogLevel;
|
|
6614
|
+
this.fetchOptions = options.fetchOptions;
|
|
6615
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
6616
|
+
this.fetch = options.fetch ?? getDefaultFetch();
|
|
6617
|
+
__classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
|
|
6618
|
+
this._options = options;
|
|
6619
|
+
this.bearerToken = bearerToken;
|
|
6620
|
+
this.webhookKey = webhookKey;
|
|
6621
|
+
}
|
|
6622
|
+
/**
|
|
6623
|
+
* Create a new client instance re-using the same options given to the current client with optional overriding.
|
|
6624
|
+
*/
|
|
6625
|
+
withOptions(options) {
|
|
6626
|
+
const client = new this.constructor({
|
|
6627
|
+
...this._options,
|
|
6628
|
+
environment: options.environment ? options.environment : undefined,
|
|
6629
|
+
baseURL: options.environment ? undefined : this.baseURL,
|
|
6630
|
+
maxRetries: this.maxRetries,
|
|
6631
|
+
timeout: this.timeout,
|
|
6632
|
+
logger: this.logger,
|
|
6633
|
+
logLevel: this.logLevel,
|
|
6634
|
+
fetch: this.fetch,
|
|
6635
|
+
fetchOptions: this.fetchOptions,
|
|
6636
|
+
bearerToken: this.bearerToken,
|
|
6637
|
+
webhookKey: this.webhookKey,
|
|
6638
|
+
...options,
|
|
6639
|
+
});
|
|
6640
|
+
return client;
|
|
6641
|
+
}
|
|
6642
|
+
defaultQuery() {
|
|
6643
|
+
return this._options.defaultQuery;
|
|
6644
|
+
}
|
|
6645
|
+
validateHeaders({ values, nulls }) {
|
|
6646
|
+
return;
|
|
6647
|
+
}
|
|
6648
|
+
async authHeaders(opts) {
|
|
6649
|
+
return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
|
|
6650
|
+
}
|
|
6651
|
+
/**
|
|
6652
|
+
* Basic re-implementation of `qs.stringify` for primitive types.
|
|
6653
|
+
*/
|
|
6654
|
+
stringifyQuery(query) {
|
|
6655
|
+
return Object.entries(query)
|
|
6656
|
+
.filter(([_, value]) => typeof value !== 'undefined')
|
|
6657
|
+
.map(([key, value]) => {
|
|
6658
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
6659
|
+
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
6660
|
+
}
|
|
6661
|
+
if (value === null) {
|
|
6662
|
+
return `${encodeURIComponent(key)}=`;
|
|
6663
|
+
}
|
|
6664
|
+
throw new DodoPaymentsError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
|
|
6665
|
+
})
|
|
6666
|
+
.join('&');
|
|
6667
|
+
}
|
|
6668
|
+
getUserAgent() {
|
|
6669
|
+
return `${this.constructor.name}/JS ${VERSION}`;
|
|
6670
|
+
}
|
|
6671
|
+
defaultIdempotencyKey() {
|
|
6672
|
+
return `stainless-node-retry-${uuid4()}`;
|
|
6673
|
+
}
|
|
6674
|
+
makeStatusError(status, error, message, headers) {
|
|
6675
|
+
return APIError.generate(status, error, message, headers);
|
|
6676
|
+
}
|
|
6677
|
+
buildURL(path, query, defaultBaseURL) {
|
|
6678
|
+
const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
|
|
6679
|
+
const url = isAbsoluteURL(path) ?
|
|
6680
|
+
new URL(path)
|
|
6681
|
+
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
6682
|
+
const defaultQuery = this.defaultQuery();
|
|
6683
|
+
if (!isEmptyObj(defaultQuery)) {
|
|
6684
|
+
query = { ...defaultQuery, ...query };
|
|
6685
|
+
}
|
|
6686
|
+
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
|
6687
|
+
url.search = this.stringifyQuery(query);
|
|
6688
|
+
}
|
|
6689
|
+
return url.toString();
|
|
6690
|
+
}
|
|
6691
|
+
/**
|
|
6692
|
+
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
|
6693
|
+
*/
|
|
6694
|
+
async prepareOptions(options) { }
|
|
6695
|
+
/**
|
|
6696
|
+
* Used as a callback for mutating the given `RequestInit` object.
|
|
6697
|
+
*
|
|
6698
|
+
* This is useful for cases where you want to add certain headers based off of
|
|
6699
|
+
* the request properties, e.g. `method` or `url`.
|
|
6700
|
+
*/
|
|
6701
|
+
async prepareRequest(request, { url, options }) { }
|
|
6702
|
+
get(path, opts) {
|
|
6703
|
+
return this.methodRequest('get', path, opts);
|
|
6704
|
+
}
|
|
6705
|
+
post(path, opts) {
|
|
6706
|
+
return this.methodRequest('post', path, opts);
|
|
6707
|
+
}
|
|
6708
|
+
patch(path, opts) {
|
|
6709
|
+
return this.methodRequest('patch', path, opts);
|
|
6710
|
+
}
|
|
6711
|
+
put(path, opts) {
|
|
6712
|
+
return this.methodRequest('put', path, opts);
|
|
6713
|
+
}
|
|
6714
|
+
delete(path, opts) {
|
|
6715
|
+
return this.methodRequest('delete', path, opts);
|
|
6716
|
+
}
|
|
6717
|
+
methodRequest(method, path, opts) {
|
|
6718
|
+
return this.request(Promise.resolve(opts).then((opts) => {
|
|
6719
|
+
return { method, path, ...opts };
|
|
6720
|
+
}));
|
|
6721
|
+
}
|
|
6722
|
+
request(options, remainingRetries = null) {
|
|
6723
|
+
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
|
|
6724
|
+
}
|
|
6725
|
+
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
|
|
6726
|
+
const options = await optionsInput;
|
|
6727
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
6728
|
+
if (retriesRemaining == null) {
|
|
6729
|
+
retriesRemaining = maxRetries;
|
|
6730
|
+
}
|
|
6731
|
+
await this.prepareOptions(options);
|
|
6732
|
+
const { req, url, timeout } = await this.buildRequest(options, {
|
|
6733
|
+
retryCount: maxRetries - retriesRemaining,
|
|
6734
|
+
});
|
|
6735
|
+
await this.prepareRequest(req, { url, options });
|
|
6736
|
+
/** Not an API request ID, just for correlating local log entries. */
|
|
6737
|
+
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
|
|
6738
|
+
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
|
|
6739
|
+
const startTime = Date.now();
|
|
6740
|
+
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
|
|
6741
|
+
retryOfRequestLogID,
|
|
6742
|
+
method: options.method,
|
|
6743
|
+
url,
|
|
6744
|
+
options,
|
|
6745
|
+
headers: req.headers,
|
|
6746
|
+
}));
|
|
6747
|
+
if (options.signal?.aborted) {
|
|
6748
|
+
throw new APIUserAbortError();
|
|
6749
|
+
}
|
|
6750
|
+
const controller = new AbortController();
|
|
6751
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
|
6752
|
+
const headersTime = Date.now();
|
|
6753
|
+
if (response instanceof globalThis.Error) {
|
|
6754
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
6755
|
+
if (options.signal?.aborted) {
|
|
6756
|
+
throw new APIUserAbortError();
|
|
6757
|
+
}
|
|
6758
|
+
// detect native connection timeout errors
|
|
6759
|
+
// deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
|
|
6760
|
+
// undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
|
|
6761
|
+
// others do not provide enough information to distinguish timeouts from other connection errors
|
|
6762
|
+
const isTimeout = isAbortError(response) ||
|
|
6763
|
+
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
|
|
6764
|
+
if (retriesRemaining) {
|
|
6765
|
+
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
|
|
6766
|
+
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
|
|
6767
|
+
retryOfRequestLogID,
|
|
6768
|
+
url,
|
|
6769
|
+
durationMs: headersTime - startTime,
|
|
6770
|
+
message: response.message,
|
|
6771
|
+
}));
|
|
6772
|
+
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
|
|
6773
|
+
}
|
|
6774
|
+
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
|
|
6775
|
+
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
|
|
6776
|
+
retryOfRequestLogID,
|
|
6777
|
+
url,
|
|
6778
|
+
durationMs: headersTime - startTime,
|
|
6779
|
+
message: response.message,
|
|
6780
|
+
}));
|
|
6781
|
+
if (isTimeout) {
|
|
6782
|
+
throw new APIConnectionTimeoutError();
|
|
6783
|
+
}
|
|
6784
|
+
throw new APIConnectionError({ cause: response });
|
|
6785
|
+
}
|
|
6786
|
+
const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
|
|
6787
|
+
if (!response.ok) {
|
|
6788
|
+
const shouldRetry = await this.shouldRetry(response);
|
|
6789
|
+
if (retriesRemaining && shouldRetry) {
|
|
6790
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
6791
|
+
// We don't need the body of this response.
|
|
6792
|
+
await CancelReadableStream(response.body);
|
|
6793
|
+
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
6794
|
+
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
6795
|
+
retryOfRequestLogID,
|
|
6796
|
+
url: response.url,
|
|
6797
|
+
status: response.status,
|
|
6798
|
+
headers: response.headers,
|
|
6799
|
+
durationMs: headersTime - startTime,
|
|
6800
|
+
}));
|
|
6801
|
+
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
|
|
6802
|
+
}
|
|
6803
|
+
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
|
|
6804
|
+
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
6805
|
+
const errText = await response.text().catch((err) => castToError(err).message);
|
|
6806
|
+
const errJSON = safeJSON(errText);
|
|
6807
|
+
const errMessage = errJSON ? undefined : errText;
|
|
6808
|
+
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
6809
|
+
retryOfRequestLogID,
|
|
6810
|
+
url: response.url,
|
|
6811
|
+
status: response.status,
|
|
6812
|
+
headers: response.headers,
|
|
6813
|
+
message: errMessage,
|
|
6814
|
+
durationMs: Date.now() - startTime,
|
|
6815
|
+
}));
|
|
6816
|
+
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
|
|
6817
|
+
throw err;
|
|
6818
|
+
}
|
|
6819
|
+
loggerFor(this).info(responseInfo);
|
|
6820
|
+
loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
|
|
6821
|
+
retryOfRequestLogID,
|
|
6822
|
+
url: response.url,
|
|
6823
|
+
status: response.status,
|
|
6824
|
+
headers: response.headers,
|
|
6825
|
+
durationMs: headersTime - startTime,
|
|
6826
|
+
}));
|
|
6827
|
+
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
|
|
6828
|
+
}
|
|
6829
|
+
getAPIList(path, Page, opts) {
|
|
6830
|
+
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
6831
|
+
}
|
|
6832
|
+
requestAPIList(Page, options) {
|
|
6833
|
+
const request = this.makeRequest(options, null, undefined);
|
|
6834
|
+
return new PagePromise(this, request, Page);
|
|
6835
|
+
}
|
|
6836
|
+
async fetchWithTimeout(url, init, ms, controller) {
|
|
6837
|
+
const { signal, method, ...options } = init || {};
|
|
6838
|
+
if (signal)
|
|
6839
|
+
signal.addEventListener('abort', () => controller.abort());
|
|
6840
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
6841
|
+
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
|
|
6842
|
+
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
|
|
6843
|
+
const fetchOptions = {
|
|
6844
|
+
signal: controller.signal,
|
|
6845
|
+
...(isReadableBody ? { duplex: 'half' } : {}),
|
|
6846
|
+
method: 'GET',
|
|
6847
|
+
...options,
|
|
6848
|
+
};
|
|
6849
|
+
if (method) {
|
|
6850
|
+
// Custom methods like 'patch' need to be uppercased
|
|
6851
|
+
// See https://github.com/nodejs/undici/issues/2294
|
|
6852
|
+
fetchOptions.method = method.toUpperCase();
|
|
6853
|
+
}
|
|
6854
|
+
try {
|
|
6855
|
+
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
|
6856
|
+
return await this.fetch.call(undefined, url, fetchOptions);
|
|
6857
|
+
}
|
|
6858
|
+
finally {
|
|
6859
|
+
clearTimeout(timeout);
|
|
6860
|
+
}
|
|
6861
|
+
}
|
|
6862
|
+
async shouldRetry(response) {
|
|
6863
|
+
// Note this is not a standard header.
|
|
6864
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
6865
|
+
// If the server explicitly says whether or not to retry, obey.
|
|
6866
|
+
if (shouldRetryHeader === 'true')
|
|
6867
|
+
return true;
|
|
6868
|
+
if (shouldRetryHeader === 'false')
|
|
6869
|
+
return false;
|
|
6870
|
+
// Retry on request timeouts.
|
|
6871
|
+
if (response.status === 408)
|
|
6872
|
+
return true;
|
|
6873
|
+
// Retry on lock timeouts.
|
|
6874
|
+
if (response.status === 409)
|
|
6875
|
+
return true;
|
|
6876
|
+
// Retry on rate limits.
|
|
6877
|
+
if (response.status === 429)
|
|
6878
|
+
return true;
|
|
6879
|
+
// Retry internal errors.
|
|
6880
|
+
if (response.status >= 500)
|
|
6881
|
+
return true;
|
|
6882
|
+
return false;
|
|
6883
|
+
}
|
|
6884
|
+
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
|
|
6885
|
+
let timeoutMillis;
|
|
6886
|
+
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
|
6887
|
+
const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
|
|
6888
|
+
if (retryAfterMillisHeader) {
|
|
6889
|
+
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
|
6890
|
+
if (!Number.isNaN(timeoutMs)) {
|
|
6891
|
+
timeoutMillis = timeoutMs;
|
|
6892
|
+
}
|
|
6893
|
+
}
|
|
6894
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
6895
|
+
const retryAfterHeader = responseHeaders?.get('retry-after');
|
|
6896
|
+
if (retryAfterHeader && !timeoutMillis) {
|
|
6897
|
+
const timeoutSeconds = parseFloat(retryAfterHeader);
|
|
6898
|
+
if (!Number.isNaN(timeoutSeconds)) {
|
|
6899
|
+
timeoutMillis = timeoutSeconds * 1000;
|
|
6900
|
+
}
|
|
6901
|
+
else {
|
|
6902
|
+
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
|
6903
|
+
}
|
|
6904
|
+
}
|
|
6905
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
6906
|
+
// just do what it says, but otherwise calculate a default
|
|
6907
|
+
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
|
|
6908
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
6909
|
+
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
|
6910
|
+
}
|
|
6911
|
+
await sleep(timeoutMillis);
|
|
6912
|
+
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
|
|
6913
|
+
}
|
|
6914
|
+
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
6915
|
+
const initialRetryDelay = 0.5;
|
|
6916
|
+
const maxRetryDelay = 8.0;
|
|
6917
|
+
const numRetries = maxRetries - retriesRemaining;
|
|
6918
|
+
// Apply exponential backoff, but not more than the max.
|
|
6919
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
|
6920
|
+
// Apply some jitter, take up to at most 25 percent of the retry time.
|
|
6921
|
+
const jitter = 1 - Math.random() * 0.25;
|
|
6922
|
+
return sleepSeconds * jitter * 1000;
|
|
6923
|
+
}
|
|
6924
|
+
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
|
|
6925
|
+
const options = { ...inputOptions };
|
|
6926
|
+
const { method, path, query, defaultBaseURL } = options;
|
|
6927
|
+
const url = this.buildURL(path, query, defaultBaseURL);
|
|
6928
|
+
if ('timeout' in options)
|
|
6929
|
+
validatePositiveInteger('timeout', options.timeout);
|
|
6930
|
+
options.timeout = options.timeout ?? this.timeout;
|
|
6931
|
+
const { bodyHeaders, body } = this.buildBody({ options });
|
|
6932
|
+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
|
|
6933
|
+
const req = {
|
|
6934
|
+
method,
|
|
6935
|
+
headers: reqHeaders,
|
|
6936
|
+
...(options.signal && { signal: options.signal }),
|
|
6937
|
+
...(globalThis.ReadableStream &&
|
|
6938
|
+
body instanceof globalThis.ReadableStream && { duplex: 'half' }),
|
|
6939
|
+
...(body && { body }),
|
|
6940
|
+
...(this.fetchOptions ?? {}),
|
|
6941
|
+
...(options.fetchOptions ?? {}),
|
|
6942
|
+
};
|
|
6943
|
+
return { req, url, timeout: options.timeout };
|
|
6944
|
+
}
|
|
6945
|
+
async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
|
|
6946
|
+
let idempotencyHeaders = {};
|
|
6947
|
+
if (this.idempotencyHeader && method !== 'get') {
|
|
6948
|
+
if (!options.idempotencyKey)
|
|
6949
|
+
options.idempotencyKey = this.defaultIdempotencyKey();
|
|
6950
|
+
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
|
|
6951
|
+
}
|
|
6952
|
+
const headers = buildHeaders([
|
|
6953
|
+
idempotencyHeaders,
|
|
6954
|
+
{
|
|
6955
|
+
Accept: 'application/json',
|
|
6956
|
+
'User-Agent': this.getUserAgent(),
|
|
6957
|
+
'X-Stainless-Retry-Count': String(retryCount),
|
|
6958
|
+
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
|
|
6959
|
+
...getPlatformHeaders(),
|
|
6960
|
+
},
|
|
6961
|
+
await this.authHeaders(options),
|
|
6962
|
+
this._options.defaultHeaders,
|
|
6963
|
+
bodyHeaders,
|
|
6964
|
+
options.headers,
|
|
6965
|
+
]);
|
|
6966
|
+
this.validateHeaders(headers);
|
|
6967
|
+
return headers.values;
|
|
6968
|
+
}
|
|
6969
|
+
buildBody({ options: { body, headers: rawHeaders } }) {
|
|
6970
|
+
if (!body) {
|
|
6971
|
+
return { bodyHeaders: undefined, body: undefined };
|
|
6972
|
+
}
|
|
6973
|
+
const headers = buildHeaders([rawHeaders]);
|
|
6974
|
+
if (
|
|
6975
|
+
// Pass raw type verbatim
|
|
6976
|
+
ArrayBuffer.isView(body) ||
|
|
6977
|
+
body instanceof ArrayBuffer ||
|
|
6978
|
+
body instanceof DataView ||
|
|
6979
|
+
(typeof body === 'string' &&
|
|
6980
|
+
// Preserve legacy string encoding behavior for now
|
|
6981
|
+
headers.values.has('content-type')) ||
|
|
6982
|
+
// `Blob` is superset of `File`
|
|
6983
|
+
(globalThis.Blob && body instanceof globalThis.Blob) ||
|
|
6984
|
+
// `FormData` -> `multipart/form-data`
|
|
6985
|
+
body instanceof FormData ||
|
|
6986
|
+
// `URLSearchParams` -> `application/x-www-form-urlencoded`
|
|
6987
|
+
body instanceof URLSearchParams ||
|
|
6988
|
+
// Send chunked stream (each chunk has own `length`)
|
|
6989
|
+
(globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
|
|
6990
|
+
return { bodyHeaders: undefined, body: body };
|
|
6991
|
+
}
|
|
6992
|
+
else if (typeof body === 'object' &&
|
|
6993
|
+
(Symbol.asyncIterator in body ||
|
|
6994
|
+
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
|
|
6995
|
+
return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
|
|
6996
|
+
}
|
|
6997
|
+
else {
|
|
6998
|
+
return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
|
|
6999
|
+
}
|
|
7000
|
+
}
|
|
7001
|
+
}
|
|
7002
|
+
_a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
|
|
7003
|
+
return this.baseURL !== environments[this._options.environment || 'live_mode'];
|
|
7004
|
+
};
|
|
7005
|
+
DodoPayments.DodoPayments = _a;
|
|
7006
|
+
DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
|
|
7007
|
+
DodoPayments.DodoPaymentsError = DodoPaymentsError;
|
|
7008
|
+
DodoPayments.APIError = APIError;
|
|
7009
|
+
DodoPayments.APIConnectionError = APIConnectionError;
|
|
7010
|
+
DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
|
|
7011
|
+
DodoPayments.APIUserAbortError = APIUserAbortError;
|
|
7012
|
+
DodoPayments.NotFoundError = NotFoundError;
|
|
7013
|
+
DodoPayments.ConflictError = ConflictError;
|
|
7014
|
+
DodoPayments.RateLimitError = RateLimitError;
|
|
7015
|
+
DodoPayments.BadRequestError = BadRequestError;
|
|
7016
|
+
DodoPayments.AuthenticationError = AuthenticationError;
|
|
7017
|
+
DodoPayments.InternalServerError = InternalServerError;
|
|
7018
|
+
DodoPayments.PermissionDeniedError = PermissionDeniedError;
|
|
7019
|
+
DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
|
|
7020
|
+
DodoPayments.toFile = toFile;
|
|
7021
|
+
DodoPayments.CheckoutSessions = CheckoutSessions;
|
|
7022
|
+
DodoPayments.Payments = Payments;
|
|
7023
|
+
DodoPayments.Subscriptions = Subscriptions;
|
|
7024
|
+
DodoPayments.Invoices = Invoices;
|
|
7025
|
+
DodoPayments.Licenses = Licenses;
|
|
7026
|
+
DodoPayments.LicenseKeys = LicenseKeys;
|
|
7027
|
+
DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
|
|
7028
|
+
DodoPayments.Customers = Customers;
|
|
7029
|
+
DodoPayments.Refunds = Refunds;
|
|
7030
|
+
DodoPayments.Disputes = Disputes;
|
|
7031
|
+
DodoPayments.Payouts = Payouts;
|
|
7032
|
+
DodoPayments.Products = Products;
|
|
7033
|
+
DodoPayments.Misc = Misc;
|
|
7034
|
+
DodoPayments.Discounts = Discounts;
|
|
7035
|
+
DodoPayments.Addons = Addons;
|
|
7036
|
+
DodoPayments.Brands = Brands;
|
|
7037
|
+
DodoPayments.Webhooks = Webhooks$1;
|
|
7038
|
+
DodoPayments.WebhookEvents = WebhookEvents;
|
|
7039
|
+
DodoPayments.UsageEvents = UsageEvents;
|
|
7040
|
+
DodoPayments.Meters = Meters;
|
|
7041
|
+
|
|
7042
|
+
// src/checkout/checkout.ts
|
|
7043
|
+
var checkoutQuerySchema = objectType({
|
|
7044
|
+
productId: stringType(),
|
|
7045
|
+
quantity: stringType().optional(),
|
|
7046
|
+
// Customer fields
|
|
7047
|
+
fullName: stringType().optional(),
|
|
7048
|
+
firstName: stringType().optional(),
|
|
7049
|
+
lastName: stringType().optional(),
|
|
7050
|
+
email: stringType().optional(),
|
|
7051
|
+
country: stringType().optional(),
|
|
7052
|
+
addressLine: stringType().optional(),
|
|
7053
|
+
city: stringType().optional(),
|
|
7054
|
+
state: stringType().optional(),
|
|
7055
|
+
zipCode: stringType().optional(),
|
|
7056
|
+
// Disable flags
|
|
7057
|
+
disableFullName: stringType().optional(),
|
|
7058
|
+
disableFirstName: stringType().optional(),
|
|
7059
|
+
disableLastName: stringType().optional(),
|
|
7060
|
+
disableEmail: stringType().optional(),
|
|
7061
|
+
disableCountry: stringType().optional(),
|
|
7062
|
+
disableAddressLine: stringType().optional(),
|
|
7063
|
+
disableCity: stringType().optional(),
|
|
7064
|
+
disableState: stringType().optional(),
|
|
7065
|
+
disableZipCode: stringType().optional(),
|
|
7066
|
+
// Advanced controls
|
|
7067
|
+
paymentCurrency: stringType().optional(),
|
|
7068
|
+
showCurrencySelector: stringType().optional(),
|
|
7069
|
+
paymentAmount: stringType().optional(),
|
|
7070
|
+
showDiscounts: stringType().optional()
|
|
7071
|
+
// Metadata (allow any key starting with metadata_)
|
|
7072
|
+
// We'll handle metadata separately in the handler
|
|
7073
|
+
}).catchall(unknownType());
|
|
7074
|
+
var dynamicCheckoutBodySchema = objectType({
|
|
7075
|
+
// For subscription
|
|
7076
|
+
product_id: stringType().optional(),
|
|
7077
|
+
quantity: numberType().optional(),
|
|
7078
|
+
// For one-time payment
|
|
7079
|
+
product_cart: arrayType(
|
|
7080
|
+
objectType({
|
|
7081
|
+
product_id: stringType(),
|
|
7082
|
+
quantity: numberType()
|
|
7083
|
+
})
|
|
7084
|
+
).optional(),
|
|
7085
|
+
// Common fields
|
|
7086
|
+
billing: objectType({
|
|
7087
|
+
city: stringType(),
|
|
7088
|
+
country: stringType(),
|
|
7089
|
+
state: stringType(),
|
|
7090
|
+
street: stringType(),
|
|
7091
|
+
zipcode: stringType()
|
|
7092
|
+
}),
|
|
7093
|
+
customer: objectType({
|
|
7094
|
+
customer_id: stringType().optional(),
|
|
7095
|
+
email: stringType().optional(),
|
|
7096
|
+
name: stringType().optional()
|
|
7097
|
+
}),
|
|
7098
|
+
discount_id: stringType().optional(),
|
|
7099
|
+
addons: arrayType(
|
|
7100
|
+
objectType({
|
|
7101
|
+
addon_id: stringType(),
|
|
7102
|
+
quantity: numberType()
|
|
7103
|
+
})
|
|
7104
|
+
).optional(),
|
|
7105
|
+
metadata: recordType(stringType(), stringType()).optional(),
|
|
7106
|
+
currency: stringType().optional()
|
|
7107
|
+
// Allow any additional fields (for future compatibility)
|
|
7108
|
+
}).catchall(unknownType());
|
|
7109
|
+
var checkoutSessionProductCartItemSchema = objectType({
|
|
7110
|
+
product_id: stringType().min(1, "Product ID is required"),
|
|
7111
|
+
quantity: numberType().int().positive("Quantity must be a positive integer"),
|
|
7112
|
+
addons: arrayType(
|
|
7113
|
+
objectType({
|
|
7114
|
+
addon_id: stringType(),
|
|
7115
|
+
quantity: numberType().int().nonnegative()
|
|
7116
|
+
})
|
|
7117
|
+
).optional(),
|
|
7118
|
+
amount: numberType().int().nonnegative(
|
|
7119
|
+
"Amount must be a non-negative integer (for pay-what-you-want products)"
|
|
7120
|
+
).optional()
|
|
7121
|
+
});
|
|
7122
|
+
var checkoutSessionCustomerSchema = unionType([
|
|
7123
|
+
objectType({
|
|
7124
|
+
email: stringType().email(),
|
|
7125
|
+
name: stringType().min(1).optional(),
|
|
7126
|
+
phone_number: stringType().optional()
|
|
7127
|
+
}),
|
|
7128
|
+
objectType({
|
|
7129
|
+
customer_id: stringType()
|
|
7130
|
+
})
|
|
7131
|
+
]).optional();
|
|
7132
|
+
var checkoutSessionBillingAddressSchema = objectType({
|
|
7133
|
+
street: stringType().optional(),
|
|
7134
|
+
city: stringType().optional(),
|
|
7135
|
+
state: stringType().optional(),
|
|
7136
|
+
country: stringType().length(2, "Country must be a 2-letter ISO code"),
|
|
7137
|
+
zipcode: stringType().optional()
|
|
7138
|
+
}).optional();
|
|
7139
|
+
var paymentMethodTypeSchema = enumType([
|
|
7140
|
+
"credit",
|
|
7141
|
+
"debit",
|
|
7142
|
+
"upi_collect",
|
|
7143
|
+
"upi_intent",
|
|
7144
|
+
"apple_pay",
|
|
7145
|
+
"cashapp",
|
|
7146
|
+
"google_pay",
|
|
7147
|
+
"multibanco",
|
|
7148
|
+
"bancontact_card",
|
|
7149
|
+
"eps",
|
|
7150
|
+
"ideal",
|
|
7151
|
+
"przelewy24",
|
|
7152
|
+
"paypal",
|
|
7153
|
+
"affirm",
|
|
7154
|
+
"klarna",
|
|
7155
|
+
"sepa",
|
|
7156
|
+
"ach",
|
|
7157
|
+
"amazon_pay",
|
|
7158
|
+
"afterpay_clearpay"
|
|
7159
|
+
]);
|
|
7160
|
+
var checkoutSessionCustomizationSchema = objectType({
|
|
7161
|
+
theme: enumType(["light", "dark", "system"]).optional(),
|
|
7162
|
+
show_order_details: booleanType().optional(),
|
|
7163
|
+
show_on_demand_tag: booleanType().optional(),
|
|
7164
|
+
force_language: stringType().optional()
|
|
7165
|
+
}).optional();
|
|
7166
|
+
var checkoutSessionFeatureFlagsSchema = objectType({
|
|
7167
|
+
allow_currency_selection: booleanType().optional(),
|
|
7168
|
+
allow_discount_code: booleanType().optional(),
|
|
7169
|
+
allow_phone_number_collection: booleanType().optional(),
|
|
7170
|
+
allow_tax_id: booleanType().optional(),
|
|
7171
|
+
always_create_new_customer: booleanType().optional()
|
|
7172
|
+
}).optional();
|
|
7173
|
+
var checkoutSessionOnDemandSchema = objectType({
|
|
7174
|
+
mandate_only: booleanType(),
|
|
7175
|
+
product_price: numberType().int().optional(),
|
|
7176
|
+
product_currency: stringType().length(3).optional(),
|
|
7177
|
+
product_description: stringType().optional(),
|
|
7178
|
+
adaptive_currency_fees_inclusive: booleanType().optional()
|
|
7179
|
+
}).optional();
|
|
7180
|
+
var checkoutSessionSubscriptionDataSchema = objectType({
|
|
7181
|
+
trial_period_days: numberType().int().nonnegative().optional(),
|
|
7182
|
+
on_demand: checkoutSessionOnDemandSchema
|
|
7183
|
+
}).optional();
|
|
7184
|
+
var checkoutSessionPayloadSchema = objectType({
|
|
7185
|
+
// Required fields
|
|
7186
|
+
product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
|
|
7187
|
+
// Optional fields
|
|
7188
|
+
customer: checkoutSessionCustomerSchema,
|
|
7189
|
+
billing_address: checkoutSessionBillingAddressSchema,
|
|
7190
|
+
return_url: stringType().url().optional(),
|
|
7191
|
+
allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
|
|
7192
|
+
billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
|
|
7193
|
+
show_saved_payment_methods: booleanType().optional(),
|
|
7194
|
+
confirm: booleanType().optional(),
|
|
7195
|
+
discount_code: stringType().optional(),
|
|
7196
|
+
metadata: recordType(stringType(), stringType()).optional(),
|
|
7197
|
+
customization: checkoutSessionCustomizationSchema,
|
|
7198
|
+
feature_flags: checkoutSessionFeatureFlagsSchema,
|
|
7199
|
+
subscription_data: checkoutSessionSubscriptionDataSchema,
|
|
7200
|
+
force_3ds: booleanType().optional()
|
|
7201
|
+
});
|
|
7202
|
+
var checkoutSessionResponseSchema = objectType({
|
|
7203
|
+
session_id: stringType().min(1, "Session ID is required"),
|
|
7204
|
+
checkout_url: stringType().url("Invalid checkout URL")
|
|
7205
|
+
});
|
|
7206
|
+
var createCheckoutSession = async (payload, config) => {
|
|
7207
|
+
const validation = checkoutSessionPayloadSchema.safeParse(payload);
|
|
7208
|
+
if (!validation.success) {
|
|
7209
|
+
throw new Error(
|
|
7210
|
+
`Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
|
|
7211
|
+
);
|
|
7212
|
+
}
|
|
7213
|
+
const dodopayments = new DodoPayments({
|
|
7214
|
+
bearerToken: config.bearerToken,
|
|
7215
|
+
environment: config.environment
|
|
7216
|
+
});
|
|
7217
|
+
try {
|
|
7218
|
+
const sdkPayload = {
|
|
7219
|
+
...validation.data,
|
|
7220
|
+
...validation.data.billing_address && {
|
|
7221
|
+
billing_address: {
|
|
7222
|
+
...validation.data.billing_address,
|
|
7223
|
+
country: validation.data.billing_address.country
|
|
7224
|
+
}
|
|
7225
|
+
}
|
|
7226
|
+
};
|
|
7227
|
+
const session = await dodopayments.checkoutSessions.create(
|
|
7228
|
+
sdkPayload
|
|
7229
|
+
);
|
|
7230
|
+
const responseValidation = checkoutSessionResponseSchema.safeParse(session);
|
|
7231
|
+
if (!responseValidation.success) {
|
|
7232
|
+
throw new Error(
|
|
7233
|
+
`Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
|
|
7234
|
+
);
|
|
7235
|
+
}
|
|
7236
|
+
return responseValidation.data;
|
|
7237
|
+
} catch (error) {
|
|
7238
|
+
if (error instanceof Error) {
|
|
7239
|
+
console.error("Dodo Payments Checkout Session API Error:", {
|
|
7240
|
+
message: error.message,
|
|
7241
|
+
payload: validation.data,
|
|
7242
|
+
config: {
|
|
7243
|
+
environment: config.environment,
|
|
7244
|
+
hasBearerToken: !!config.bearerToken
|
|
7245
|
+
}
|
|
7246
|
+
});
|
|
7247
|
+
throw new Error(`Failed to create checkout session: ${error.message}`);
|
|
7248
|
+
}
|
|
7249
|
+
console.error("Unknown error creating checkout session:", error);
|
|
7250
|
+
throw new Error(
|
|
7251
|
+
"Failed to create checkout session due to an unknown error"
|
|
7252
|
+
);
|
|
7253
|
+
}
|
|
7254
|
+
};
|
|
7255
|
+
var buildCheckoutUrl = async ({
|
|
7256
|
+
queryParams,
|
|
7257
|
+
body,
|
|
7258
|
+
sessionPayload,
|
|
7259
|
+
returnUrl,
|
|
7260
|
+
bearerToken,
|
|
7261
|
+
environment,
|
|
7262
|
+
type = "static"
|
|
7263
|
+
}) => {
|
|
7264
|
+
if (type === "session") {
|
|
7265
|
+
if (!sessionPayload) {
|
|
7266
|
+
throw new Error("sessionPayload is required when type is 'session'");
|
|
7267
|
+
}
|
|
7268
|
+
const session = await createCheckoutSession(sessionPayload, {
|
|
7269
|
+
bearerToken,
|
|
7270
|
+
environment
|
|
7271
|
+
});
|
|
7272
|
+
return session.checkout_url;
|
|
7273
|
+
}
|
|
7274
|
+
const inputData = type === "dynamic" ? body : queryParams;
|
|
7275
|
+
let parseResult;
|
|
7276
|
+
if (type === "dynamic") {
|
|
7277
|
+
parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
|
|
7278
|
+
} else {
|
|
7279
|
+
parseResult = checkoutQuerySchema.safeParse(inputData);
|
|
7280
|
+
}
|
|
7281
|
+
const { success, data, error } = parseResult;
|
|
7282
|
+
if (!success) {
|
|
7283
|
+
throw new Error(
|
|
7284
|
+
`Invalid ${type === "dynamic" ? "body" : "query parameters"}.
|
|
7285
|
+
${error.message}`
|
|
7286
|
+
);
|
|
7287
|
+
}
|
|
7288
|
+
if (type !== "dynamic") {
|
|
7289
|
+
const {
|
|
7290
|
+
productId,
|
|
7291
|
+
quantity: quantity2,
|
|
7292
|
+
fullName,
|
|
7293
|
+
firstName,
|
|
7294
|
+
lastName,
|
|
7295
|
+
email,
|
|
7296
|
+
country,
|
|
7297
|
+
addressLine,
|
|
7298
|
+
city,
|
|
7299
|
+
state,
|
|
7300
|
+
zipCode,
|
|
7301
|
+
disableFullName,
|
|
7302
|
+
disableFirstName,
|
|
7303
|
+
disableLastName,
|
|
7304
|
+
disableEmail,
|
|
7305
|
+
disableCountry,
|
|
7306
|
+
disableAddressLine,
|
|
7307
|
+
disableCity,
|
|
7308
|
+
disableState,
|
|
7309
|
+
disableZipCode,
|
|
7310
|
+
paymentCurrency,
|
|
7311
|
+
showCurrencySelector,
|
|
7312
|
+
paymentAmount,
|
|
7313
|
+
showDiscounts
|
|
7314
|
+
// metadata handled below
|
|
7315
|
+
} = data;
|
|
7316
|
+
const dodopayments2 = new DodoPayments({
|
|
7317
|
+
bearerToken,
|
|
7318
|
+
environment
|
|
7319
|
+
});
|
|
7320
|
+
if (!productId) throw new Error("Missing required field: productId");
|
|
7321
|
+
try {
|
|
7322
|
+
await dodopayments2.products.retrieve(productId);
|
|
7323
|
+
} catch (err) {
|
|
7324
|
+
console.error(err);
|
|
7325
|
+
throw new Error("Product not found");
|
|
7326
|
+
}
|
|
7327
|
+
const url = new URL(
|
|
7328
|
+
`${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
|
|
7329
|
+
);
|
|
7330
|
+
url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
|
|
7331
|
+
if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
|
|
7332
|
+
if (fullName) url.searchParams.set("fullName", String(fullName));
|
|
7333
|
+
if (firstName) url.searchParams.set("firstName", String(firstName));
|
|
7334
|
+
if (lastName) url.searchParams.set("lastName", String(lastName));
|
|
7335
|
+
if (email) url.searchParams.set("email", String(email));
|
|
7336
|
+
if (country) url.searchParams.set("country", String(country));
|
|
7337
|
+
if (addressLine) url.searchParams.set("addressLine", String(addressLine));
|
|
7338
|
+
if (city) url.searchParams.set("city", String(city));
|
|
7339
|
+
if (state) url.searchParams.set("state", String(state));
|
|
7340
|
+
if (zipCode) url.searchParams.set("zipCode", String(zipCode));
|
|
7341
|
+
if (disableFullName === "true")
|
|
7342
|
+
url.searchParams.set("disableFullName", "true");
|
|
7343
|
+
if (disableFirstName === "true")
|
|
7344
|
+
url.searchParams.set("disableFirstName", "true");
|
|
7345
|
+
if (disableLastName === "true")
|
|
7346
|
+
url.searchParams.set("disableLastName", "true");
|
|
7347
|
+
if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
|
|
7348
|
+
if (disableCountry === "true")
|
|
7349
|
+
url.searchParams.set("disableCountry", "true");
|
|
7350
|
+
if (disableAddressLine === "true")
|
|
7351
|
+
url.searchParams.set("disableAddressLine", "true");
|
|
7352
|
+
if (disableCity === "true") url.searchParams.set("disableCity", "true");
|
|
7353
|
+
if (disableState === "true") url.searchParams.set("disableState", "true");
|
|
7354
|
+
if (disableZipCode === "true")
|
|
7355
|
+
url.searchParams.set("disableZipCode", "true");
|
|
7356
|
+
if (paymentCurrency)
|
|
7357
|
+
url.searchParams.set("paymentCurrency", String(paymentCurrency));
|
|
7358
|
+
if (showCurrencySelector)
|
|
7359
|
+
url.searchParams.set(
|
|
7360
|
+
"showCurrencySelector",
|
|
7361
|
+
String(showCurrencySelector)
|
|
7362
|
+
);
|
|
7363
|
+
if (paymentAmount)
|
|
7364
|
+
url.searchParams.set("paymentAmount", String(paymentAmount));
|
|
7365
|
+
if (showDiscounts)
|
|
7366
|
+
url.searchParams.set("showDiscounts", String(showDiscounts));
|
|
7367
|
+
for (const [key, value] of Object.entries(queryParams || {})) {
|
|
7368
|
+
if (key.startsWith("metadata_") && value && typeof value !== "object") {
|
|
7369
|
+
url.searchParams.set(key, String(value));
|
|
7370
|
+
}
|
|
7371
|
+
}
|
|
7372
|
+
return url.toString();
|
|
7373
|
+
}
|
|
7374
|
+
const dyn = data;
|
|
7375
|
+
const {
|
|
7376
|
+
product_id,
|
|
7377
|
+
product_cart,
|
|
7378
|
+
quantity,
|
|
7379
|
+
billing,
|
|
7380
|
+
customer,
|
|
7381
|
+
addons,
|
|
7382
|
+
metadata,
|
|
7383
|
+
allowed_payment_method_types,
|
|
7384
|
+
billing_currency,
|
|
7385
|
+
discount_code,
|
|
7386
|
+
on_demand,
|
|
7387
|
+
return_url: bodyReturnUrl,
|
|
7388
|
+
show_saved_payment_methods,
|
|
7389
|
+
tax_id,
|
|
7390
|
+
trial_period_days
|
|
7391
|
+
} = dyn;
|
|
7392
|
+
const dodopayments = new DodoPayments({
|
|
7393
|
+
bearerToken,
|
|
7394
|
+
environment
|
|
7395
|
+
});
|
|
7396
|
+
let isSubscription = false;
|
|
7397
|
+
let productIdToFetch = product_id;
|
|
7398
|
+
if (!product_id && product_cart && product_cart.length > 0) {
|
|
7399
|
+
productIdToFetch = product_cart[0].product_id;
|
|
7400
|
+
}
|
|
7401
|
+
if (!productIdToFetch)
|
|
7402
|
+
throw new Error(
|
|
7403
|
+
"Missing required field: product_id or product_cart[0].product_id"
|
|
7404
|
+
);
|
|
7405
|
+
let product;
|
|
7406
|
+
try {
|
|
7407
|
+
product = await dodopayments.products.retrieve(productIdToFetch);
|
|
7408
|
+
} catch (err) {
|
|
7409
|
+
console.error(err);
|
|
7410
|
+
throw new Error("Product not found");
|
|
7411
|
+
}
|
|
7412
|
+
isSubscription = Boolean(product.is_recurring);
|
|
7413
|
+
if (isSubscription && !product_id)
|
|
7414
|
+
throw new Error("Missing required field: product_id for subscription");
|
|
7415
|
+
if (!billing) throw new Error("Missing required field: billing");
|
|
7416
|
+
if (!customer) throw new Error("Missing required field: customer");
|
|
7417
|
+
if (isSubscription) {
|
|
7418
|
+
const subscriptionPayload = {
|
|
7419
|
+
billing,
|
|
7420
|
+
customer,
|
|
7421
|
+
product_id,
|
|
7422
|
+
quantity: quantity ? Number(quantity) : 1
|
|
7423
|
+
};
|
|
7424
|
+
if (metadata) subscriptionPayload.metadata = metadata;
|
|
7425
|
+
if (discount_code) subscriptionPayload.discount_code = discount_code;
|
|
7426
|
+
if (addons) subscriptionPayload.addons = addons;
|
|
7427
|
+
if (allowed_payment_method_types)
|
|
7428
|
+
subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
|
|
7429
|
+
if (billing_currency)
|
|
7430
|
+
subscriptionPayload.billing_currency = billing_currency;
|
|
7431
|
+
if (on_demand) subscriptionPayload.on_demand = on_demand;
|
|
7432
|
+
subscriptionPayload.payment_link = true;
|
|
7433
|
+
if (bodyReturnUrl) {
|
|
7434
|
+
subscriptionPayload.return_url = bodyReturnUrl;
|
|
7435
|
+
} else if (returnUrl) {
|
|
7436
|
+
subscriptionPayload.return_url = returnUrl;
|
|
7437
|
+
}
|
|
7438
|
+
if (show_saved_payment_methods)
|
|
7439
|
+
subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
|
|
7440
|
+
if (tax_id) subscriptionPayload.tax_id = tax_id;
|
|
7441
|
+
if (trial_period_days)
|
|
7442
|
+
subscriptionPayload.trial_period_days = trial_period_days;
|
|
7443
|
+
let subscription;
|
|
7444
|
+
try {
|
|
7445
|
+
subscription = await dodopayments.subscriptions.create(subscriptionPayload);
|
|
7446
|
+
} catch (err) {
|
|
7447
|
+
console.error("Error when creating subscription", err);
|
|
7448
|
+
throw new Error(err instanceof Error ? err.message : String(err));
|
|
7486
7449
|
}
|
|
7487
|
-
|
|
7488
|
-
|
|
7489
|
-
|
|
7490
|
-
|
|
7491
|
-
|
|
7492
|
-
|
|
7450
|
+
if (!subscription || !subscription.payment_link) {
|
|
7451
|
+
throw new Error(
|
|
7452
|
+
"No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
|
|
7453
|
+
);
|
|
7454
|
+
}
|
|
7455
|
+
return subscription.payment_link;
|
|
7456
|
+
} else {
|
|
7457
|
+
let cart = product_cart;
|
|
7458
|
+
if (!cart && product_id) {
|
|
7459
|
+
cart = [
|
|
7460
|
+
{ product_id, quantity: quantity ? Number(quantity) : 1 }
|
|
7461
|
+
];
|
|
7462
|
+
}
|
|
7463
|
+
if (!cart || cart.length === 0)
|
|
7464
|
+
throw new Error("Missing required field: product_cart or product_id");
|
|
7465
|
+
const paymentPayload = {
|
|
7466
|
+
billing,
|
|
7467
|
+
customer,
|
|
7468
|
+
product_cart: cart
|
|
7469
|
+
};
|
|
7470
|
+
if (metadata) paymentPayload.metadata = metadata;
|
|
7471
|
+
paymentPayload.payment_link = true;
|
|
7472
|
+
if (allowed_payment_method_types)
|
|
7473
|
+
paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
|
|
7474
|
+
if (billing_currency) paymentPayload.billing_currency = billing_currency;
|
|
7475
|
+
if (discount_code) paymentPayload.discount_code = discount_code;
|
|
7476
|
+
if (bodyReturnUrl) {
|
|
7477
|
+
paymentPayload.return_url = bodyReturnUrl;
|
|
7478
|
+
} else if (returnUrl) {
|
|
7479
|
+
paymentPayload.return_url = returnUrl;
|
|
7480
|
+
}
|
|
7481
|
+
if (show_saved_payment_methods)
|
|
7482
|
+
paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
|
|
7483
|
+
if (tax_id) paymentPayload.tax_id = tax_id;
|
|
7484
|
+
let payment;
|
|
7485
|
+
try {
|
|
7486
|
+
payment = await dodopayments.payments.create(paymentPayload);
|
|
7487
|
+
} catch (err) {
|
|
7488
|
+
console.error("Error when creating payment link", err);
|
|
7489
|
+
throw new Error(err instanceof Error ? err.message : String(err));
|
|
7490
|
+
}
|
|
7491
|
+
if (!payment || !payment.payment_link) {
|
|
7492
|
+
throw new Error(
|
|
7493
|
+
"No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
|
|
7494
|
+
);
|
|
7495
|
+
}
|
|
7496
|
+
return payment.payment_link;
|
|
7497
|
+
}
|
|
7498
|
+
};
|
|
7499
|
+
|
|
7500
|
+
const Checkout = (config) => {
|
|
7501
|
+
const getHandler = async ({ request }) => {
|
|
7502
|
+
const { searchParams } = new URL(request.url);
|
|
7503
|
+
const queryParams = Object.fromEntries(searchParams);
|
|
7504
|
+
if (!queryParams.productId) {
|
|
7505
|
+
return new Response("Please provide productId query parameter", {
|
|
7506
|
+
status: 400,
|
|
7507
|
+
});
|
|
7493
7508
|
}
|
|
7494
|
-
|
|
7495
|
-
|
|
7496
|
-
|
|
7497
|
-
|
|
7498
|
-
|
|
7499
|
-
|
|
7509
|
+
const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
|
|
7510
|
+
if (!success) {
|
|
7511
|
+
if (error.errors.some((e) => e.path.toString() === "productId")) {
|
|
7512
|
+
return new Response("Please provide productId query parameter", {
|
|
7513
|
+
status: 400,
|
|
7514
|
+
});
|
|
7500
7515
|
}
|
|
7516
|
+
return new Response(`Invalid query parameters.\n ${error.message}`, {
|
|
7517
|
+
status: 400,
|
|
7518
|
+
});
|
|
7501
7519
|
}
|
|
7502
|
-
|
|
7503
|
-
|
|
7504
|
-
|
|
7505
|
-
}
|
|
7506
|
-
if (secret.startsWith(Webhook.prefix)) {
|
|
7507
|
-
secret = secret.substring(Webhook.prefix.length);
|
|
7508
|
-
}
|
|
7509
|
-
this.key = base64.decode(secret);
|
|
7520
|
+
let url = "";
|
|
7521
|
+
try {
|
|
7522
|
+
url = await buildCheckoutUrl({ queryParams: data, ...config });
|
|
7510
7523
|
}
|
|
7511
|
-
|
|
7512
|
-
|
|
7513
|
-
const headers = {};
|
|
7514
|
-
for (const key of Object.keys(headers_)) {
|
|
7515
|
-
headers[key.toLowerCase()] = headers_[key];
|
|
7524
|
+
catch (error) {
|
|
7525
|
+
return new Response(error.message, { status: 400 });
|
|
7516
7526
|
}
|
|
7517
|
-
|
|
7518
|
-
|
|
7519
|
-
|
|
7520
|
-
|
|
7521
|
-
|
|
7527
|
+
return Response.json({ checkout_url: url });
|
|
7528
|
+
};
|
|
7529
|
+
const postHandler = async ({ request }) => {
|
|
7530
|
+
let body;
|
|
7531
|
+
try {
|
|
7532
|
+
body = await request.json();
|
|
7522
7533
|
}
|
|
7523
|
-
|
|
7524
|
-
|
|
7525
|
-
|
|
7526
|
-
|
|
7527
|
-
|
|
7528
|
-
|
|
7529
|
-
|
|
7530
|
-
|
|
7531
|
-
|
|
7534
|
+
catch (e) {
|
|
7535
|
+
return new Response("Invalid JSON body", { status: 400 });
|
|
7536
|
+
}
|
|
7537
|
+
if (config.type === "dynamic") {
|
|
7538
|
+
// Handle dynamic checkout
|
|
7539
|
+
const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
|
|
7540
|
+
if (!success) {
|
|
7541
|
+
return new Response(`Invalid request body.\n ${error.message}`, {
|
|
7542
|
+
status: 400,
|
|
7543
|
+
});
|
|
7532
7544
|
}
|
|
7533
|
-
|
|
7534
|
-
|
|
7545
|
+
let url = "";
|
|
7546
|
+
try {
|
|
7547
|
+
url = await buildCheckoutUrl({
|
|
7548
|
+
body: data,
|
|
7549
|
+
...config,
|
|
7550
|
+
type: "dynamic",
|
|
7551
|
+
});
|
|
7535
7552
|
}
|
|
7536
|
-
|
|
7537
|
-
|
|
7538
|
-
|
|
7539
|
-
|
|
7540
|
-
if (typeof payload === "string") ;
|
|
7541
|
-
else if (payload.constructor.name === "Buffer") {
|
|
7542
|
-
payload = payload.toString();
|
|
7553
|
+
catch (error) {
|
|
7554
|
+
return new Response(error.message, { status: 400 });
|
|
7555
|
+
}
|
|
7556
|
+
return Response.json({ checkout_url: url });
|
|
7543
7557
|
}
|
|
7544
7558
|
else {
|
|
7545
|
-
|
|
7559
|
+
// Handle checkout session
|
|
7560
|
+
const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
|
|
7561
|
+
if (!success) {
|
|
7562
|
+
return new Response(`Invalid checkout session payload.\n ${error.message}`, {
|
|
7563
|
+
status: 400,
|
|
7564
|
+
});
|
|
7565
|
+
}
|
|
7566
|
+
let url = "";
|
|
7567
|
+
try {
|
|
7568
|
+
url = await buildCheckoutUrl({
|
|
7569
|
+
sessionPayload: data,
|
|
7570
|
+
...config,
|
|
7571
|
+
type: "session",
|
|
7572
|
+
});
|
|
7573
|
+
}
|
|
7574
|
+
catch (error) {
|
|
7575
|
+
return new Response(error.message, { status: 400 });
|
|
7576
|
+
}
|
|
7577
|
+
return Response.json({ checkout_url: url });
|
|
7546
7578
|
}
|
|
7547
|
-
|
|
7548
|
-
|
|
7549
|
-
|
|
7550
|
-
|
|
7551
|
-
return `v1,${expectedSignature}`;
|
|
7552
|
-
}
|
|
7553
|
-
verifyTimestamp(timestampHeader) {
|
|
7554
|
-
const now = Math.floor(Date.now() / 1000);
|
|
7555
|
-
const timestamp = parseInt(timestampHeader, 10);
|
|
7556
|
-
if (isNaN(timestamp)) {
|
|
7557
|
-
throw new WebhookVerificationError("Invalid Signature Headers");
|
|
7579
|
+
};
|
|
7580
|
+
return (context) => {
|
|
7581
|
+
if (context.request.method === "POST") {
|
|
7582
|
+
return postHandler(context);
|
|
7558
7583
|
}
|
|
7559
|
-
|
|
7560
|
-
|
|
7584
|
+
return getHandler(context);
|
|
7585
|
+
};
|
|
7586
|
+
};
|
|
7587
|
+
|
|
7588
|
+
const CustomerPortal = ({ bearerToken, environment, }) => {
|
|
7589
|
+
const getHandler = async ({ request }) => {
|
|
7590
|
+
const { searchParams } = new URL(request.url);
|
|
7591
|
+
const customerId = searchParams.get("customer_id");
|
|
7592
|
+
const params = {
|
|
7593
|
+
send_email: false,
|
|
7594
|
+
};
|
|
7595
|
+
const sendEmail = Boolean(searchParams.get("send_email"));
|
|
7596
|
+
if (sendEmail) {
|
|
7597
|
+
params.send_email = sendEmail;
|
|
7561
7598
|
}
|
|
7562
|
-
if (
|
|
7563
|
-
|
|
7599
|
+
if (!customerId) {
|
|
7600
|
+
return new Response("Missing customerId in query parameters", {
|
|
7601
|
+
status: 400,
|
|
7602
|
+
});
|
|
7564
7603
|
}
|
|
7565
|
-
|
|
7566
|
-
|
|
7567
|
-
|
|
7568
|
-
|
|
7569
|
-
|
|
7604
|
+
const dodopayments = new DodoPayments({
|
|
7605
|
+
bearerToken,
|
|
7606
|
+
environment,
|
|
7607
|
+
});
|
|
7608
|
+
try {
|
|
7609
|
+
const session = await dodopayments.customers.customerPortal.create(customerId, params);
|
|
7610
|
+
return Response.redirect(session.link, 307);
|
|
7611
|
+
}
|
|
7612
|
+
catch (error) {
|
|
7613
|
+
console.error("Error creating customer portal session:", error);
|
|
7614
|
+
return new Response(`Failed to create customer portal session: ${error.message}`, {
|
|
7615
|
+
status: 500,
|
|
7616
|
+
});
|
|
7617
|
+
}
|
|
7618
|
+
};
|
|
7619
|
+
return getHandler;
|
|
7620
|
+
};
|
|
7570
7621
|
|
|
7571
7622
|
// src/schemas/webhook.ts
|
|
7572
7623
|
var PaymentSchema = objectType({
|