@dodopayments/tanstack 0.1.1 → 0.1.3

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.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
 
3
- const VERSION = '1.42.0'; // x-release-please-version
3
+ const VERSION = '1.51.2'; // x-release-please-version
4
4
 
5
5
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6
6
  class DodoPaymentsError extends Error {
@@ -1144,6 +1144,46 @@ class DefaultPageNumberPagination extends AbstractPage {
1144
1144
  return { params: { page_number: currentPage + 1 } };
1145
1145
  }
1146
1146
  }
1147
+ class CursorPagePagination extends AbstractPage {
1148
+ constructor(client, response, body, options) {
1149
+ super(client, response, body, options);
1150
+ this.data = body.data || [];
1151
+ this.iterator = body.iterator || '';
1152
+ this.done = body.done || false;
1153
+ }
1154
+ getPaginatedItems() {
1155
+ return this.data ?? [];
1156
+ }
1157
+ hasNextPage() {
1158
+ if (this.done === false) {
1159
+ return false;
1160
+ }
1161
+ return super.hasNextPage();
1162
+ }
1163
+ // @deprecated Please use `nextPageInfo()` instead
1164
+ nextPageParams() {
1165
+ const info = this.nextPageInfo();
1166
+ if (!info)
1167
+ return null;
1168
+ if ('params' in info)
1169
+ return info.params;
1170
+ const params = Object.fromEntries(info.url.searchParams);
1171
+ if (!Object.keys(params).length)
1172
+ return null;
1173
+ return params;
1174
+ }
1175
+ nextPageInfo() {
1176
+ const cursor = this.iterator;
1177
+ if (!cursor) {
1178
+ return null;
1179
+ }
1180
+ return {
1181
+ params: {
1182
+ iterator: cursor,
1183
+ },
1184
+ };
1185
+ }
1186
+ }
1147
1187
 
1148
1188
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1149
1189
  class APIResource {
@@ -1202,6 +1242,13 @@ class Brands extends APIResource {
1202
1242
  }
1203
1243
  }
1204
1244
 
