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