@dodopayments/nextjs 0.1.7 → 0.1.9

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
@@ -5344,7 +5344,7 @@ var reflectUtils = {};
5344
5344
 
5345
5345
  var serverExports = server.exports;
5346
5346
 
5347
- const VERSION = '1.42.0'; // x-release-please-version
5347
+ const VERSION = '1.51.2'; // x-release-please-version
5348
5348
 
5349
5349
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5350
5350
  class DodoPaymentsError extends Error {
@@ -6488,6 +6488,46 @@ class DefaultPageNumberPagination extends AbstractPage {
6488
6488
  return { params: { page_number: currentPage + 1 } };
6489
6489
  }
6490
6490
  }
6491
+ class CursorPagePagination extends AbstractPage {
6492
+ constructor(client, response, body, options) {
6493
+ super(client, response, body, options);
6494
+ this.data = body.data || [];
6495
+ this.iterator = body.iterator || '';
6496
+ this.done = body.done || false;
6497
+ }
6498
+ getPaginatedItems() {
6499
+ return this.data ?? [];
6500
+ }
6501
+ hasNextPage() {
6502
+ if (this.done === false) {
6503
+ return false;
6504
+ }
6505
+ return super.hasNextPage();
6506
+ }
6507
+ // @deprecated Please use `nextPageInfo()` instead
6508
+ nextPageParams() {
6509
+ const info = this.nextPageInfo();
6510
+ if (!info)
6511
+ return null;
6512
+ if ('params' in info)
6513
+ return info.params;
6514
+ const params = Object.fromEntries(info.url.searchParams);
6515
+ if (!Object.keys(params).length)
6516
+ return null;
6517
+ return params;
6518
+ }
6519
+ nextPageInfo() {
6520
+ const cursor = this.iterator;
6521
+ if (!cursor) {
6522
+ return null;
6523
+ }
6524
+ return {
6525
+ params: {
6526
+ iterator: cursor,
6527
+ },
6528
+ };
6529
+ }
6530
+ }
6491
6531
 
6492
6532
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6493
6533
  class APIResource {
@@ -6546,6 +6586,13 @@ class Brands extends APIResource {
6546
6586
  }
6547
6587
  }
6548
6588
 