1245
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1246
+ class CheckoutSessions extends APIResource {
1247
+ create(body, options) {
1248
+ return this._client.post('/checkouts', { body, ...options });
1249
+ }
1250
+ }
1251
+
1205
1252
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1206
1253
  let CustomerPortal$1 = class CustomerPortal extends APIResource {
1207
1254
  create(customerId, params = {}, options) {
@@ -1607,26 +1654,79 @@ Subscriptions.SubscriptionListResponsesDefaultPageNumberPagination =
1607
1654
  SubscriptionListResponsesDefaultPageNumberPagination;
1608
1655
 
1609
1656
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1610
- class WebhookEvents extends APIResource {
1657
+ let Headers$1 = class Headers extends APIResource {
1611
1658
  /**
1612
- * @deprecated
1659
+ * Get a webhook by id
1613
1660
  */
1614
- retrieve(webhookEventId, options) {
1615
- return this._client.get(`/webhook_events/${webhookEventId}`, options);
1661
+ retrieve(webhookId, options) {
1662
+ return this._client.get(`/webhooks/${webhookId}/headers`, options);
1663
+ }
1664
+ /**
1665
+ * Patch a webhook by id
1666
+ */
1667
+ update(webhookId, body, options) {
1668
+ return this._client.patch(`/webhooks/${webhookId}/headers`, {
1669
+ body,
1670
+ ...options,
1671
+ headers: { Accept: '*/*', ...options?.headers },
1672
+ });
1673
+ }
1674
+ };
1675
+
1676
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1677
+ let Webhooks$1 = class Webhooks extends APIResource {
1678
+ constructor() {
1679
+ super(...arguments);
1680
+ this.headers = new Headers$1(this._client);
1681
+ }
1682
+ /**
1683
+ * Create a new webhook
1684
+ */
1685
+ create(body, options) {
1686
+ return this._client.post('/webhooks', { body, ...options });
1687
+ }
1688
+ /**
1689
+ * Get a webhook by id
1690
+ */
1691
+ retrieve(webhookId, options) {
1692
+ return this._client.get(`/webhooks/${webhookId}`, options);
1693
+ }
1694
+ /**
1695
+ * Patch a webhook by id
1696
+ */
1697
+ update(webhookId, body, options) {
1698
+ return this._client.patch(`/webhooks/${webhookId}`, { body, ...options });
1616
1699
  }
1617
1700
  list(query = {}, options) {
1618
1701
  if (isRequestOptions(query)) {
1619
1702
  return this.list({}, query);
1620
1703
  }
1621
- return this._client.getAPIList('/webhook_events', WebhookEventsDefaultPageNumberPagination, {
1622
- query,
1704
+ return this._client.getAPIList('/webhooks', WebhookDetailsCursorPagePagination, { query, ...options });
1705
+ }
1706
+ /**
1707
+ * Delete a webhook by id
1708
+ */
1709
+ delete(webhookId, options) {
1710
+ return this._client.delete(`/webhooks/${webhookId}`, {
1623
1711
  ...options,
1712
+ headers: { Accept: '*/*', ...options?.headers },
1624
1713
  });
1625
1714
  }
1715
+ /**
1716
+ * Get webhook secret by id
1717
+ */
1718
+ retrieveSecret(webhookId, options) {
1719
+ return this._client.get(`/webhooks/${webhookId}/secret`, options);
1720
+ }
1721
+ };
1722
+ class WebhookDetailsCursorPagePagination extends CursorPagePagination {
1626
1723
  }
1627
- class WebhookEventsDefaultPageNumberPagination extends DefaultPageNumberPagination {
1724
+ Webhooks$1.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
1725
+ Webhooks$1.Headers = Headers$1;
1726
+
1727
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1728
+ class WebhookEvents extends APIResource {
1628
1729
  }
1629
- WebhookEvents.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
1630
1730
 
1631
1731
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1632
1732
  var _DodoPayments_instances, _a;
@@ -1673,6 +1773,7 @@ class DodoPayments extends APIClient {
1673
1773
  fetch: options.fetch,
1674
1774
  });
1675
1775
  _DodoPayments_instances.add(this);
1776
+ this.checkoutSessions = new CheckoutSessions(this);
1676
1777
  this.payments = new Payments(this);
1677
1778
  this.subscriptions = new Subscriptions(this);
1678
1779
  this.invoices = new Invoices(this);
@@ -1689,6 +1790,7 @@ class DodoPayments extends APIClient {
1689
1790
  this.discounts = new Discounts(this);
1690
1791
  this.addons = new Addons(this);
1691
1792
  this.brands = new Brands(this);
1793
+ this.webhooks = new Webhooks$1(this);
1692
1794
  this._options = options;
1693
1795
  this.bearerToken = bearerToken;
1694
1796
  }
@@ -1723,6 +1825,7 @@ DodoPayments.PermissionDeniedError = PermissionDeniedError;
1723
1825
  DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
1724
1826
  DodoPayments.toFile = toFile;
1725
1827
  DodoPayments.fileFromPath = fileFromPath;
1828
+ DodoPayments.CheckoutSessions = CheckoutSessions;
1726
1829
  DodoPayments.Payments = Payments;
1727
1830
  DodoPayments.PaymentListResponsesDefaultPageNumberPagination =
1728
1831
  PaymentListResponsesDefaultPageNumberPagination;
@@ -1745,7 +1848,6 @@ DodoPayments.DisputeListResponsesDefaultPageNumberPagination =
1745
1848
  DodoPayments.Payouts = Payouts;
1746
1849
  DodoPayments.PayoutListResponsesDefaultPageNumberPagination = PayoutListResponsesDefaultPageNumberPagination;
1747
1850
  DodoPayments.WebhookEvents = WebhookEvents;
1748
- DodoPayments.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
1749
1851
  DodoPayments.Products = Products;
1750
1852
  DodoPayments.ProductListResponsesDefaultPageNumberPagination =
1751
1853
  ProductListResponsesDefaultPageNumberPagination;
@@ -1755,7 +1857,20 @@ DodoPayments.DiscountsDefaultPageNumberPagination = DiscountsDefaultPageNumberPa
1755
1857
  DodoPayments.Addons = Addons;
1756
1858
  DodoPayments.AddonResponsesDefaultPageNumberPagination = AddonResponsesDefaultPageNumberPagination;
1757
1859
  DodoPayments.Brands = Brands;
1860
+ DodoPayments.Webhooks = Webhooks$1;
1861
+ DodoPayments.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
1758
1862
 
1863
+ var __assign = (undefined && undefined.__assign) || function () {
1864
+ __assign = Object.assign || function(t) {
1865
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1866
+ s = arguments[i];
1867
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1868
+ t[p] = s[p];
1869
+ }
1870
+ return t;
1871
+ };
1872
+ return __assign.apply(this, arguments);
1873
+ };
1759
1874
  var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1760
1875
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1761
1876
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -1792,7 +1907,8 @@ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, b
1792
1907
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1793
1908
  }
1794
1909
  };
1795
- var checkoutQuerySchema = z.object({
1910
+ var checkoutQuerySchema = z
1911
+ .object({
1796
1912
  productId: z.string(),
1797
1913
  quantity: z.string().optional(),
1798
1914
  // Customer fields
@@ -1822,7 +1938,8 @@ var checkoutQuerySchema = z.object({
1822
1938
  showDiscounts: z.string().optional(),
1823
1939
  // Metadata (allow any key starting with metadata_)
1824
1940
  // We'll handle metadata separately in the handler
1825
- });
1941
+ })
1942
+ .catchall(z.unknown());
1826
1943
  // Add Zod schema for dynamic checkout body
1827
1944
  var dynamicCheckoutBodySchema = z
1828
1945
  .object({
@@ -1861,12 +1978,192 @@ var dynamicCheckoutBodySchema = z
1861
1978
  // Allow any additional fields (for future compatibility)
1862
1979
  })
1863
1980
  .catchall(z.unknown());
1981
+ // ========================================
1982
+ // CHECKOUT SESSIONS SCHEMAS & TYPES
1983
+ // ========================================
1984
+ // Product cart item schema for checkout sessions
1985
+ var checkoutSessionProductCartItemSchema = z.object({
1986
+ product_id: z.string().min(1, "Product ID is required"),
1987
+ quantity: z.number().int().positive("Quantity must be a positive integer"),
1988
+ });
1989
+ // Customer information schema for checkout sessions
1990
+ var checkoutSessionCustomerSchema = z
1991
+ .object({
1992
+ email: z.string().email().optional(),
1993
+ name: z.string().min(1).optional(),
1994
+ phone_number: z.string().optional(),
1995
+ })
1996
+ .optional();
1997
+ // Billing address schema for checkout sessions
1998
+ var checkoutSessionBillingAddressSchema = z
1999
+ .object({
2000
+ street: z.string().optional(),
2001
+ city: z.string().optional(),
2002
+ state: z.string().optional(),
2003
+ country: z.string().length(2, "Country must be a 2-letter ISO code"),
2004
+ zipcode: z.string().optional(),
2005
+ })
2006
+ .optional();
2007
+ // Payment method types enum based on Dodo Payments documentation
2008
+ var paymentMethodTypeSchema = z.enum([
2009
+ "credit",
2010
+ "debit",
2011
+ "upi_collect",
2012
+ "upi_intent",
2013
+ "apple_pay",
2014
+ "google_pay",
2015
+ "amazon_pay",
2016
+ "klarna",
2017
+ "affirm",
2018
+ "afterpay_clearpay",
2019
+ "sepa",
2020
+ "ach",
2021
+ ]);
2022
+ // Customization options schema
2023
+ var checkoutSessionCustomizationSchema = z
2024
+ .object({
2025
+ theme: z.enum(["light", "dark", "system"]).optional(),
2026
+ show_order_details: z.boolean().optional(),
2027
+ show_on_demand_tag: z.boolean().optional(),
2028
+ })
2029
+ .optional();
2030
+ // Feature flags schema
2031
+ var checkoutSessionFeatureFlagsSchema = z
2032
+ .object({
2033
+ allow_currency_selection: z.boolean().optional(),
2034
+ allow_discount_code: z.boolean().optional(),
2035
+ allow_phone_number_collection: z.boolean().optional(),
2036
+ allow_tax_id: z.boolean().optional(),
2037
+ always_create_new_customer: z.boolean().optional(),
2038
+ })
2039
+ .optional();
2040
+ // Subscription data schema
2041
+ var checkoutSessionSubscriptionDataSchema = z
2042
+ .object({
2043
+ trial_period_days: z.number().int().nonnegative().optional(),
2044
+ })
2045
+ .optional();
2046
+ // Main checkout session payload schema
2047
+ var checkoutSessionPayloadSchema = z.object({
2048
+ // Required fields
2049
+ product_cart: z
2050
+ .array(checkoutSessionProductCartItemSchema)
2051
+ .min(1, "At least one product is required"),
2052
+ // Optional fields
2053
+ customer: checkoutSessionCustomerSchema,
2054
+ billing_address: checkoutSessionBillingAddressSchema,
2055
+ return_url: z.string().url().optional(),
2056
+ allowed_payment_method_types: z.array(paymentMethodTypeSchema).optional(),
2057
+ billing_currency: z
2058
+ .string()
2059
+ .length(3, "Currency must be a 3-letter ISO code")
2060
+ .optional(),
2061
+ show_saved_payment_methods: z.boolean().optional(),
2062
+ confirm: z.boolean().optional(),
2063
+ discount_code: z.string().optional(),
2064
+ metadata: z.record(z.string(), z.string()).optional(),
2065
+ customization: checkoutSessionCustomizationSchema,
2066
+ feature_flags: checkoutSessionFeatureFlagsSchema,
2067
+ subscription_data: checkoutSessionSubscriptionDataSchema,
2068
+ });
2069
+ // Checkout session response schema
2070
+ var checkoutSessionResponseSchema = z.object({
2071
+ session_id: z.string().min(1, "Session ID is required"),
2072
+ checkout_url: z.string().url("Invalid checkout URL"),
2073
+ });
2074
+ /**
2075
+ * Creates a new Dodo Payments Checkout Session using the modern /checkouts endpoint.
2076
+ * This function provides a clean, type-safe interface to the Checkout Sessions API.
2077
+ *
2078
+ * @param payload - The checkout session data, validated against CheckoutSessionPayloadSchema
2079
+ * @param config - Dodo Payments client configuration (bearerToken, environment)
2080
+ * @returns Promise<CheckoutSessionResponse> - The checkout session with session_id and checkout_url
2081
+ *
2082
+ * @throws {Error} When payload validation fails or API request fails
2083
+ *
2084
+ * @example
2085
+ * ```typescript
2086
+ * const session = await createCheckoutSession({
2087
+ * product_cart: [{ product_id: 'prod_123', quantity: 1 }],
2088
+ * customer: { email: 'customer@example.com' },
2089
+ * return_url: 'https://yoursite.com/success'
2090
+ * }, {
2091
+ * bearerToken: process.env.DODO_PAYMENTS_API_KEY,
2092
+ * environment: 'test_mode'
2093
+ * });
2094
+ *
2095
+ * ```
2096
+ */
2097
+ var createCheckoutSession = function (payload, config) { return __awaiter$1(void 0, void 0, void 0, function () {
2098
+ var validation, dodopayments, sdkPayload, session, responseValidation, error_1;
2099
+ return __generator$1(this, function (_a) {
2100
+ switch (_a.label) {
2101
+ case 0:
2102
+ validation = checkoutSessionPayloadSchema.safeParse(payload);
2103
+ if (!validation.success) {
2104
+ throw new Error("Invalid checkout session payload: ".concat(validation.error.issues
2105
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
2106
+ .join(", ")));
2107
+ }
2108
+ dodopayments = new DodoPayments({
2109
+ bearerToken: config.bearerToken,
2110
+ environment: config.environment,
2111
+ });
2112
+ _a.label = 1;
2113
+ case 1:
2114
+ _a.trys.push([1, 3, , 4]);
2115
+ sdkPayload = __assign(__assign({}, validation.data), (validation.data.billing_address && {
2116
+ billing_address: __assign(__assign({}, validation.data.billing_address), { country: validation.data.billing_address.country }),
2117
+ }));
2118
+ return [4 /*yield*/, dodopayments.checkoutSessions.create(sdkPayload)];
2119
+ case 2:
2120
+ session = _a.sent();
2121
+ responseValidation = checkoutSessionResponseSchema.safeParse(session);
2122
+ if (!responseValidation.success) {
2123
+ throw new Error("Invalid checkout session response from API: ".concat(responseValidation.error.issues
2124
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
2125
+ .join(", ")));
2126
+ }
2127
+ return [2 /*return*/, responseValidation.data];
2128
+ case 3:
2129
+ error_1 = _a.sent();
2130
+ if (error_1 instanceof Error) {
2131
+ console.error("Dodo Payments Checkout Session API Error:", {
2132
+ message: error_1.message,
2133
+ payload: validation.data,
2134
+ config: {
2135
+ environment: config.environment,
2136
+ hasBearerToken: !!config.bearerToken,
2137
+ },
2138
+ });
2139
+ // Re-throw with a more user-friendly message
2140
+ throw new Error("Failed to create checkout session: ".concat(error_1.message));
2141
+ }
2142
+ // Handle non-Error objects
2143
+ console.error("Unknown error creating checkout session:", error_1);
2144
+ throw new Error("Failed to create checkout session due to an unknown error");
2145
+ case 4: return [2 /*return*/];
2146
+ }
2147
+ });
2148
+ }); };
1864
2149
  var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
1865
- var inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
1866
- var queryParams = _b.queryParams, body = _b.body, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
2150
+ var session, inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
2151
+ var queryParams = _b.queryParams, body = _b.body, sessionPayload = _b.sessionPayload, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
1867
2152
  return __generator$1(this, function (_g) {
1868
2153
  switch (_g.label) {
1869
2154
  case 0:
2155
+ if (!(type === "session")) return [3 /*break*/, 2];
2156
+ if (!sessionPayload) {
2157
+ throw new Error("sessionPayload is required when type is 'session'");
2158
+ }
2159
+ return [4 /*yield*/, createCheckoutSession(sessionPayload, {
2160
+ bearerToken: bearerToken,
2161
+ environment: environment,
2162
+ })];
2163
+ case 1:
2164
+ session = _g.sent();
2165
+ return [2 /*return*/, session.checkout_url];
2166
+ case 2:
1870
2167
  inputData = type === "dynamic" ? body : queryParams;
1871
2168
  if (type === "dynamic") {
1872
2169
  parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
@@ -1878,7 +2175,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1878
2175
  if (!success) {
1879
2176
  throw new Error("Invalid ".concat(type === "dynamic" ? "body" : "query parameters", ".\n ").concat(error.message));
1880
2177
  }
1881
- if (!(type !== "dynamic")) return [3 /*break*/, 5];
2178
+ if (!(type !== "dynamic")) return [3 /*break*/, 7];
1882
2179
  _c = data, productId = _c.productId, quantity_1 = _c.quantity, fullName = _c.fullName, firstName = _c.firstName, lastName = _c.lastName, email = _c.email, country = _c.country, addressLine = _c.addressLine, city = _c.city, state = _c.state, zipCode = _c.zipCode, disableFullName = _c.disableFullName, disableFirstName = _c.disableFirstName, disableLastName = _c.disableLastName, disableEmail = _c.disableEmail, disableCountry = _c.disableCountry, disableAddressLine = _c.disableAddressLine, disableCity = _c.disableCity, disableState = _c.disableState, disableZipCode = _c.disableZipCode, paymentCurrency = _c.paymentCurrency, showCurrencySelector = _c.showCurrencySelector, paymentAmount = _c.paymentAmount, showDiscounts = _c.showDiscounts;
1883
2180
  dodopayments_1 = new DodoPayments({
1884
2181
  bearerToken: bearerToken,
@@ -1887,18 +2184,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1887
2184
  // Check that the product exists for this merchant
1888
2185
  if (!productId)
1889
2186
  throw new Error("Missing required field: productId");
1890
- _g.label = 1;
1891
- case 1:
1892
- _g.trys.push([1, 3, , 4]);
2187
+ _g.label = 3;
2188
+ case 3:
2189
+ _g.trys.push([3, 5, , 6]);
1893
2190
  return [4 /*yield*/, dodopayments_1.products.retrieve(productId)];
1894
- case 2:
2191
+ case 4:
1895
2192
  _g.sent();
1896
- return [3 /*break*/, 4];
1897
- case 3:
2193
+ return [3 /*break*/, 6];
2194
+ case 5:
1898
2195
  err_1 = _g.sent();
1899
2196
  console.error(err_1);
1900
2197
  throw new Error("Product not found");
1901
- case 4:
2198
+ case 6:
1902
2199
  url = new URL("".concat(environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com", "/buy/").concat(productId));
1903
2200
  url.searchParams.set("quantity", quantity_1 ? String(quantity_1) : "1");
1904
2201
  if (returnUrl)
@@ -1958,7 +2255,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1958
2255
  }
1959
2256
  }
1960
2257
  return [2 /*return*/, url.toString()];
1961
- case 5:
2258
+ case 7:
1962
2259
  dyn = data;
1963
2260
  product_id = dyn.product_id, product_cart = dyn.product_cart, quantity = dyn.quantity, billing = dyn.billing, customer = dyn.customer, addons = dyn.addons, metadata = dyn.metadata, allowed_payment_method_types = dyn.allowed_payment_method_types, billing_currency = dyn.billing_currency, discount_code = dyn.discount_code, on_demand = dyn.on_demand, bodyReturnUrl = dyn.return_url, show_saved_payment_methods = dyn.show_saved_payment_methods, tax_id = dyn.tax_id, trial_period_days = dyn.trial_period_days;
1964
2261
  dodopayments = new DodoPayments({
@@ -1972,18 +2269,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1972
2269
  }
1973
2270
  if (!productIdToFetch)
1974
2271
  throw new Error("Missing required field: product_id or product_cart[0].product_id");
1975
- _g.label = 6;
1976
- case 6:
1977
- _g.trys.push([6, 8, , 9]);
2272
+ _g.label = 8;
2273
+ case 8:
2274
+ _g.trys.push([8, 10, , 11]);
1978
2275
  return [4 /*yield*/, dodopayments.products.retrieve(productIdToFetch)];
1979
- case 7:
2276
+ case 9:
1980
2277
  product = _g.sent();
1981
- return [3 /*break*/, 9];
1982
- case 8:
2278
+ return [3 /*break*/, 11];
2279
+ case 10:
1983
2280
  err_2 = _g.sent();
1984
2281
  console.error(err_2);
1985
2282
  throw new Error("Product not found");
1986
- case 9:
2283
+ case 11:
1987
2284
  isSubscription = Boolean(product.is_recurring);
1988
2285
  // Required field validation
1989
2286
  if (isSubscription && !product_id)
@@ -1992,7 +2289,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1992
2289
  throw new Error("Missing required field: billing");
1993
2290
  if (!customer)
1994
2291
  throw new Error("Missing required field: customer");
1995
- if (!isSubscription) return [3 /*break*/, 14];
2292
+ if (!isSubscription) return [3 /*break*/, 16];
1996
2293
  subscriptionPayload = {
1997
2294
  billing: billing,
1998
2295
  customer: customer,
@@ -2028,24 +2325,24 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2028
2325
  if (trial_period_days)
2029
2326
  subscriptionPayload.trial_period_days = trial_period_days;
2030
2327
  subscription = void 0;
2031
- _g.label = 10;
2032
- case 10:
2033
- _g.trys.push([10, 12, , 13]);
2328
+ _g.label = 12;
2329
+ case 12:
2330
+ _g.trys.push([12, 14, , 15]);
2034
2331
  return [4 /*yield*/, dodopayments.subscriptions.create(subscriptionPayload)];
2035
- case 11:
2332
+ case 13:
2036
2333
  subscription =
2037
2334
  _g.sent();
2038
- return [3 /*break*/, 13];
2039
- case 12:
2335
+ return [3 /*break*/, 15];
2336
+ case 14:
2040
2337
  err_3 = _g.sent();
2041
2338
  console.error("Error when creating subscription", err_3);
2042
2339
  throw new Error(err_3 instanceof Error ? err_3.message : String(err_3));
2043
- case 13:
2340
+ case 15:
2044
2341
  if (!subscription || !subscription.payment_link) {
2045
2342
  throw new Error("No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload");
2046
2343
  }
2047
2344
  return [2 /*return*/, subscription.payment_link];
2048
- case 14:
2345
+ case 16:
2049
2346
  cart = product_cart;
2050
2347
  if (!cart && product_id) {
2051
2348
  cart = [
@@ -2081,18 +2378,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2081
2378
  if (tax_id)
2082
2379
  paymentPayload.tax_id = tax_id;
2083
2380
  payment = void 0;
2084
- _g.label = 15;
2085
- case 15:
2086
- _g.trys.push([15, 17, , 18]);
2381
+ _g.label = 17;
2382
+ case 17:
2383
+ _g.trys.push([17, 19, , 20]);
2087
2384
  return [4 /*yield*/, dodopayments.payments.create(paymentPayload)];
2088
- case 16:
2385
+ case 18:
2089
2386
  payment = _g.sent();
2090
- return [3 /*break*/, 18];
2091
- case 17:
2387
+ return [3 /*break*/, 20];
2388
+ case 19:
2092
2389
  err_4 = _g.sent();
2093
2390
  console.error("Error when creating payment link", err_4);
2094
2391
  throw new Error(err_4 instanceof Error ? err_4.message : String(err_4));
2095
- case 18:
2392
+ case 20:
2096
2393
  if (!payment || !payment.payment_link) {
2097
2394
  throw new Error("No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload.");
2098
2395
  }
@@ -2108,7 +2405,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2108
2405
  function Checkout(config) {
2109
2406
  return async function (request) {
2110
2407
  if (request.method === "POST") {
2111
- // Handle dynamic checkout (POST)
2408
+ // Handle dynamic checkout and checkout sessions (POST)
2112
2409
  let body;
2113
2410
  try {
2114
2411
  body = await request.json();
@@ -2116,20 +2413,48 @@ function Checkout(config) {
2116
2413
  catch (e) {
2117
2414
  return new Response("Invalid JSON body", { status: 400 });
2118
2415
  }
2119
- const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
2120
- if (!success) {
2121
- return new Response(`Invalid request body.\n ${error.message}`, {
2122
- status: 400,
2123
- });
2124
- }
2125
- let url = "";
2126
- try {
2127
- url = await buildCheckoutUrl({ body: data, ...config });
2416
+ if (config.type === "dynamic") {
2417
+ // Handle dynamic checkout
2418
+ const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
2419
+ if (!success) {
2420
+ return new Response(`Invalid request body.\n ${error.message}`, {
2421
+ status: 400,
2422
+ });
2423
+ }
2424
+ let url = "";
2425
+ try {
2426
+ url = await buildCheckoutUrl({
2427
+ body: data,
2428
+ ...config,
2429
+ type: "dynamic",
2430
+ });
2431
+ }
2432
+ catch (error) {
2433
+ return new Response(error.message, { status: 400 });
2434
+ }
2435
+ return Response.json({ checkout_url: url });
2128
2436
  }
2129
- catch (error) {
2130
- return new Response(error.message, { status: 400 });
2437
+ else {
2438
+ // Handle checkout session
2439
+ const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
2440
+ if (!success) {
2441
+ return new Response(`Invalid checkout session payload.\n ${error.message}`, {
2442
+ status: 400,
2443
+ });
2444
+ }
2445
+ let url = "";
2446
+ try {
2447
+ url = await buildCheckoutUrl({
2448
+ sessionPayload: data,
2449
+ ...config,
2450
+ type: "session",
2451
+ });
2452
+ }
2453
+ catch (error) {
2454
+ return new Response(error.message, { status: 400 });
2455
+ }
2456
+ return Response.json({ checkout_url: url });
2131
2457
  }
2132
- return Response.redirect(url, 302);
2133
2458
  }
2134
2459
  else {
2135
2460
  // Handle static checkout (GET)
@@ -2158,7 +2483,7 @@ function Checkout(config) {
2158
2483
  catch (error) {
2159
2484
  return new Response(error.message, { status: 400 });
2160
2485
  }
2161
- return Response.redirect(url, 302);
2486
+ return Response.json({ checkout_url: url });
2162
2487
  }
2163
2488
  };
2164
2489
  }