6589
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6590
+ class CheckoutSessions extends APIResource {
6591
+ create(body, options) {
6592
+ return this._client.post('/checkouts', { body, ...options });
6593
+ }
6594
+ }
6595
+
6549
6596
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6550
6597
  let CustomerPortal$1 = class CustomerPortal extends APIResource {
6551
6598
  create(customerId, params = {}, options) {
@@ -6951,26 +6998,79 @@ Subscriptions.SubscriptionListResponsesDefaultPageNumberPagination =
6951
6998
  SubscriptionListResponsesDefaultPageNumberPagination;
6952
6999
 
6953
7000
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6954
- class WebhookEvents extends APIResource {
7001
+ let Headers$1 = class Headers extends APIResource {
7002
+ /**
7003
+ * Get a webhook by id
7004
+ */
7005
+ retrieve(webhookId, options) {
7006
+ return this._client.get(`/webhooks/${webhookId}/headers`, options);
7007
+ }
7008
+ /**
7009
+ * Patch a webhook by id
7010
+ */
7011
+ update(webhookId, body, options) {
7012
+ return this._client.patch(`/webhooks/${webhookId}/headers`, {
7013
+ body,
7014
+ ...options,
7015
+ headers: { Accept: '*/*', ...options?.headers },
7016
+ });
7017
+ }
7018
+ };
7019
+
7020
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
7021
+ let Webhooks$1 = class Webhooks extends APIResource {
7022
+ constructor() {
7023
+ super(...arguments);
7024
+ this.headers = new Headers$1(this._client);
7025
+ }
7026
+ /**
7027
+ * Create a new webhook
7028
+ */
7029
+ create(body, options) {
7030
+ return this._client.post('/webhooks', { body, ...options });
7031
+ }
7032
+ /**
7033
+ * Get a webhook by id
7034
+ */
7035
+ retrieve(webhookId, options) {
7036
+ return this._client.get(`/webhooks/${webhookId}`, options);
7037
+ }
6955
7038
  /**
6956
- * @deprecated
7039
+ * Patch a webhook by id
6957
7040
  */
6958
- retrieve(webhookEventId, options) {
6959
- return this._client.get(`/webhook_events/${webhookEventId}`, options);
7041
+ update(webhookId, body, options) {
7042
+ return this._client.patch(`/webhooks/${webhookId}`, { body, ...options });
6960
7043
  }
6961
7044
  list(query = {}, options) {
6962
7045
  if (isRequestOptions(query)) {
6963
7046
  return this.list({}, query);
6964
7047
  }
6965
- return this._client.getAPIList('/webhook_events', WebhookEventsDefaultPageNumberPagination, {
6966
- query,
7048
+ return this._client.getAPIList('/webhooks', WebhookDetailsCursorPagePagination, { query, ...options });
7049
+ }
7050
+ /**
7051
+ * Delete a webhook by id
7052
+ */
7053
+ delete(webhookId, options) {
7054
+ return this._client.delete(`/webhooks/${webhookId}`, {
6967
7055
  ...options,
7056
+ headers: { Accept: '*/*', ...options?.headers },
6968
7057
  });
6969
7058
  }
7059
+ /**
7060
+ * Get webhook secret by id
7061
+ */
7062
+ retrieveSecret(webhookId, options) {
7063
+ return this._client.get(`/webhooks/${webhookId}/secret`, options);
7064
+ }
7065
+ };
7066
+ class WebhookDetailsCursorPagePagination extends CursorPagePagination {
6970
7067
  }
6971
- class WebhookEventsDefaultPageNumberPagination extends DefaultPageNumberPagination {
7068
+ Webhooks$1.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
7069
+ Webhooks$1.Headers = Headers$1;
7070
+
7071
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
7072
+ class WebhookEvents extends APIResource {
6972
7073
  }
6973
- WebhookEvents.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
6974
7074
 
6975
7075
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6976
7076
  var _DodoPayments_instances, _a;
@@ -7017,6 +7117,7 @@ class DodoPayments extends APIClient {
7017
7117
  fetch: options.fetch,
7018
7118
  });
7019
7119
  _DodoPayments_instances.add(this);
7120
+ this.checkoutSessions = new CheckoutSessions(this);
7020
7121
  this.payments = new Payments(this);
7021
7122
  this.subscriptions = new Subscriptions(this);
7022
7123
  this.invoices = new Invoices(this);
@@ -7033,6 +7134,7 @@ class DodoPayments extends APIClient {
7033
7134
  this.discounts = new Discounts(this);
7034
7135
  this.addons = new Addons(this);
7035
7136
  this.brands = new Brands(this);
7137
+ this.webhooks = new Webhooks$1(this);
7036
7138
  this._options = options;
7037
7139
  this.bearerToken = bearerToken;
7038
7140
  }
@@ -7067,6 +7169,7 @@ DodoPayments.PermissionDeniedError = PermissionDeniedError;
7067
7169
  DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
7068
7170
  DodoPayments.toFile = toFile;
7069
7171
  DodoPayments.fileFromPath = fileFromPath;
7172
+ DodoPayments.CheckoutSessions = CheckoutSessions;
7070
7173
  DodoPayments.Payments = Payments;
7071
7174
  DodoPayments.PaymentListResponsesDefaultPageNumberPagination =
7072
7175
  PaymentListResponsesDefaultPageNumberPagination;
@@ -7089,7 +7192,6 @@ DodoPayments.DisputeListResponsesDefaultPageNumberPagination =
7089
7192
  DodoPayments.Payouts = Payouts;
7090
7193
  DodoPayments.PayoutListResponsesDefaultPageNumberPagination = PayoutListResponsesDefaultPageNumberPagination;
7091
7194
  DodoPayments.WebhookEvents = WebhookEvents;
7092
- DodoPayments.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
7093
7195
  DodoPayments.Products = Products;
7094
7196
  DodoPayments.ProductListResponsesDefaultPageNumberPagination =
7095
7197
  ProductListResponsesDefaultPageNumberPagination;
@@ -7099,7 +7201,20 @@ DodoPayments.DiscountsDefaultPageNumberPagination = DiscountsDefaultPageNumberPa
7099
7201
  DodoPayments.Addons = Addons;
7100
7202
  DodoPayments.AddonResponsesDefaultPageNumberPagination = AddonResponsesDefaultPageNumberPagination;
7101
7203
  DodoPayments.Brands = Brands;
7102
-
7204
+ DodoPayments.Webhooks = Webhooks$1;
7205
+ DodoPayments.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
7206
+
7207
+ var __assign = (undefined && undefined.__assign) || function () {
7208
+ __assign = Object.assign || function(t) {
7209
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
7210
+ s = arguments[i];
7211
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7212
+ t[p] = s[p];
7213
+ }
7214
+ return t;
7215
+ };
7216
+ return __assign.apply(this, arguments);
7217
+ };
7103
7218
  var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7104
7219
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7105
7220
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -7136,7 +7251,8 @@ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, b
7136
7251
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7137
7252
  }
7138
7253
  };
7139
- var checkoutQuerySchema = z.object({
7254
+ var checkoutQuerySchema = z
7255
+ .object({
7140
7256
  productId: z.string(),
7141
7257
  quantity: z.string().optional(),
7142
7258
  // Customer fields
@@ -7166,7 +7282,8 @@ var checkoutQuerySchema = z.object({
7166
7282
  showDiscounts: z.string().optional(),
7167
7283
  // Metadata (allow any key starting with metadata_)
7168
7284
  // We'll handle metadata separately in the handler
7169
- });
7285
+ })
7286
+ .catchall(z.unknown());
7170
7287
  // Add Zod schema for dynamic checkout body
7171
7288
  var dynamicCheckoutBodySchema = z
7172
7289
  .object({
@@ -7205,12 +7322,192 @@ var dynamicCheckoutBodySchema = z
7205
7322
  // Allow any additional fields (for future compatibility)
7206
7323
  })
7207
7324
  .catchall(z.unknown());
7325
+ // ========================================
7326
+ // CHECKOUT SESSIONS SCHEMAS & TYPES
7327
+ // ========================================
7328
+ // Product cart item schema for checkout sessions
7329
+ var checkoutSessionProductCartItemSchema = z.object({
7330
+ product_id: z.string().min(1, "Product ID is required"),
7331
+ quantity: z.number().int().positive("Quantity must be a positive integer"),
7332
+ });
7333
+ // Customer information schema for checkout sessions
7334
+ var checkoutSessionCustomerSchema = z
7335
+ .object({
7336
+ email: z.string().email().optional(),
7337
+ name: z.string().min(1).optional(),
7338
+ phone_number: z.string().optional(),
7339
+ })
7340
+ .optional();
7341
+ // Billing address schema for checkout sessions
7342
+ var checkoutSessionBillingAddressSchema = z
7343
+ .object({
7344
+ street: z.string().optional(),
7345
+ city: z.string().optional(),
7346
+ state: z.string().optional(),
7347
+ country: z.string().length(2, "Country must be a 2-letter ISO code"),
7348
+ zipcode: z.string().optional(),
7349
+ })
7350
+ .optional();
7351
+ // Payment method types enum based on Dodo Payments documentation
7352
+ var paymentMethodTypeSchema = z.enum([
7353
+ "credit",
7354
+ "debit",
7355
+ "upi_collect",
7356
+ "upi_intent",
7357
+ "apple_pay",
7358
+ "google_pay",
7359
+ "amazon_pay",
7360
+ "klarna",
7361
+ "affirm",
7362
+ "afterpay_clearpay",
7363
+ "sepa",
7364
+ "ach",
7365
+ ]);
7366
+ // Customization options schema
7367
+ var checkoutSessionCustomizationSchema = z
7368
+ .object({
7369
+ theme: z.enum(["light", "dark", "system"]).optional(),
7370
+ show_order_details: z.boolean().optional(),
7371
+ show_on_demand_tag: z.boolean().optional(),
7372
+ })
7373
+ .optional();
7374
+ // Feature flags schema
7375
+ var checkoutSessionFeatureFlagsSchema = z
7376
+ .object({
7377
+ allow_currency_selection: z.boolean().optional(),
7378
+ allow_discount_code: z.boolean().optional(),
7379
+ allow_phone_number_collection: z.boolean().optional(),
7380
+ allow_tax_id: z.boolean().optional(),
7381
+ always_create_new_customer: z.boolean().optional(),
7382
+ })
7383
+ .optional();
7384
+ // Subscription data schema
7385
+ var checkoutSessionSubscriptionDataSchema = z
7386
+ .object({
7387
+ trial_period_days: z.number().int().nonnegative().optional(),
7388
+ })
7389
+ .optional();
7390
+ // Main checkout session payload schema
7391
+ var checkoutSessionPayloadSchema = z.object({
7392
+ // Required fields
7393
+ product_cart: z
7394
+ .array(checkoutSessionProductCartItemSchema)
7395
+ .min(1, "At least one product is required"),
7396
+ // Optional fields
7397
+ customer: checkoutSessionCustomerSchema,
7398
+ billing_address: checkoutSessionBillingAddressSchema,
7399
+ return_url: z.string().url().optional(),
7400
+ allowed_payment_method_types: z.array(paymentMethodTypeSchema).optional(),
7401
+ billing_currency: z
7402
+ .string()
7403
+ .length(3, "Currency must be a 3-letter ISO code")
7404
+ .optional(),
7405
+ show_saved_payment_methods: z.boolean().optional(),
7406
+ confirm: z.boolean().optional(),
7407
+ discount_code: z.string().optional(),
7408
+ metadata: z.record(z.string(), z.string()).optional(),
7409
+ customization: checkoutSessionCustomizationSchema,
7410
+ feature_flags: checkoutSessionFeatureFlagsSchema,
7411
+ subscription_data: checkoutSessionSubscriptionDataSchema,
7412
+ });
7413
+ // Checkout session response schema
7414
+ var checkoutSessionResponseSchema = z.object({
7415
+ session_id: z.string().min(1, "Session ID is required"),
7416
+ checkout_url: z.string().url("Invalid checkout URL"),
7417
+ });
7418
+ /**
7419
+ * Creates a new Dodo Payments Checkout Session using the modern /checkouts endpoint.
7420
+ * This function provides a clean, type-safe interface to the Checkout Sessions API.
7421
+ *
7422
+ * @param payload - The checkout session data, validated against CheckoutSessionPayloadSchema
7423
+ * @param config - Dodo Payments client configuration (bearerToken, environment)
7424
+ * @returns Promise<CheckoutSessionResponse> - The checkout session with session_id and checkout_url
7425
+ *
7426
+ * @throws {Error} When payload validation fails or API request fails
7427
+ *
7428
+ * @example
7429
+ * ```typescript
7430
+ * const session = await createCheckoutSession({
7431
+ * product_cart: [{ product_id: 'prod_123', quantity: 1 }],
7432
+ * customer: { email: 'customer@example.com' },
7433
+ * return_url: 'https://yoursite.com/success'
7434
+ * }, {
7435
+ * bearerToken: process.env.DODO_PAYMENTS_API_KEY,
7436
+ * environment: 'test_mode'
7437
+ * });
7438
+ *
7439
+ * ```
7440
+ */
7441
+ var createCheckoutSession = function (payload, config) { return __awaiter$1(void 0, void 0, void 0, function () {
7442
+ var validation, dodopayments, sdkPayload, session, responseValidation, error_1;
7443
+ return __generator$1(this, function (_a) {
7444
+ switch (_a.label) {
7445
+ case 0:
7446
+ validation = checkoutSessionPayloadSchema.safeParse(payload);
7447
+ if (!validation.success) {
7448
+ throw new Error("Invalid checkout session payload: ".concat(validation.error.issues
7449
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
7450
+ .join(", ")));
7451
+ }
7452
+ dodopayments = new DodoPayments({
7453
+ bearerToken: config.bearerToken,
7454
+ environment: config.environment,
7455
+ });
7456
+ _a.label = 1;
7457
+ case 1:
7458
+ _a.trys.push([1, 3, , 4]);
7459
+ sdkPayload = __assign(__assign({}, validation.data), (validation.data.billing_address && {
7460
+ billing_address: __assign(__assign({}, validation.data.billing_address), { country: validation.data.billing_address.country }),
7461
+ }));
7462
+ return [4 /*yield*/, dodopayments.checkoutSessions.create(sdkPayload)];
7463
+ case 2:
7464
+ session = _a.sent();
7465
+ responseValidation = checkoutSessionResponseSchema.safeParse(session);
7466
+ if (!responseValidation.success) {
7467
+ throw new Error("Invalid checkout session response from API: ".concat(responseValidation.error.issues
7468
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
7469
+ .join(", ")));
7470
+ }
7471
+ return [2 /*return*/, responseValidation.data];
7472
+ case 3:
7473
+ error_1 = _a.sent();
7474
+ if (error_1 instanceof Error) {
7475
+ console.error("Dodo Payments Checkout Session API Error:", {
7476
+ message: error_1.message,
7477
+ payload: validation.data,
7478
+ config: {
7479
+ environment: config.environment,
7480
+ hasBearerToken: !!config.bearerToken,
7481
+ },
7482
+ });
7483
+ // Re-throw with a more user-friendly message
7484
+ throw new Error("Failed to create checkout session: ".concat(error_1.message));
7485
+ }
7486
+ // Handle non-Error objects
7487
+ console.error("Unknown error creating checkout session:", error_1);
7488
+ throw new Error("Failed to create checkout session due to an unknown error");
7489
+ case 4: return [2 /*return*/];
7490
+ }
7491
+ });
7492
+ }); };
7208
7493
  var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
7209
- 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;
7210
- 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;
7494
+ 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;
7495
+ 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;
7211
7496
  return __generator$1(this, function (_g) {
7212
7497
  switch (_g.label) {
7213
7498
  case 0:
7499
+ if (!(type === "session")) return [3 /*break*/, 2];
7500
+ if (!sessionPayload) {
7501
+ throw new Error("sessionPayload is required when type is 'session'");
7502
+ }
7503
+ return [4 /*yield*/, createCheckoutSession(sessionPayload, {
7504
+ bearerToken: bearerToken,
7505
+ environment: environment,
7506
+ })];
7507
+ case 1:
7508
+ session = _g.sent();
7509
+ return [2 /*return*/, session.checkout_url];
7510
+ case 2:
7214
7511
  inputData = type === "dynamic" ? body : queryParams;
7215
7512
  if (type === "dynamic") {
7216
7513
  parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
@@ -7222,7 +7519,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
7222
7519
  if (!success) {
7223
7520
  throw new Error("Invalid ".concat(type === "dynamic" ? "body" : "query parameters", ".\n ").concat(error.message));
7224
7521
  }
7225
- if (!(type !== "dynamic")) return [3 /*break*/, 5];
7522
+ if (!(type !== "dynamic")) return [3 /*break*/, 7];
7226
7523
  _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;
7227
7524
  dodopayments_1 = new DodoPayments({
7228
7525
  bearerToken: bearerToken,
@@ -7231,18 +7528,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
7231
7528
  // Check that the product exists for this merchant
7232
7529
  if (!productId)
7233
7530
  throw new Error("Missing required field: productId");
7234
- _g.label = 1;
7235
- case 1:
7236
- _g.trys.push([1, 3, , 4]);
7531
+ _g.label = 3;
7532
+ case 3:
7533
+ _g.trys.push([3, 5, , 6]);
7237
7534
  return [4 /*yield*/, dodopayments_1.products.retrieve(productId)];
7238
- case 2:
7535
+ case 4:
7239
7536
  _g.sent();
7240
- return [3 /*break*/, 4];
7241
- case 3:
7537
+ return [3 /*break*/, 6];
7538
+ case 5:
7242
7539
  err_1 = _g.sent();
7243
7540
  console.error(err_1);
7244
7541
  throw new Error("Product not found");
7245
- case 4:
7542
+ case 6:
7246
7543
  url = new URL("".concat(environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com", "/buy/").concat(productId));
7247
7544
  url.searchParams.set("quantity", quantity_1 ? String(quantity_1) : "1");
7248
7545
  if (returnUrl)
@@ -7302,7 +7599,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
7302
7599
  }
7303
7600
  }
7304
7601
  return [2 /*return*/, url.toString()];
7305
- case 5:
7602
+ case 7:
7306
7603
  dyn = data;
7307
7604
  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;
7308
7605
  dodopayments = new DodoPayments({
@@ -7316,18 +7613,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
7316
7613
  }
7317
7614
  if (!productIdToFetch)
7318
7615
  throw new Error("Missing required field: product_id or product_cart[0].product_id");
7319
- _g.label = 6;
7320
- case 6:
7321
- _g.trys.push([6, 8, , 9]);
7616
+ _g.label = 8;
7617
+ case 8:
7618
+ _g.trys.push([8, 10, , 11]);
7322
7619
  return [4 /*yield*/, dodopayments.products.retrieve(productIdToFetch)];
7323
- case 7:
7620
+ case 9:
7324
7621
  product = _g.sent();
7325
- return [3 /*break*/, 9];
7326
- case 8:
7622
+ return [3 /*break*/, 11];
7623
+ case 10:
7327
7624
  err_2 = _g.sent();
7328
7625
  console.error(err_2);
7329
7626
  throw new Error("Product not found");
7330
- case 9:
7627
+ case 11:
7331
7628
  isSubscription = Boolean(product.is_recurring);
7332
7629
  // Required field validation
7333
7630
  if (isSubscription && !product_id)
@@ -7336,7 +7633,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
7336
7633
  throw new Error("Missing required field: billing");
7337
7634
  if (!customer)
7338
7635
  throw new Error("Missing required field: customer");
7339
- if (!isSubscription) return [3 /*break*/, 14];
7636
+ if (!isSubscription) return [3 /*break*/, 16];
7340
7637
  subscriptionPayload = {
7341
7638
  billing: billing,
7342
7639
  customer: customer,
@@ -7372,24 +7669,24 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
7372
7669
  if (trial_period_days)
7373
7670
  subscriptionPayload.trial_period_days = trial_period_days;
7374
7671
  subscription = void 0;
7375
- _g.label = 10;
7376
- case 10:
7377
- _g.trys.push([10, 12, , 13]);
7672
+ _g.label = 12;
7673
+ case 12:
7674
+ _g.trys.push([12, 14, , 15]);
7378
7675
  return [4 /*yield*/, dodopayments.subscriptions.create(subscriptionPayload)];
7379
- case 11:
7676
+ case 13:
7380
7677
  subscription =
7381
7678
  _g.sent();
7382
- return [3 /*break*/, 13];
7383
- case 12:
7679
+ return [3 /*break*/, 15];
7680
+ case 14:
7384
7681
  err_3 = _g.sent();
7385
7682
  console.error("Error when creating subscription", err_3);
7386
7683
  throw new Error(err_3 instanceof Error ? err_3.message : String(err_3));
7387
- case 13:
7684
+ case 15:
7388
7685
  if (!subscription || !subscription.payment_link) {
7389
7686
  throw new Error("No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload");
7390
7687
  }
7391
7688
  return [2 /*return*/, subscription.payment_link];
7392
- case 14:
7689
+ case 16:
7393
7690
  cart = product_cart;
7394
7691
  if (!cart && product_id) {
7395
7692
  cart = [
@@ -7425,18 +7722,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
7425
7722
  if (tax_id)
7426
7723
  paymentPayload.tax_id = tax_id;
7427
7724
  payment = void 0;
7428
- _g.label = 15;
7429
- case 15:
7430
- _g.trys.push([15, 17, , 18]);
7725
+ _g.label = 17;
7726
+ case 17:
7727
+ _g.trys.push([17, 19, , 20]);
7431
7728
  return [4 /*yield*/, dodopayments.payments.create(paymentPayload)];
7432
- case 16:
7729
+ case 18:
7433
7730
  payment = _g.sent();
7434
- return [3 /*break*/, 18];
7435
- case 17:
7731
+ return [3 /*break*/, 20];
7732
+ case 19:
7436
7733
  err_4 = _g.sent();
7437
7734
  console.error("Error when creating payment link", err_4);
7438
7735
  throw new Error(err_4 instanceof Error ? err_4.message : String(err_4));
7439
- case 18:
7736
+ case 20:
7440
7737
  if (!payment || !payment.payment_link) {
7441
7738
  throw new Error("No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload.");
7442
7739
  }
@@ -7472,7 +7769,7 @@ const Checkout = (config) => {
7472
7769
  catch (error) {
7473
7770
  return new serverExports.NextResponse(error.message, { status: 400 });
7474
7771
  }
7475
- return serverExports.NextResponse.redirect(url);
7772
+ return serverExports.NextResponse.json({ checkout_url: url });
7476
7773
  };
7477
7774
  const postHandler = async (req) => {
7478
7775
  let body;
@@ -7482,20 +7779,48 @@ const Checkout = (config) => {
7482
7779
  catch (e) {
7483
7780
  return new serverExports.NextResponse("Invalid JSON body", { status: 400 });
7484
7781
  }
7485
- const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
7486
- if (!success) {
7487
- return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
7488
- status: 400,
7489
- });
7490
- }
7491
- let url = "";
7492
- try {
7493
- url = await buildCheckoutUrl({ body: data, ...config, type: "dynamic" });
7782
+ if (config.type === "dynamic") {
7783
+ // Handle dynamic checkout
7784
+ const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
7785
+ if (!success) {
7786
+ return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
7787
+ status: 400,
7788
+ });
7789
+ }
7790
+ let url = "";
7791
+ try {
7792
+ url = await buildCheckoutUrl({
7793
+ body: data,
7794
+ ...config,
7795
+ type: "dynamic",
7796
+ });
7797
+ }
7798
+ catch (error) {
7799
+ return new serverExports.NextResponse(error.message, { status: 400 });
7800
+ }
7801
+ return serverExports.NextResponse.json({ checkout_url: url });
7494
7802
  }
7495
- catch (error) {
7496
- return new serverExports.NextResponse(error.message, { status: 400 });
7803
+ else {
7804
+ // Handle checkout session
7805
+ const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
7806
+ if (!success) {
7807
+ return new serverExports.NextResponse(`Invalid checkout session payload.\n ${error.message}`, {
7808
+ status: 400,
7809
+ });
7810
+ }
7811
+ let url = "";
7812
+ try {
7813
+ url = await buildCheckoutUrl({
7814
+ sessionPayload: data,
7815
+ ...config,
7816
+ type: "session",
7817
+ });
7818
+ }
7819
+ catch (error) {
7820
+ return new serverExports.NextResponse(error.message, { status: 400 });
7821
+ }
7822
+ return serverExports.NextResponse.json({ checkout_url: url });
7497
7823
  }
7498
- return serverExports.NextResponse.redirect(url);
7499
7824
  };
7500
7825
  return (req) => {
7501
7826
  if (req.method === "POST") {