dodopayments-mcp 2.32.2 → 2.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -2
- package/local-docs-search.d.mts.map +1 -1
- package/local-docs-search.d.ts.map +1 -1
- package/local-docs-search.js +28 -18
- package/local-docs-search.js.map +1 -1
- package/local-docs-search.mjs +28 -18
- package/local-docs-search.mjs.map +1 -1
- package/package.json +2 -2
- package/server.js +1 -1
- package/server.mjs +1 -1
- package/src/local-docs-search.ts +28 -18
- package/src/server.ts +1 -1
package/local-docs-search.js
CHANGED
|
@@ -377,8 +377,8 @@ const EMBEDDED_METHODS = [
|
|
|
377
377
|
stainlessPath: '(resource) payments > (method) retrieve',
|
|
378
378
|
qualified: 'client.payments.retrieve',
|
|
379
379
|
params: ['payment_id: string;'],
|
|
380
|
-
response: "{ billing: object; brand_id: string; business_id: string; created_at: string; currency: string; customer: object; digital_products_delivered: boolean; disputes: object[]; metadata: object; payment_id: string; refunds: object[]; settlement_amount: number; settlement_currency: string; total_amount: number; card_holder_name?: string; card_issuing_country?: string; card_last_four?: string; card_network?: string; card_type?: string; checkout_session_id?: string; custom_field_responses?: object[]; discount_id?: string; discounts?: object[]; error_code?: string; error_message?: string; invoice_id?: string; invoice_url?: string; payment_link?: string; payment_method?: string; payment_method_type?: string; product_cart?: { product_id: string; quantity: number; }[]; refund_status?: 'partial' | 'full'; settlement_tax?: number; status?: string; subscription_id?: string; tax?: number; updated_at?: string; }",
|
|
381
|
-
markdown: "## retrieve\n\n`client.payments.retrieve(payment_id: string): { billing: billing_address; brand_id: string; business_id: string; created_at: string; currency: currency; customer: customer_limited_details; digital_products_delivered: boolean; disputes: dispute[]; metadata: object; payment_id: string; refunds: refund_list_item[]; settlement_amount: number; settlement_currency: currency; total_amount: number; card_holder_name?: string; card_issuing_country?: country_code; card_last_four?: string; card_network?: string; card_type?: string; checkout_session_id?: string; custom_field_responses?: custom_field_response[]; discount_id?: string; discounts?: discount_detail[]; error_code?: string; error_message?: string; invoice_id?: string; invoice_url?: string; payment_link?: string; payment_method?: string; payment_method_type?: string; product_cart?: object[]; refund_status?: payment_refund_status; settlement_tax?: number; status?: intent_status; subscription_id?: string; tax?: number; updated_at?: string; }`\n\n**get** `/payments/{payment_id}`\n\n### Parameters\n\n- `payment_id: string`\n\n### Returns\n\n- `{ billing: { country: country_code; city?: string; state?: string; street?: string; zipcode?: string; }; brand_id: string; business_id: string; created_at: string; currency: string; customer: { customer_id: string; email: string; name: string; metadata?: object; phone_number?: string; }; digital_products_delivered: boolean; disputes: { amount: string; business_id: string; created_at: string; currency: string; dispute_id: string; dispute_stage: dispute_stage; dispute_status: dispute_status; payment_id: string; is_resolved_by_rdr?: boolean; remarks?: string; }[]; metadata: object; payment_id: string; refunds: { business_id: string; created_at: string; is_partial: boolean; payment_id: string; refund_id: string; status: refund_status; amount?: number; currency?: currency; reason?: string; }[]; settlement_amount: number; settlement_currency: string; total_amount: number; card_holder_name?: string; card_issuing_country?: string; card_last_four?: string; card_network?: string; card_type?: string; checkout_session_id?: string; custom_field_responses?: { key: string; value: string; }[]; discount_id?: string; discounts?: { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; position: number; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; cycles_remaining?: number; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }[]; error_code?: string; error_message?: string; invoice_id?: string; invoice_url?: string; payment_link?: string; payment_method?: string; payment_method_type?: string; product_cart?: { product_id: string; quantity: number; }[]; refund_status?: 'partial' | 'full'; settlement_tax?: number; status?: string; subscription_id?: string; tax?: number; updated_at?: string; }`\n\n - `billing: { country: string; city?: string; state?: string; street?: string; zipcode?: string; }`\n - `brand_id: string`\n - `business_id: string`\n - `created_at: string`\n - `currency: string`\n - `customer: { customer_id: string; email: string; name: string; metadata?: object; phone_number?: string; }`\n - `digital_products_delivered: boolean`\n - `disputes: { amount: string; business_id: string; created_at: string; currency: string; dispute_id: string; dispute_stage: 'pre_dispute' | 'dispute' | 'pre_arbitration'; dispute_status: string; payment_id: string; is_resolved_by_rdr?: boolean; remarks?: string; }[]`\n - `metadata: object`\n - `payment_id: string`\n - `refunds: { business_id: string; created_at: string; is_partial: boolean; payment_id: string; refund_id: string; status: 'succeeded' | 'failed' | 'pending' | 'review'; amount?: number; currency?: string; reason?: string; }[]`\n - `settlement_amount: number`\n - `settlement_currency: string`\n - `total_amount: number`\n - `card_holder_name?: string`\n - `card_issuing_country?: string`\n - `card_last_four?: string`\n - `card_network?: string`\n - `card_type?: string`\n - `checkout_session_id?: string`\n - `custom_field_responses?: { key: string; value: string; }[]`\n - `discount_id?: string`\n - `discounts?: { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; position: number; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; cycles_remaining?: number; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }[]`\n - `error_code?: string`\n - `error_message?: string`\n - `invoice_id?: string`\n - `invoice_url?: string`\n - `payment_link?: string`\n - `payment_method?: string`\n - `payment_method_type?: string`\n - `product_cart?: { product_id: string; quantity: number; }[]`\n - `refund_status?: 'partial' | 'full'`\n - `settlement_tax?: number`\n - `status?: string`\n - `subscription_id?: string`\n - `tax?: number`\n - `updated_at?: string`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst payment = await client.payments.retrieve('payment_id');\n\nconsole.log(payment);\n```",
|
|
380
|
+
response: "{ billing: object; brand_id: string; business_id: string; created_at: string; currency: string; customer: object; digital_products_delivered: boolean; disputes: object[]; metadata: object; payment_id: string; refunds: object[]; retry_attempt: number; settlement_amount: number; settlement_currency: string; total_amount: number; card_holder_name?: string; card_issuing_country?: string; card_last_four?: string; card_network?: string; card_type?: string; checkout_session_id?: string; custom_field_responses?: object[]; discount_id?: string; discounts?: object[]; error_code?: string; error_message?: string; invoice_id?: string; invoice_url?: string; payment_link?: string; payment_method?: string; payment_method_type?: string; product_cart?: { product_id: string; quantity: number; }[]; refund_status?: 'partial' | 'full'; settlement_tax?: number; status?: string; subscription_id?: string; tax?: number; updated_at?: string; }",
|
|
381
|
+
markdown: "## retrieve\n\n`client.payments.retrieve(payment_id: string): { billing: billing_address; brand_id: string; business_id: string; created_at: string; currency: currency; customer: customer_limited_details; digital_products_delivered: boolean; disputes: dispute[]; metadata: object; payment_id: string; refunds: refund_list_item[]; retry_attempt: number; settlement_amount: number; settlement_currency: currency; total_amount: number; card_holder_name?: string; card_issuing_country?: country_code; card_last_four?: string; card_network?: string; card_type?: string; checkout_session_id?: string; custom_field_responses?: custom_field_response[]; discount_id?: string; discounts?: discount_detail[]; error_code?: string; error_message?: string; invoice_id?: string; invoice_url?: string; payment_link?: string; payment_method?: string; payment_method_type?: string; product_cart?: object[]; refund_status?: payment_refund_status; settlement_tax?: number; status?: intent_status; subscription_id?: string; tax?: number; updated_at?: string; }`\n\n**get** `/payments/{payment_id}`\n\n### Parameters\n\n- `payment_id: string`\n\n### Returns\n\n- `{ billing: { country: country_code; city?: string; state?: string; street?: string; zipcode?: string; }; brand_id: string; business_id: string; created_at: string; currency: string; customer: { customer_id: string; email: string; name: string; metadata?: object; phone_number?: string; }; digital_products_delivered: boolean; disputes: { amount: string; business_id: string; created_at: string; currency: string; dispute_id: string; dispute_stage: dispute_stage; dispute_status: dispute_status; payment_id: string; is_resolved_by_rdr?: boolean; remarks?: string; }[]; metadata: object; payment_id: string; refunds: { business_id: string; created_at: string; is_partial: boolean; payment_id: string; refund_id: string; status: refund_status; amount?: number; currency?: currency; reason?: string; }[]; retry_attempt: number; settlement_amount: number; settlement_currency: string; total_amount: number; card_holder_name?: string; card_issuing_country?: string; card_last_four?: string; card_network?: string; card_type?: string; checkout_session_id?: string; custom_field_responses?: { key: string; value: string; }[]; discount_id?: string; discounts?: { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; position: number; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; cycles_remaining?: number; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }[]; error_code?: string; error_message?: string; invoice_id?: string; invoice_url?: string; payment_link?: string; payment_method?: string; payment_method_type?: string; product_cart?: { product_id: string; quantity: number; }[]; refund_status?: 'partial' | 'full'; settlement_tax?: number; status?: string; subscription_id?: string; tax?: number; updated_at?: string; }`\n\n - `billing: { country: string; city?: string; state?: string; street?: string; zipcode?: string; }`\n - `brand_id: string`\n - `business_id: string`\n - `created_at: string`\n - `currency: string`\n - `customer: { customer_id: string; email: string; name: string; metadata?: object; phone_number?: string; }`\n - `digital_products_delivered: boolean`\n - `disputes: { amount: string; business_id: string; created_at: string; currency: string; dispute_id: string; dispute_stage: 'pre_dispute' | 'dispute' | 'pre_arbitration'; dispute_status: string; payment_id: string; is_resolved_by_rdr?: boolean; remarks?: string; }[]`\n - `metadata: object`\n - `payment_id: string`\n - `refunds: { business_id: string; created_at: string; is_partial: boolean; payment_id: string; refund_id: string; status: 'succeeded' | 'failed' | 'pending' | 'review'; amount?: number; currency?: string; reason?: string; }[]`\n - `retry_attempt: number`\n - `settlement_amount: number`\n - `settlement_currency: string`\n - `total_amount: number`\n - `card_holder_name?: string`\n - `card_issuing_country?: string`\n - `card_last_four?: string`\n - `card_network?: string`\n - `card_type?: string`\n - `checkout_session_id?: string`\n - `custom_field_responses?: { key: string; value: string; }[]`\n - `discount_id?: string`\n - `discounts?: { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; position: number; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; cycles_remaining?: number; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }[]`\n - `error_code?: string`\n - `error_message?: string`\n - `invoice_id?: string`\n - `invoice_url?: string`\n - `payment_link?: string`\n - `payment_method?: string`\n - `payment_method_type?: string`\n - `product_cart?: { product_id: string; quantity: number; }[]`\n - `refund_status?: 'partial' | 'full'`\n - `settlement_tax?: number`\n - `status?: string`\n - `subscription_id?: string`\n - `tax?: number`\n - `updated_at?: string`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst payment = await client.payments.retrieve('payment_id');\n\nconsole.log(payment);\n```",
|
|
382
382
|
perLanguage: {
|
|
383
383
|
typescript: {
|
|
384
384
|
method: 'client.payments.retrieve',
|
|
@@ -3413,7 +3413,7 @@ const EMBEDDED_METHODS = [
|
|
|
3413
3413
|
'product_id?: string;',
|
|
3414
3414
|
],
|
|
3415
3415
|
response: "{ amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }",
|
|
3416
|
-
markdown: "## list\n\n`client.discounts.list(active?: boolean, code?: string, discount_type?: 'percentage', page_number?: number, page_size?: number, product_id?: string): { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n**get** `/discounts`\n\nGET /discounts\n\n### Parameters\n\n- `active?: boolean`\n Filter by active status (true = not expired, false = expired)\n\n- `code?: string`\n Filter by discount code (partial match, case-insensitive)\n\n- `discount_type?: 'percentage'`\n Filter by discount type
|
|
3416
|
+
markdown: "## list\n\n`client.discounts.list(active?: boolean, code?: string, discount_type?: 'percentage', page_number?: number, page_size?: number, product_id?: string): { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n**get** `/discounts`\n\nGET /discounts\n\n### Parameters\n\n- `active?: boolean`\n Filter by active status (true = not expired, false = expired)\n\n- `code?: string`\n Filter by discount code (partial match, case-insensitive)\n\n- `discount_type?: 'percentage'`\n Filter by discount type\n\n- `page_number?: number`\n Page number (default = 0).\n\n- `page_size?: number`\n Page size (default = 10, max = 100).\n\n- `product_id?: string`\n Filter by product restriction (only discounts that apply to this product)\n\n### Returns\n\n- `{ amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n - `amount: number`\n - `business_id: string`\n - `code: string`\n - `created_at: string`\n - `discount_id: string`\n - `metadata: object`\n - `preserve_on_plan_change: boolean`\n - `restricted_to: string[]`\n - `times_used: number`\n - `type: 'percentage'`\n - `expires_at?: string`\n - `name?: string`\n - `subscription_cycles?: number`\n - `usage_limit?: number`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\n// Automatically fetches more pages as needed.\nfor await (const discount of client.discounts.list()) {\n console.log(discount);\n}\n```",
|
|
3417
3417
|
perLanguage: {
|
|
3418
3418
|
typescript: {
|
|
3419
3419
|
method: 'client.discounts.list',
|
|
@@ -3473,7 +3473,7 @@ const EMBEDDED_METHODS = [
|
|
|
3473
3473
|
'usage_limit?: number;',
|
|
3474
3474
|
],
|
|
3475
3475
|
response: "{ amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }",
|
|
3476
|
-
markdown: "## create\n\n`client.discounts.create(amount: number, type: 'percentage', code?: string, expires_at?: string, metadata?: object, name?: string, preserve_on_plan_change?: boolean, restricted_to?: string[], subscription_cycles?: number, usage_limit?: number): { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n**post** `/discounts`\n\nPOST /discounts\nIf `code` is omitted or empty, a random 16-char uppercase code is generated.\n\n### Parameters\n\n- `amount: number`\n The discount amount
|
|
3476
|
+
markdown: "## create\n\n`client.discounts.create(amount: number, type: 'percentage', code?: string, expires_at?: string, metadata?: object, name?: string, preserve_on_plan_change?: boolean, restricted_to?: string[], subscription_cycles?: number, usage_limit?: number): { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n**post** `/discounts`\n\nPOST /discounts\nIf `code` is omitted or empty, a random 16-char uppercase code is generated.\n\n### Parameters\n\n- `amount: number`\n The discount amount in **basis points** (e.g. `540` means `5.4%`, `10000` means `100%`).\n\nMust be at least 1.\n\n- `type: 'percentage'`\n The discount type. Currently only `percentage` is supported.\n\n- `code?: string`\n Optionally supply a code (will be uppercased).\n- Must be at least 3 characters if provided.\n- If omitted, a random 16-character code is generated.\n\n- `expires_at?: string`\n When the discount expires, if ever.\n\n- `metadata?: object`\n Additional metadata for the discount\n\n- `name?: string`\n\n- `preserve_on_plan_change?: boolean`\n Whether this discount should be preserved when a subscription changes plans.\nDefault: false (discount is removed on plan change)\n\n- `restricted_to?: string[]`\n List of product IDs to restrict usage (if any).\n\n- `subscription_cycles?: number`\n Number of subscription billing cycles this discount is valid for.\nIf not provided, the discount will be applied indefinitely to\nall recurring payments related to the subscription.\n\n- `usage_limit?: number`\n How many times this discount can be used (if any).\nMust be >= 1 if provided.\n\n### Returns\n\n- `{ amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n - `amount: number`\n - `business_id: string`\n - `code: string`\n - `created_at: string`\n - `discount_id: string`\n - `metadata: object`\n - `preserve_on_plan_change: boolean`\n - `restricted_to: string[]`\n - `times_used: number`\n - `type: 'percentage'`\n - `expires_at?: string`\n - `name?: string`\n - `subscription_cycles?: number`\n - `usage_limit?: number`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst discount = await client.discounts.create({ amount: 0, type: 'percentage' });\n\nconsole.log(discount);\n```",
|
|
3477
3477
|
perLanguage: {
|
|
3478
3478
|
typescript: {
|
|
3479
3479
|
method: 'client.discounts.create',
|
|
@@ -3631,7 +3631,7 @@ const EMBEDDED_METHODS = [
|
|
|
3631
3631
|
'usage_limit?: number;',
|
|
3632
3632
|
],
|
|
3633
3633
|
response: "{ amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }",
|
|
3634
|
-
markdown: "## update\n\n`client.discounts.update(discount_id: string, amount?: number, code?: string, expires_at?: string, metadata?: object, name?: string, preserve_on_plan_change?: boolean, restricted_to?: string[], subscription_cycles?: number, type?: 'percentage', usage_limit?: number): { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n**patch** `/discounts/{discount_id}`\n\nPATCH /discounts/{discount_id}\n\n### Parameters\n\n- `discount_id: string`\n\n- `amount?: number`\n If present, update the discount amount
|
|
3634
|
+
markdown: "## update\n\n`client.discounts.update(discount_id: string, amount?: number, code?: string, expires_at?: string, metadata?: object, name?: string, preserve_on_plan_change?: boolean, restricted_to?: string[], subscription_cycles?: number, type?: 'percentage', usage_limit?: number): { amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: discount_type; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n**patch** `/discounts/{discount_id}`\n\nPATCH /discounts/{discount_id}\n\n### Parameters\n\n- `discount_id: string`\n\n- `amount?: number`\n If present, update the discount amount in **basis points** (e.g., `540` = `5.4%`, `10000` = `100%`).\n\nMust be at least 1 if provided.\n\n- `code?: string`\n If present, update the discount code (uppercase).\n\n- `expires_at?: string`\n\n- `metadata?: object`\n Additional metadata for the discount\n\n- `name?: string`\n\n- `preserve_on_plan_change?: boolean`\n Whether this discount should be preserved when a subscription changes plans.\nIf not provided, the existing value is kept.\n\n- `restricted_to?: string[]`\n If present, replaces all restricted product IDs with this new set.\nTo remove all restrictions, send empty array\n\n- `subscription_cycles?: number`\n Number of subscription billing cycles this discount is valid for.\nIf not provided, the discount will be applied indefinitely to\nall recurring payments related to the subscription.\n\n- `type?: 'percentage'`\n If present, update the discount type. Currently only `percentage` is supported.\n\n- `usage_limit?: number`\n\n### Returns\n\n- `{ amount: number; business_id: string; code: string; created_at: string; discount_id: string; metadata: object; preserve_on_plan_change: boolean; restricted_to: string[]; times_used: number; type: 'percentage'; expires_at?: string; name?: string; subscription_cycles?: number; usage_limit?: number; }`\n\n - `amount: number`\n - `business_id: string`\n - `code: string`\n - `created_at: string`\n - `discount_id: string`\n - `metadata: object`\n - `preserve_on_plan_change: boolean`\n - `restricted_to: string[]`\n - `times_used: number`\n - `type: 'percentage'`\n - `expires_at?: string`\n - `name?: string`\n - `subscription_cycles?: number`\n - `usage_limit?: number`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst discount = await client.discounts.update('discount_id');\n\nconsole.log(discount);\n```",
|
|
3635
3635
|
perLanguage: {
|
|
3636
3636
|
typescript: {
|
|
3637
3637
|
method: 'client.discounts.update',
|
|
@@ -6307,9 +6307,14 @@ const EMBEDDED_METHODS = [
|
|
|
6307
6307
|
'name: string;',
|
|
6308
6308
|
'brand_id?: string;',
|
|
6309
6309
|
'description?: string;',
|
|
6310
|
+
"effective_at_on_downgrade?: 'immediately' | 'next_billing_date';",
|
|
6311
|
+
"effective_at_on_upgrade?: 'immediately' | 'next_billing_date';",
|
|
6312
|
+
"on_payment_failure?: 'prevent_change' | 'apply_change';",
|
|
6313
|
+
"proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill';",
|
|
6314
|
+
"proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill';",
|
|
6310
6315
|
],
|
|
6311
|
-
response:
|
|
6312
|
-
markdown: "## create\n\n`client.productCollections.create(groups: { products: group_product[]; group_name?: string; status?: boolean; }[], name: string, brand_id?: string, description?: string): { id: string; brand_id: string; created_at: string; groups: product_collection_group_response[]; name: string; updated_at: string; description?: string; image?: string; }`\n\n**post** `/product-collections`\n\n### Parameters\n\n- `groups: { products: { product_id: string; status?: boolean; }[]; group_name?: string; status?: boolean; }[]`\n Groups of products in this collection\n\n- `name: string`\n Name of the product collection\n\n- `brand_id?: string`\n Brand id for the collection, if not provided will default to primary brand\n\n- `description?: string`\n Optional description of the product collection\n\n### Returns\n\n- `{ id: string; brand_id: string; created_at: string; groups: { group_id: string; products: product_collection_product[]; status: boolean; group_name?: string; }[]; name: string; updated_at: string; description?: string; image?: string; }`\n\n - `id: string`\n - `brand_id: string`\n - `created_at: string`\n - `groups: { group_id: string; products: { id: string; addons_count: number; files_count: number; has_credit_entitlements: boolean; is_recurring: boolean; license_key_enabled: boolean; meters_count: number; product_id: string; status: boolean; currency?: currency; description?: string; name?: string; price?: number; price_detail?: price; tax_category?: tax_category; tax_inclusive?: boolean; }[]; status: boolean; group_name?: string; }[]`\n - `name: string`\n - `updated_at: string`\n - `description?: string`\n - `image?: string`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst productCollection = await client.productCollections.create({ groups: [{ products: [{ product_id: 'product_id' }] }], name: 'name' });\n\nconsole.log(productCollection);\n```",
|
|
6316
|
+
response: "{ id: string; brand_id: string; created_at: string; groups: { group_id: string; products: product_collection_product[]; status: boolean; group_name?: string; }[]; name: string; updated_at: string; description?: string; effective_at_on_downgrade?: 'immediately' | 'next_billing_date'; effective_at_on_upgrade?: 'immediately' | 'next_billing_date'; image?: string; on_payment_failure?: 'prevent_change' | 'apply_change'; proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; }",
|
|
6317
|
+
markdown: "## create\n\n`client.productCollections.create(groups: { products: group_product[]; group_name?: string; status?: boolean; }[], name: string, brand_id?: string, description?: string, effective_at_on_downgrade?: 'immediately' | 'next_billing_date', effective_at_on_upgrade?: 'immediately' | 'next_billing_date', on_payment_failure?: 'prevent_change' | 'apply_change', proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill', proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'): { id: string; brand_id: string; created_at: string; groups: product_collection_group_response[]; name: string; updated_at: string; description?: string; effective_at_on_downgrade?: 'immediately' | 'next_billing_date'; effective_at_on_upgrade?: 'immediately' | 'next_billing_date'; image?: string; on_payment_failure?: 'prevent_change' | 'apply_change'; proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; }`\n\n**post** `/product-collections`\n\n### Parameters\n\n- `groups: { products: { product_id: string; status?: boolean; }[]; group_name?: string; status?: boolean; }[]`\n Groups of products in this collection\n\n- `name: string`\n Name of the product collection\n\n- `brand_id?: string`\n Brand id for the collection, if not provided will default to primary brand\n\n- `description?: string`\n Optional description of the product collection\n\n- `effective_at_on_downgrade?: 'immediately' | 'next_billing_date'`\n Default effective_at setting for subscription plan downgrades (NULL = inherit from business)\n\n- `effective_at_on_upgrade?: 'immediately' | 'next_billing_date'`\n Default effective_at setting for subscription plan upgrades (NULL = inherit from business)\n\n- `on_payment_failure?: 'prevent_change' | 'apply_change'`\n Default behavior for subscription plan changes on payment failure (NULL = inherit from business)\n\n- `proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n Default proration billing mode for subscription plan downgrades (NULL = inherit from business)\n\n- `proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n Default proration billing mode for subscription plan upgrades (NULL = inherit from business)\n\n### Returns\n\n- `{ id: string; brand_id: string; created_at: string; groups: { group_id: string; products: product_collection_product[]; status: boolean; group_name?: string; }[]; name: string; updated_at: string; description?: string; effective_at_on_downgrade?: 'immediately' | 'next_billing_date'; effective_at_on_upgrade?: 'immediately' | 'next_billing_date'; image?: string; on_payment_failure?: 'prevent_change' | 'apply_change'; proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; }`\n\n - `id: string`\n - `brand_id: string`\n - `created_at: string`\n - `groups: { group_id: string; products: { id: string; addons_count: number; files_count: number; has_credit_entitlements: boolean; is_recurring: boolean; license_key_enabled: boolean; meters_count: number; product_id: string; status: boolean; currency?: currency; description?: string; name?: string; price?: number; price_detail?: price; tax_category?: tax_category; tax_inclusive?: boolean; }[]; status: boolean; group_name?: string; }[]`\n - `name: string`\n - `updated_at: string`\n - `description?: string`\n - `effective_at_on_downgrade?: 'immediately' | 'next_billing_date'`\n - `effective_at_on_upgrade?: 'immediately' | 'next_billing_date'`\n - `image?: string`\n - `on_payment_failure?: 'prevent_change' | 'apply_change'`\n - `proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n - `proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst productCollection = await client.productCollections.create({ groups: [{ products: [{ product_id: 'product_id' }] }], name: 'name' });\n\nconsole.log(productCollection);\n```",
|
|
6313
6318
|
perLanguage: {
|
|
6314
6319
|
typescript: {
|
|
6315
6320
|
method: 'client.productCollections.create',
|
|
@@ -6340,7 +6345,7 @@ const EMBEDDED_METHODS = [
|
|
|
6340
6345
|
},
|
|
6341
6346
|
php: {
|
|
6342
6347
|
method: 'productCollections->create',
|
|
6343
|
-
example: "<?php\n\nrequire_once dirname(__DIR__) . '/vendor/autoload.php';\n\n$client = new Client(bearerToken: 'My Bearer Token', environment: 'test_mode');\n\n$productCollection = $client->productCollections->create(\n groups: [\n [\n 'products' => [['productID' => 'product_id', 'status' => true]],\n 'groupName' => 'group_name',\n 'status' => true,\n ],\n ],\n name: 'name',\n brandID: 'brand_id',\n description: 'description',\n);\n\nvar_dump($productCollection);",
|
|
6348
|
+
example: "<?php\n\nrequire_once dirname(__DIR__) . '/vendor/autoload.php';\n\n$client = new Client(bearerToken: 'My Bearer Token', environment: 'test_mode');\n\n$productCollection = $client->productCollections->create(\n groups: [\n [\n 'products' => [['productID' => 'product_id', 'status' => true]],\n 'groupName' => 'group_name',\n 'status' => true,\n ],\n ],\n name: 'name',\n brandID: 'brand_id',\n description: 'description',\n effectiveAtOnDowngrade: 'immediately',\n effectiveAtOnUpgrade: 'immediately',\n onPaymentFailure: 'prevent_change',\n prorationBillingModeOnDowngrade: 'prorated_immediately',\n prorationBillingModeOnUpgrade: 'prorated_immediately',\n);\n\nvar_dump($productCollection);",
|
|
6344
6349
|
},
|
|
6345
6350
|
csharp: {
|
|
6346
6351
|
method: 'ProductCollections.Create',
|
|
@@ -6357,8 +6362,8 @@ const EMBEDDED_METHODS = [
|
|
|
6357
6362
|
stainlessPath: '(resource) product_collections > (method) retrieve',
|
|
6358
6363
|
qualified: 'client.productCollections.retrieve',
|
|
6359
6364
|
params: ['id: string;'],
|
|
6360
|
-
response:
|
|
6361
|
-
markdown: "## retrieve\n\n`client.productCollections.retrieve(id: string): { id: string; brand_id: string; created_at: string; groups: product_collection_group_response[]; name: string; updated_at: string; description?: string; image?: string; }`\n\n**get** `/product-collections/{id}`\n\n### Parameters\n\n- `id: string`\n\n### Returns\n\n- `{ id: string; brand_id: string; created_at: string; groups: { group_id: string; products: product_collection_product[]; status: boolean; group_name?: string; }[]; name: string; updated_at: string; description?: string; image?: string; }`\n\n - `id: string`\n - `brand_id: string`\n - `created_at: string`\n - `groups: { group_id: string; products: { id: string; addons_count: number; files_count: number; has_credit_entitlements: boolean; is_recurring: boolean; license_key_enabled: boolean; meters_count: number; product_id: string; status: boolean; currency?: currency; description?: string; name?: string; price?: number; price_detail?: price; tax_category?: tax_category; tax_inclusive?: boolean; }[]; status: boolean; group_name?: string; }[]`\n - `name: string`\n - `updated_at: string`\n - `description?: string`\n - `image?: string`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst productCollection = await client.productCollections.retrieve('id');\n\nconsole.log(productCollection);\n```",
|
|
6365
|
+
response: "{ id: string; brand_id: string; created_at: string; groups: { group_id: string; products: product_collection_product[]; status: boolean; group_name?: string; }[]; name: string; updated_at: string; description?: string; effective_at_on_downgrade?: 'immediately' | 'next_billing_date'; effective_at_on_upgrade?: 'immediately' | 'next_billing_date'; image?: string; on_payment_failure?: 'prevent_change' | 'apply_change'; proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; }",
|
|
6366
|
+
markdown: "## retrieve\n\n`client.productCollections.retrieve(id: string): { id: string; brand_id: string; created_at: string; groups: product_collection_group_response[]; name: string; updated_at: string; description?: string; effective_at_on_downgrade?: 'immediately' | 'next_billing_date'; effective_at_on_upgrade?: 'immediately' | 'next_billing_date'; image?: string; on_payment_failure?: 'prevent_change' | 'apply_change'; proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; }`\n\n**get** `/product-collections/{id}`\n\n### Parameters\n\n- `id: string`\n\n### Returns\n\n- `{ id: string; brand_id: string; created_at: string; groups: { group_id: string; products: product_collection_product[]; status: boolean; group_name?: string; }[]; name: string; updated_at: string; description?: string; effective_at_on_downgrade?: 'immediately' | 'next_billing_date'; effective_at_on_upgrade?: 'immediately' | 'next_billing_date'; image?: string; on_payment_failure?: 'prevent_change' | 'apply_change'; proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'; }`\n\n - `id: string`\n - `brand_id: string`\n - `created_at: string`\n - `groups: { group_id: string; products: { id: string; addons_count: number; files_count: number; has_credit_entitlements: boolean; is_recurring: boolean; license_key_enabled: boolean; meters_count: number; product_id: string; status: boolean; currency?: currency; description?: string; name?: string; price?: number; price_detail?: price; tax_category?: tax_category; tax_inclusive?: boolean; }[]; status: boolean; group_name?: string; }[]`\n - `name: string`\n - `updated_at: string`\n - `description?: string`\n - `effective_at_on_downgrade?: 'immediately' | 'next_billing_date'`\n - `effective_at_on_upgrade?: 'immediately' | 'next_billing_date'`\n - `image?: string`\n - `on_payment_failure?: 'prevent_change' | 'apply_change'`\n - `proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n - `proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nconst productCollection = await client.productCollections.retrieve('id');\n\nconsole.log(productCollection);\n```",
|
|
6362
6367
|
perLanguage: {
|
|
6363
6368
|
typescript: {
|
|
6364
6369
|
method: 'client.productCollections.retrieve',
|
|
@@ -6457,11 +6462,16 @@ const EMBEDDED_METHODS = [
|
|
|
6457
6462
|
'id: string;',
|
|
6458
6463
|
'brand_id?: string;',
|
|
6459
6464
|
'description?: string;',
|
|
6465
|
+
"effective_at_on_downgrade?: 'immediately' | 'next_billing_date';",
|
|
6466
|
+
"effective_at_on_upgrade?: 'immediately' | 'next_billing_date';",
|
|
6460
6467
|
'group_order?: string[];',
|
|
6461
6468
|
'image_id?: string;',
|
|
6462
6469
|
'name?: string;',
|
|
6470
|
+
"on_payment_failure?: 'prevent_change' | 'apply_change';",
|
|
6471
|
+
"proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill';",
|
|
6472
|
+
"proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill';",
|
|
6463
6473
|
],
|
|
6464
|
-
markdown: "## update\n\n`client.productCollections.update(id: string, brand_id?: string, description?: string, group_order?: string[], image_id?: string, name?: string): void`\n\n**patch** `/product-collections/{id}`\n\n### Parameters\n\n- `id: string`\n\n- `brand_id?: string`\n Optional brand_id update\n\n- `description?: string`\n Optional description update - pass null to remove, omit to keep unchanged\n\n- `group_order?: string[]`\n Optional new order for groups (array of group UUIDs in desired order)\n\n- `image_id?: string`\n Optional image update - pass null to remove, omit to keep unchanged\n\n- `name?: string`\n Optional new name for the collection\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nawait client.productCollections.update('id')\n```",
|
|
6474
|
+
markdown: "## update\n\n`client.productCollections.update(id: string, brand_id?: string, description?: string, effective_at_on_downgrade?: 'immediately' | 'next_billing_date', effective_at_on_upgrade?: 'immediately' | 'next_billing_date', group_order?: string[], image_id?: string, name?: string, on_payment_failure?: 'prevent_change' | 'apply_change', proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill', proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'): void`\n\n**patch** `/product-collections/{id}`\n\n### Parameters\n\n- `id: string`\n\n- `brand_id?: string`\n Optional brand_id update\n\n- `description?: string`\n Optional description update - pass null to remove, omit to keep unchanged\n\n- `effective_at_on_downgrade?: 'immediately' | 'next_billing_date'`\n Effective_at setting for downgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change\n\n- `effective_at_on_upgrade?: 'immediately' | 'next_billing_date'`\n Effective_at setting for upgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change\n\n- `group_order?: string[]`\n Optional new order for groups (array of group UUIDs in desired order)\n\n- `image_id?: string`\n Optional image update - pass null to remove, omit to keep unchanged\n\n- `name?: string`\n Optional new name for the collection\n\n- `on_payment_failure?: 'prevent_change' | 'apply_change'`\n On payment failure behavior: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change\n\n- `proration_billing_mode_on_downgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n Proration billing mode for downgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change\n\n- `proration_billing_mode_on_upgrade?: 'prorated_immediately' | 'full_immediately' | 'difference_immediately' | 'do_not_bill'`\n Proration billing mode for upgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change\n\n### Example\n\n```typescript\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments();\n\nawait client.productCollections.update('id')\n```",
|
|
6465
6475
|
perLanguage: {
|
|
6466
6476
|
typescript: {
|
|
6467
6477
|
method: 'client.productCollections.update',
|
|
@@ -6492,7 +6502,7 @@ const EMBEDDED_METHODS = [
|
|
|
6492
6502
|
},
|
|
6493
6503
|
php: {
|
|
6494
6504
|
method: 'productCollections->update',
|
|
6495
|
-
example: "<?php\n\nrequire_once dirname(__DIR__) . '/vendor/autoload.php';\n\n$client = new Client(bearerToken: 'My Bearer Token', environment: 'test_mode');\n\n$result = $client->productCollections->update(\n 'id',\n brandID: 'brand_id',\n description: 'description',\n groupOrder: ['182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e'],\n imageID: '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e',\n name: 'name',\n);\n\nvar_dump($result);",
|
|
6505
|
+
example: "<?php\n\nrequire_once dirname(__DIR__) . '/vendor/autoload.php';\n\n$client = new Client(bearerToken: 'My Bearer Token', environment: 'test_mode');\n\n$result = $client->productCollections->update(\n 'id',\n brandID: 'brand_id',\n description: 'description',\n effectiveAtOnDowngrade: 'immediately',\n effectiveAtOnUpgrade: 'immediately',\n groupOrder: ['182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e'],\n imageID: '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e',\n name: 'name',\n onPaymentFailure: 'prevent_change',\n prorationBillingModeOnDowngrade: 'prorated_immediately',\n prorationBillingModeOnUpgrade: 'prorated_immediately',\n);\n\nvar_dump($result);",
|
|
6496
6506
|
},
|
|
6497
6507
|
csharp: {
|
|
6498
6508
|
method: 'ProductCollections.Update',
|
|
@@ -6903,27 +6913,27 @@ const EMBEDDED_METHODS = [
|
|
|
6903
6913
|
const EMBEDDED_READMES = [
|
|
6904
6914
|
{
|
|
6905
6915
|
language: 'typescript',
|
|
6906
|
-
content: "# Dodo Payments TypeScript API Library\n\n[)](https://npmjs.org/package/dodopayments) \n\nThis library provides convenient access to the Dodo Payments REST API from server-side TypeScript or JavaScript.\n\n\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). The full API of this library can be found in [api.md](api.md).\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n[](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22dodopayments-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22dodopayments-mcp%22%5D%2C%22env%22%3A%7B%22DODO_PAYMENTS_API_KEY%22%3A%22My%20Bearer%20Token%22%2C%22DODO_PAYMENTS_WEBHOOK_KEY%22%3A%22My%20Webhook%20Key%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Installation\n\n```sh\nnpm install dodopayments\n```\n\n\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n<!-- prettier-ignore -->\n```js\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n bearerToken: process.env['DODO_PAYMENTS_API_KEY'], // This is the default and can be omitted\n environment: 'test_mode', // defaults to 'live_mode'\n});\n\nconst checkoutSessionResponse = await client.checkoutSessions.create({\n product_cart: [{ product_id: 'pdt_example', quantity: 1 }],\n});\n\nconsole.log(checkoutSessionResponse.session_id);\n```\n\n\n\n### Request & Response types\n\nThis library includes TypeScript definitions for all request params and response fields. You may import and use them like so:\n\n<!-- prettier-ignore -->\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n bearerToken: process.env['DODO_PAYMENTS_API_KEY'], // This is the default and can be omitted\n environment: 'test_mode', // defaults to 'live_mode'\n});\n\nconst params: DodoPayments.CheckoutSessionCreateParams = {\n product_cart: [{ product_id: 'pdt_example', quantity: 1 }],\n};\nconst checkoutSessionResponse: DodoPayments.CheckoutSessionResponse =\n await client.checkoutSessions.create(params);\n```\n\nDocumentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.\n\n\n\n\n\n## Handling errors\n\nWhen the library is unable to connect to the API,\nor if the API returns a non-success status code (i.e., 4xx or 5xx response),\na subclass of `APIError` will be thrown:\n\n<!-- prettier-ignore -->\n```ts\nconst checkoutSessionResponse = await client.checkoutSessions\n .create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] })\n .catch(async (err) => {\n if (err instanceof DodoPayments.APIError) {\n console.log(err.status); // 400\n console.log(err.name); // BadRequestError\n console.log(err.headers); // {server: 'nginx', ...}\n } else {\n throw err;\n }\n });\n```\n\nError codes are as follows:\n\n| Status Code | Error Type |\n| ----------- | -------------------------- |\n| 400 | `BadRequestError` |\n| 401 | `AuthenticationError` |\n| 403 | `PermissionDeniedError` |\n| 404 | `NotFoundError` |\n| 422 | `UnprocessableEntityError` |\n| 429 | `RateLimitError` |\n| >=500 | `InternalServerError` |\n| N/A | `APIConnectionError` |\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,\n429 Rate Limit, and >=500 Internal errors will all be retried by default.\n\nYou can use the `maxRetries` option to configure or disable this:\n\n<!-- prettier-ignore -->\n```js\n// Configure the default for all requests:\nconst client = new DodoPayments({\n maxRetries: 0, // default is 2\n});\n\n// Or, configure per-request:\nawait client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] }, {\n maxRetries: 5,\n});\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default. You can configure this with a `timeout` option:\n\n<!-- prettier-ignore -->\n```ts\n// Configure the default for all requests:\nconst client = new DodoPayments({\n timeout: 20 * 1000, // 20 seconds (default is 1 minute)\n});\n\n// Override per-request:\nawait client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] }, {\n timeout: 5 * 1000,\n});\n```\n\nOn timeout, an `APIConnectionTimeoutError` is thrown.\n\nNote that requests which time out will be [retried twice by default](#retries).\n\n## Auto-pagination\n\nList methods in the DodoPayments API are paginated.\nYou can use the `for await … of` syntax to iterate through items across all pages:\n\n```ts\nasync function fetchAllPaymentListResponses(params) {\n const allPaymentListResponses = [];\n // Automatically fetches more pages as needed.\n for await (const paymentListResponse of client.payments.list()) {\n allPaymentListResponses.push(paymentListResponse);\n }\n return allPaymentListResponses;\n}\n```\n\nAlternatively, you can request a single page at a time:\n\n```ts\nlet page = await client.payments.list();\nfor (const paymentListResponse of page.items) {\n console.log(paymentListResponse);\n}\n\n// Convenience methods are provided for manually paginating:\nwhile (page.hasNextPage()) {\n page = await page.getNextPage();\n // ...\n}\n```\n\n\n\n## Advanced Usage\n\n### Accessing raw Response data (e.g., headers)\n\nThe \"raw\" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return.\nThis method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.\n\nYou can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.\nUnlike `.asResponse()` this method consumes the body, returning once it is parsed.\n\n<!-- prettier-ignore -->\n```ts\nconst client = new DodoPayments();\n\nconst response = await client.checkoutSessions\n .create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] })\n .asResponse();\nconsole.log(response.headers.get('X-My-Header'));\nconsole.log(response.statusText); // access the underlying Response object\n\nconst { data: checkoutSessionResponse, response: raw } = await client.checkoutSessions\n .create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] })\n .withResponse();\nconsole.log(raw.headers.get('X-My-Header'));\nconsole.log(checkoutSessionResponse.session_id);\n```\n\n### Logging\n\n> [!IMPORTANT]\n> All log messages are intended for debugging only. The format and content of log messages\n> may change between releases.\n\n#### Log levels\n\nThe log level can be configured in two ways:\n\n1. Via the `DODO_PAYMENTS_LOG` environment variable\n2. Using the `logLevel` client option (overrides the environment variable if set)\n\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n logLevel: 'debug', // Show all log messages\n});\n```\n\nAvailable log levels, from most to least verbose:\n\n- `'debug'` - Show debug messages, info, warnings, and errors\n- `'info'` - Show info messages, warnings, and errors\n- `'warn'` - Show warnings and errors (default)\n- `'error'` - Show only errors\n- `'off'` - Disable all logging\n\nAt the `'debug'` level, all HTTP requests and responses are logged, including headers and bodies.\nSome authentication-related headers are redacted, but sensitive data in request and response bodies\nmay still be visible.\n\n#### Custom logger\n\nBy default, this library logs to `globalThis.console`. You can also provide a custom logger.\nMost logging libraries are supported, including [pino](https://www.npmjs.com/package/pino), [winston](https://www.npmjs.com/package/winston), [bunyan](https://www.npmjs.com/package/bunyan), [consola](https://www.npmjs.com/package/consola), [signale](https://www.npmjs.com/package/signale), and [@std/log](https://jsr.io/@std/log). If your logger doesn't work, please open an issue.\n\nWhen providing a custom logger, the `logLevel` option still controls which messages are emitted, messages\nbelow the configured level will not be sent to your logger.\n\n```ts\nimport DodoPayments from 'dodopayments';\nimport pino from 'pino';\n\nconst logger = pino();\n\nconst client = new DodoPayments({\n logger: logger.child({ name: 'DodoPayments' }),\n logLevel: 'debug', // Send all messages to pino, allowing it to filter\n});\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs.\nOptions on the client, such as retries, will be respected when making these requests.\n\n```ts\nawait client.post('/some/path', {\n body: { some_prop: 'foo' },\n query: { some_query_arg: 'bar' },\n});\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented\nparameter. This library doesn't validate at runtime that the request matches the type, so any extra values you\nsend will be sent as-is.\n\n```ts\nclient.checkoutSessions.create({\n // ...\n // @ts-expect-error baz is not yet public\n baz: 'undocumented option',\n});\n```\n\nFor requests with the `GET` verb, any extra params will be in the query, all other requests will send the\nextra param in the body.\n\nIf you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may access the response object with `// @ts-expect-error` on\nthe response object, or cast the response object to the requisite type. Like the request params, we do not\nvalidate or strip extra properties from the response from the API.\n\n### Customizing the fetch client\n\nBy default, this library expects a global `fetch` function is defined.\n\nIf you want to use a different `fetch` function, you can either polyfill the global:\n\n```ts\nimport fetch from 'my-fetch';\n\nglobalThis.fetch = fetch;\n```\n\nOr pass it to the client:\n\n```ts\nimport DodoPayments from 'dodopayments';\nimport fetch from 'my-fetch';\n\nconst client = new DodoPayments({ fetch });\n```\n\n### Fetch options\n\nIf you want to set custom `fetch` options without overriding the `fetch` function, you can provide a `fetchOptions` object when instantiating the client or making a request. (Request-specific options override client options.)\n\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n fetchOptions: {\n // `RequestInit` options\n },\n});\n```\n\n#### Configuring proxies\n\nTo modify proxy behavior, you can provide custom `fetchOptions` that add runtime-specific proxy\noptions to requests:\n\n<img src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/node.svg\" align=\"top\" width=\"18\" height=\"21\"> **Node** <sup>[[docs](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md#example---proxyagent-with-fetch)]</sup>\n\n```ts\nimport DodoPayments from 'dodopayments';\nimport * as undici from 'undici';\n\nconst proxyAgent = new undici.ProxyAgent('http://localhost:8888');\nconst client = new DodoPayments({\n fetchOptions: {\n dispatcher: proxyAgent,\n },\n});\n```\n\n<img src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/bun.svg\" align=\"top\" width=\"18\" height=\"21\"> **Bun** <sup>[[docs](https://bun.sh/guides/http/proxy)]</sup>\n\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n fetchOptions: {\n proxy: 'http://localhost:8888',\n },\n});\n```\n\n<img src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/deno.svg\" align=\"top\" width=\"18\" height=\"21\"> **Deno** <sup>[[docs](https://docs.deno.com/api/deno/~/Deno.createHttpClient)]</sup>\n\n```ts\nimport DodoPayments from 'npm:dodopayments';\n\nconst httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });\nconst client = new DodoPayments({\n fetchOptions: {\n client: httpClient,\n },\n});\n```\n\n## Frequently Asked Questions\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-typescript/issues) with questions, bugs, or suggestions.\n\n## Requirements\n\nTypeScript >= 4.9 is supported.\n\nThe following runtimes are supported:\n\n- Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more)\n- Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.\n- Deno v1.28.0 or higher.\n- Bun 1.0 or later.\n- Cloudflare Workers.\n- Vercel Edge Runtime.\n- Jest 28 or greater with the `\"node\"` environment (`\"jsdom\"` is not supported at this time).\n- Nitro v2.6 or greater.\n\nNote that React Native is not supported at this time.\n\nIf you are interested in other runtime environments, please open or upvote an issue on GitHub.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n",
|
|
6916
|
+
content: "# Dodo Payments TypeScript API Library\n\n[)](https://npmjs.org/package/dodopayments) \n\nThis library provides convenient access to the Dodo Payments REST API from server-side TypeScript or JavaScript.\n\n\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). The full API of this library can be found in [api.md](api.md).\n\n\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Installation\n\n```sh\nnpm install dodopayments\n```\n\n\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n<!-- prettier-ignore -->\n```js\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n bearerToken: process.env['DODO_PAYMENTS_API_KEY'], // This is the default and can be omitted\n environment: 'test_mode', // defaults to 'live_mode'\n});\n\nconst checkoutSessionResponse = await client.checkoutSessions.create({\n product_cart: [{ product_id: 'pdt_example', quantity: 1 }],\n});\n\nconsole.log(checkoutSessionResponse.session_id);\n```\n\n\n\n### Request & Response types\n\nThis library includes TypeScript definitions for all request params and response fields. You may import and use them like so:\n\n<!-- prettier-ignore -->\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n bearerToken: process.env['DODO_PAYMENTS_API_KEY'], // This is the default and can be omitted\n environment: 'test_mode', // defaults to 'live_mode'\n});\n\nconst params: DodoPayments.CheckoutSessionCreateParams = {\n product_cart: [{ product_id: 'pdt_example', quantity: 1 }],\n};\nconst checkoutSessionResponse: DodoPayments.CheckoutSessionResponse =\n await client.checkoutSessions.create(params);\n```\n\nDocumentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors.\n\n\n\n\n\n## Handling errors\n\nWhen the library is unable to connect to the API,\nor if the API returns a non-success status code (i.e., 4xx or 5xx response),\na subclass of `APIError` will be thrown:\n\n<!-- prettier-ignore -->\n```ts\nconst checkoutSessionResponse = await client.checkoutSessions\n .create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] })\n .catch(async (err) => {\n if (err instanceof DodoPayments.APIError) {\n console.log(err.status); // 400\n console.log(err.name); // BadRequestError\n console.log(err.headers); // {server: 'nginx', ...}\n } else {\n throw err;\n }\n });\n```\n\nError codes are as follows:\n\n| Status Code | Error Type |\n| ----------- | -------------------------- |\n| 400 | `BadRequestError` |\n| 401 | `AuthenticationError` |\n| 403 | `PermissionDeniedError` |\n| 404 | `NotFoundError` |\n| 422 | `UnprocessableEntityError` |\n| 429 | `RateLimitError` |\n| >=500 | `InternalServerError` |\n| N/A | `APIConnectionError` |\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,\n429 Rate Limit, and >=500 Internal errors will all be retried by default.\n\nYou can use the `maxRetries` option to configure or disable this:\n\n<!-- prettier-ignore -->\n```js\n// Configure the default for all requests:\nconst client = new DodoPayments({\n maxRetries: 0, // default is 2\n});\n\n// Or, configure per-request:\nawait client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] }, {\n maxRetries: 5,\n});\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default. You can configure this with a `timeout` option:\n\n<!-- prettier-ignore -->\n```ts\n// Configure the default for all requests:\nconst client = new DodoPayments({\n timeout: 20 * 1000, // 20 seconds (default is 1 minute)\n});\n\n// Override per-request:\nawait client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] }, {\n timeout: 5 * 1000,\n});\n```\n\nOn timeout, an `APIConnectionTimeoutError` is thrown.\n\nNote that requests which time out will be [retried twice by default](#retries).\n\n## Auto-pagination\n\nList methods in the DodoPayments API are paginated.\nYou can use the `for await … of` syntax to iterate through items across all pages:\n\n```ts\nasync function fetchAllPaymentListResponses(params) {\n const allPaymentListResponses = [];\n // Automatically fetches more pages as needed.\n for await (const paymentListResponse of client.payments.list()) {\n allPaymentListResponses.push(paymentListResponse);\n }\n return allPaymentListResponses;\n}\n```\n\nAlternatively, you can request a single page at a time:\n\n```ts\nlet page = await client.payments.list();\nfor (const paymentListResponse of page.items) {\n console.log(paymentListResponse);\n}\n\n// Convenience methods are provided for manually paginating:\nwhile (page.hasNextPage()) {\n page = await page.getNextPage();\n // ...\n}\n```\n\n\n\n## Advanced Usage\n\n### Accessing raw Response data (e.g., headers)\n\nThe \"raw\" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return.\nThis method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.\n\nYou can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.\nUnlike `.asResponse()` this method consumes the body, returning once it is parsed.\n\n<!-- prettier-ignore -->\n```ts\nconst client = new DodoPayments();\n\nconst response = await client.checkoutSessions\n .create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] })\n .asResponse();\nconsole.log(response.headers.get('X-My-Header'));\nconsole.log(response.statusText); // access the underlying Response object\n\nconst { data: checkoutSessionResponse, response: raw } = await client.checkoutSessions\n .create({ product_cart: [{ product_id: 'pdt_example', quantity: 1 }] })\n .withResponse();\nconsole.log(raw.headers.get('X-My-Header'));\nconsole.log(checkoutSessionResponse.session_id);\n```\n\n### Logging\n\n> [!IMPORTANT]\n> All log messages are intended for debugging only. The format and content of log messages\n> may change between releases.\n\n#### Log levels\n\nThe log level can be configured in two ways:\n\n1. Via the `DODO_PAYMENTS_LOG` environment variable\n2. Using the `logLevel` client option (overrides the environment variable if set)\n\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n logLevel: 'debug', // Show all log messages\n});\n```\n\nAvailable log levels, from most to least verbose:\n\n- `'debug'` - Show debug messages, info, warnings, and errors\n- `'info'` - Show info messages, warnings, and errors\n- `'warn'` - Show warnings and errors (default)\n- `'error'` - Show only errors\n- `'off'` - Disable all logging\n\nAt the `'debug'` level, all HTTP requests and responses are logged, including headers and bodies.\nSome authentication-related headers are redacted, but sensitive data in request and response bodies\nmay still be visible.\n\n#### Custom logger\n\nBy default, this library logs to `globalThis.console`. You can also provide a custom logger.\nMost logging libraries are supported, including [pino](https://www.npmjs.com/package/pino), [winston](https://www.npmjs.com/package/winston), [bunyan](https://www.npmjs.com/package/bunyan), [consola](https://www.npmjs.com/package/consola), [signale](https://www.npmjs.com/package/signale), and [@std/log](https://jsr.io/@std/log). If your logger doesn't work, please open an issue.\n\nWhen providing a custom logger, the `logLevel` option still controls which messages are emitted, messages\nbelow the configured level will not be sent to your logger.\n\n```ts\nimport DodoPayments from 'dodopayments';\nimport pino from 'pino';\n\nconst logger = pino();\n\nconst client = new DodoPayments({\n logger: logger.child({ name: 'DodoPayments' }),\n logLevel: 'debug', // Send all messages to pino, allowing it to filter\n});\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs.\nOptions on the client, such as retries, will be respected when making these requests.\n\n```ts\nawait client.post('/some/path', {\n body: { some_prop: 'foo' },\n query: { some_query_arg: 'bar' },\n});\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented\nparameter. This library doesn't validate at runtime that the request matches the type, so any extra values you\nsend will be sent as-is.\n\n```ts\nclient.checkoutSessions.create({\n // ...\n // @ts-expect-error baz is not yet public\n baz: 'undocumented option',\n});\n```\n\nFor requests with the `GET` verb, any extra params will be in the query, all other requests will send the\nextra param in the body.\n\nIf you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may access the response object with `// @ts-expect-error` on\nthe response object, or cast the response object to the requisite type. Like the request params, we do not\nvalidate or strip extra properties from the response from the API.\n\n### Customizing the fetch client\n\nBy default, this library expects a global `fetch` function is defined.\n\nIf you want to use a different `fetch` function, you can either polyfill the global:\n\n```ts\nimport fetch from 'my-fetch';\n\nglobalThis.fetch = fetch;\n```\n\nOr pass it to the client:\n\n```ts\nimport DodoPayments from 'dodopayments';\nimport fetch from 'my-fetch';\n\nconst client = new DodoPayments({ fetch });\n```\n\n### Fetch options\n\nIf you want to set custom `fetch` options without overriding the `fetch` function, you can provide a `fetchOptions` object when instantiating the client or making a request. (Request-specific options override client options.)\n\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n fetchOptions: {\n // `RequestInit` options\n },\n});\n```\n\n#### Configuring proxies\n\nTo modify proxy behavior, you can provide custom `fetchOptions` that add runtime-specific proxy\noptions to requests:\n\n**Node** <sup>[[docs](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md#example---proxyagent-with-fetch)]</sup>\n\n```ts\nimport DodoPayments from 'dodopayments';\nimport * as undici from 'undici';\n\nconst proxyAgent = new undici.ProxyAgent('http://localhost:8888');\nconst client = new DodoPayments({\n fetchOptions: {\n dispatcher: proxyAgent,\n },\n});\n```\n\n**Bun** <sup>[[docs](https://bun.sh/guides/http/proxy)]</sup>\n\n```ts\nimport DodoPayments from 'dodopayments';\n\nconst client = new DodoPayments({\n fetchOptions: {\n proxy: 'http://localhost:8888',\n },\n});\n```\n\n**Deno** <sup>[[docs](https://docs.deno.com/api/deno/~/Deno.createHttpClient)]</sup>\n\n```ts\nimport DodoPayments from 'npm:dodopayments';\n\nconst httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });\nconst client = new DodoPayments({\n fetchOptions: {\n client: httpClient,\n },\n});\n```\n\n## Frequently Asked Questions\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-typescript/issues) with questions, bugs, or suggestions.\n\n## Requirements\n\nTypeScript >= 4.9 is supported.\n\nThe following runtimes are supported:\n\n- Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more)\n- Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.\n- Deno v1.28.0 or higher.\n- Bun 1.0 or later.\n- Cloudflare Workers.\n- Vercel Edge Runtime.\n- Jest 28 or greater with the `\"node\"` environment (`\"jsdom\"` is not supported at this time).\n- Nitro v2.6 or greater.\n\nNote that React Native is not supported at this time.\n\nIf you are interested in other runtime environments, please open or upvote an issue on GitHub.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n",
|
|
6907
6917
|
},
|
|
6908
6918
|
{
|
|
6909
6919
|
language: 'python',
|
|
6910
|
-
content: '# Dodo Payments Python API library\n\n<!-- prettier-ignore -->\n[)](https://pypi.org/project/dodopayments/)\n\nThe Dodo Payments Python library provides convenient access to the Dodo Payments REST API from any Python 3.9+\napplication. The library includes type definitions for all request params and response fields,\nand offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).\n\n\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n[](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22dodopayments-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22dodopayments-mcp%22%5D%2C%22env%22%3A%7B%22DODO_PAYMENTS_API_KEY%22%3A%22My%20Bearer%20Token%22%2C%22DODO_PAYMENTS_WEBHOOK_KEY%22%3A%22My%20Webhook%20Key%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Documentation\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). The full API of this library can be found in [api.md](api.md).\n\n## Installation\n\n```sh\n# install from PyPI\npip install dodopayments\n```\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n```python\nimport os\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments(\n bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), # This is the default and can be omitted\n # defaults to "live_mode".\n environment="test_mode",\n)\n\ncheckout_session_response = client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\nprint(checkout_session_response.session_id)\n```\n\nWhile you can provide a `bearer_token` keyword argument,\nwe recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)\nto add `DODO_PAYMENTS_API_KEY="My Bearer Token"` to your `.env` file\nso that your Bearer Token is not stored in source control.\n\n## Async usage\n\nSimply import `AsyncDodoPayments` instead of `DodoPayments` and use `await` with each API call:\n\n```python\nimport os\nimport asyncio\nfrom dodopayments import AsyncDodoPayments\n\nclient = AsyncDodoPayments(\n bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), # This is the default and can be omitted\n # defaults to "live_mode".\n environment="test_mode",\n)\n\nasync def main() -> None:\n checkout_session_response = await client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n )\n print(checkout_session_response.session_id)\n\nasyncio.run(main())\n```\n\nFunctionality between the synchronous and asynchronous clients is otherwise identical.\n\n### With aiohttp\n\nBy default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.\n\nYou can enable this by installing `aiohttp`:\n\n```sh\n# install from PyPI\npip install dodopayments[aiohttp]\n```\n\nThen you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:\n\n```python\nimport os\nimport asyncio\nfrom dodopayments import DefaultAioHttpClient\nfrom dodopayments import AsyncDodoPayments\n\nasync def main() -> None:\n async with AsyncDodoPayments(\n bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), # This is the default and can be omitted\n http_client=DefaultAioHttpClient(),\n) as client:\n checkout_session_response = await client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n )\n print(checkout_session_response.session_id)\n\nasyncio.run(main())\n```\n\n\n\n## Using types\n\nNested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like:\n\n- Serializing back into JSON, `model.to_json()`\n- Converting to a dictionary, `model.to_dict()`\n\nTyped requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.\n\n## Pagination\n\nList methods in the Dodo Payments API are paginated.\n\nThis library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:\n\n```python\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\n\nall_payments = []\n# Automatically fetches more pages as needed.\nfor payment in client.payments.list():\n # Do something with payment here\n all_payments.append(payment)\nprint(all_payments)\n```\n\nOr, asynchronously:\n\n```python\nimport asyncio\nfrom dodopayments import AsyncDodoPayments\n\nclient = AsyncDodoPayments()\n\nasync def main() -> None:\n all_payments = []\n # Iterate through items across all pages, issuing requests as needed.\n async for payment in client.payments.list():\n all_payments.append(payment)\n print(all_payments)\n\nasyncio.run(main())\n```\n\nAlternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages:\n\n```python\nfirst_page = await client.payments.list()\nif first_page.has_next_page():\n print(f"will fetch next page using these details: {first_page.next_page_info()}")\n next_page = await first_page.get_next_page()\n print(f"number of items we just fetched: {len(next_page.items)}")\n\n# Remove `await` for non-async usage.\n```\n\nOr just work directly with the returned data:\n\n```python\nfirst_page = await client.payments.list()\nfor payment in first_page.items:\n print(payment.brand_id)\n\n# Remove `await` for non-async usage.\n```\n\n## Nested params\n\nNested parameters are dictionaries, typed using `TypedDict`, for example:\n\n```python\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\n\ncheckout_session_response = client.checkout_sessions.create(\n product_cart=[{\n "product_id": "product_id",\n "quantity": 0,\n }],\n billing_address={\n "country": "AF"\n },\n)\nprint(checkout_session_response.billing_address)\n```\n\n\n\n## Handling errors\n\nWhen the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `dodopayments.APIConnectionError` is raised.\n\nWhen the API returns a non-success status code (that is, 4xx or 5xx\nresponse), a subclass of `dodopayments.APIStatusError` is raised, containing `status_code` and `response` properties.\n\nAll errors inherit from `dodopayments.APIError`.\n\n```python\nimport dodopayments\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\n\ntry:\n client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n )\nexcept dodopayments.APIConnectionError as e:\n print("The server could not be reached")\n print(e.__cause__) # an underlying Exception, likely raised within httpx.\nexcept dodopayments.RateLimitError as e:\n print("A 429 status code was received; we should back off a bit.")\nexcept dodopayments.APIStatusError as e:\n print("Another non-200-range status code was received")\n print(e.status_code)\n print(e.response)\n```\n\nError codes are as follows:\n\n| Status Code | Error Type |\n| ----------- | -------------------------- |\n| 400 | `BadRequestError` |\n| 401 | `AuthenticationError` |\n| 403 | `PermissionDeniedError` |\n| 404 | `NotFoundError` |\n| 422 | `UnprocessableEntityError` |\n| 429 | `RateLimitError` |\n| >=500 | `InternalServerError` |\n| N/A | `APIConnectionError` |\n\n### Retries\n\nCertain errors are automatically retried 2 times by default, with a short exponential backoff.\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,\n429 Rate Limit, and >=500 Internal errors are all retried by default.\n\nYou can use the `max_retries` option to configure or disable retry settings:\n\n```python\nfrom dodopayments import DodoPayments\n\n# Configure the default for all requests:\nclient = DodoPayments(\n # default is 2\n max_retries=0,\n)\n\n# Or, configure per-request:\nclient.with_options(max_retries = 5).checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\n```\n\n### Timeouts\n\nBy default requests time out after 1 minute. You can configure this with a `timeout` option,\nwhich accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:\n\n```python\nfrom dodopayments import DodoPayments\n\n# Configure the default for all requests:\nclient = DodoPayments(\n # 20 seconds (default is 1 minute)\n timeout=20.0,\n)\n\n# More granular control:\nclient = DodoPayments(\n timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),\n)\n\n# Override per-request:\nclient.with_options(timeout = 5.0).checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\n```\n\nOn timeout, an `APITimeoutError` is thrown.\n\nNote that requests that time out are [retried twice by default](#retries).\n\n\n\n## Advanced\n\n### Logging\n\nWe use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.\n\nYou can enable logging by setting the environment variable `DODO_PAYMENTS_LOG` to `info`.\n\n```shell\n$ export DODO_PAYMENTS_LOG=info\n```\n\nOr to `debug` for more verbose logging.\n\n### How to tell whether `None` means `null` or missing\n\nIn an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:\n\n```py\nif response.my_field is None:\n if \'my_field\' not in response.model_fields_set:\n print(\'Got json like {}, without a "my_field" key present at all.\')\n else:\n print(\'Got json like {"my_field": null}.\')\n```\n\n### Accessing raw response data (e.g. headers)\n\nThe "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,\n\n```py\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\nresponse = client.checkout_sessions.with_raw_response.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\nprint(response.headers.get(\'X-My-Header\'))\n\ncheckout_session = response.parse() # get the object that `checkout_sessions.create()` would have returned\nprint(checkout_session.session_id)\n```\n\nThese methods return an [`APIResponse`](https://github.com/dodopayments/dodopayments-python/tree/main/src/dodopayments/_response.py) object.\n\nThe async client returns an [`AsyncAPIResponse`](https://github.com/dodopayments/dodopayments-python/tree/main/src/dodopayments/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.\n\n#### `.with_streaming_response`\n\nThe above interface eagerly reads the full response body when you make the request, which may not always be what you want.\n\nTo stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.\n\n```python\nwith client.checkout_sessions.with_streaming_response.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n) as response :\n print(response.headers.get(\'X-My-Header\'))\n\n for line in response.iter_lines():\n print(line)\n```\n\nThe context manager is required so that the response will reliably be closed.\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API.\n\nIf you need to access undocumented endpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other\nhttp verbs. Options on the client will be respected (such as retries) when making this request.\n\n```py\nimport httpx\n\nresponse = client.post(\n "/foo",\n cast_to=httpx.Response,\n body={"my_param": True},\n)\n\nprint(response.headers.get("x-foo"))\n```\n\n#### Undocumented request params\n\nIf you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You\ncan also get all the extra fields on the Pydantic model as a dict with\n[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).\n\n### Configuring the HTTP client\n\nYou can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:\n\n- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)\n- Custom [transports](https://www.python-httpx.org/advanced/transports/)\n- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality\n\n```python\nimport httpx\nfrom dodopayments import DodoPayments, DefaultHttpxClient\n\nclient = DodoPayments(\n # Or use the `DODO_PAYMENTS_BASE_URL` env var\n base_url="http://my.test.server.example.com:8083",\n http_client=DefaultHttpxClient(proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0")),\n)\n```\n\nYou can also customize the client on a per-request basis by using `with_options()`:\n\n```python\nclient.with_options(http_client=DefaultHttpxClient(...))\n```\n\n### Managing HTTP resources\n\nBy default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.\n\n```py\nfrom dodopayments import DodoPayments\n\nwith DodoPayments() as client:\n # make requests here\n ...\n\n# HTTP client is now closed\n```\n\n## Versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-python/issues) with questions, bugs, or suggestions.\n\n### Determining the installed version\n\nIf you\'ve upgraded to the latest version but aren\'t seeing any new features you were expecting then your python environment is likely still using an older version.\n\nYou can determine the version that is being used at runtime with:\n\n```py\nimport dodopayments\nprint(dodopayments.__version__)\n```\n\n## Requirements\n\nPython 3.9 or higher.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n',
|
|
6920
|
+
content: '# Dodo Payments Python API library\n\n<!-- prettier-ignore -->\n[)](https://pypi.org/project/dodopayments/)\n\nThe Dodo Payments Python library provides convenient access to the Dodo Payments REST API from any Python 3.9+\napplication. The library includes type definitions for all request params and response fields,\nand offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).\n\n\n\n\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Documentation\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). The full API of this library can be found in [api.md](api.md).\n\n## Installation\n\n```sh\n# install from PyPI\npip install dodopayments\n```\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n```python\nimport os\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments(\n bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), # This is the default and can be omitted\n # defaults to "live_mode".\n environment="test_mode",\n)\n\ncheckout_session_response = client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\nprint(checkout_session_response.session_id)\n```\n\nWhile you can provide a `bearer_token` keyword argument,\nwe recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)\nto add `DODO_PAYMENTS_API_KEY="My Bearer Token"` to your `.env` file\nso that your Bearer Token is not stored in source control.\n\n## Async usage\n\nSimply import `AsyncDodoPayments` instead of `DodoPayments` and use `await` with each API call:\n\n```python\nimport os\nimport asyncio\nfrom dodopayments import AsyncDodoPayments\n\nclient = AsyncDodoPayments(\n bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), # This is the default and can be omitted\n # defaults to "live_mode".\n environment="test_mode",\n)\n\nasync def main() -> None:\n checkout_session_response = await client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n )\n print(checkout_session_response.session_id)\n\nasyncio.run(main())\n```\n\nFunctionality between the synchronous and asynchronous clients is otherwise identical.\n\n### With aiohttp\n\nBy default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.\n\nYou can enable this by installing `aiohttp`:\n\n```sh\n# install from PyPI\npip install dodopayments[aiohttp]\n```\n\nThen you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:\n\n```python\nimport os\nimport asyncio\nfrom dodopayments import DefaultAioHttpClient\nfrom dodopayments import AsyncDodoPayments\n\nasync def main() -> None:\n async with AsyncDodoPayments(\n bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), # This is the default and can be omitted\n http_client=DefaultAioHttpClient(),\n) as client:\n checkout_session_response = await client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n )\n print(checkout_session_response.session_id)\n\nasyncio.run(main())\n```\n\n\n\n## Using types\n\nNested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like:\n\n- Serializing back into JSON, `model.to_json()`\n- Converting to a dictionary, `model.to_dict()`\n\nTyped requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.\n\n## Pagination\n\nList methods in the Dodo Payments API are paginated.\n\nThis library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:\n\n```python\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\n\nall_payments = []\n# Automatically fetches more pages as needed.\nfor payment in client.payments.list():\n # Do something with payment here\n all_payments.append(payment)\nprint(all_payments)\n```\n\nOr, asynchronously:\n\n```python\nimport asyncio\nfrom dodopayments import AsyncDodoPayments\n\nclient = AsyncDodoPayments()\n\nasync def main() -> None:\n all_payments = []\n # Iterate through items across all pages, issuing requests as needed.\n async for payment in client.payments.list():\n all_payments.append(payment)\n print(all_payments)\n\nasyncio.run(main())\n```\n\nAlternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages:\n\n```python\nfirst_page = await client.payments.list()\nif first_page.has_next_page():\n print(f"will fetch next page using these details: {first_page.next_page_info()}")\n next_page = await first_page.get_next_page()\n print(f"number of items we just fetched: {len(next_page.items)}")\n\n# Remove `await` for non-async usage.\n```\n\nOr just work directly with the returned data:\n\n```python\nfirst_page = await client.payments.list()\nfor payment in first_page.items:\n print(payment.brand_id)\n\n# Remove `await` for non-async usage.\n```\n\n## Nested params\n\nNested parameters are dictionaries, typed using `TypedDict`, for example:\n\n```python\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\n\ncheckout_session_response = client.checkout_sessions.create(\n product_cart=[{\n "product_id": "product_id",\n "quantity": 0,\n }],\n billing_address={\n "country": "AF"\n },\n)\nprint(checkout_session_response.billing_address)\n```\n\n\n\n## Handling errors\n\nWhen the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `dodopayments.APIConnectionError` is raised.\n\nWhen the API returns a non-success status code (that is, 4xx or 5xx\nresponse), a subclass of `dodopayments.APIStatusError` is raised, containing `status_code` and `response` properties.\n\nAll errors inherit from `dodopayments.APIError`.\n\n```python\nimport dodopayments\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\n\ntry:\n client.checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n )\nexcept dodopayments.APIConnectionError as e:\n print("The server could not be reached")\n print(e.__cause__) # an underlying Exception, likely raised within httpx.\nexcept dodopayments.RateLimitError as e:\n print("A 429 status code was received; we should back off a bit.")\nexcept dodopayments.APIStatusError as e:\n print("Another non-200-range status code was received")\n print(e.status_code)\n print(e.response)\n```\n\nError codes are as follows:\n\n| Status Code | Error Type |\n| ----------- | -------------------------- |\n| 400 | `BadRequestError` |\n| 401 | `AuthenticationError` |\n| 403 | `PermissionDeniedError` |\n| 404 | `NotFoundError` |\n| 422 | `UnprocessableEntityError` |\n| 429 | `RateLimitError` |\n| >=500 | `InternalServerError` |\n| N/A | `APIConnectionError` |\n\n### Retries\n\nCertain errors are automatically retried 2 times by default, with a short exponential backoff.\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,\n429 Rate Limit, and >=500 Internal errors are all retried by default.\n\nYou can use the `max_retries` option to configure or disable retry settings:\n\n```python\nfrom dodopayments import DodoPayments\n\n# Configure the default for all requests:\nclient = DodoPayments(\n # default is 2\n max_retries=0,\n)\n\n# Or, configure per-request:\nclient.with_options(max_retries = 5).checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\n```\n\n### Timeouts\n\nBy default requests time out after 1 minute. You can configure this with a `timeout` option,\nwhich accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:\n\n```python\nfrom dodopayments import DodoPayments\n\n# Configure the default for all requests:\nclient = DodoPayments(\n # 20 seconds (default is 1 minute)\n timeout=20.0,\n)\n\n# More granular control:\nclient = DodoPayments(\n timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),\n)\n\n# Override per-request:\nclient.with_options(timeout = 5.0).checkout_sessions.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\n```\n\nOn timeout, an `APITimeoutError` is thrown.\n\nNote that requests that time out are [retried twice by default](#retries).\n\n\n\n## Advanced\n\n### Logging\n\nWe use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.\n\nYou can enable logging by setting the environment variable `DODO_PAYMENTS_LOG` to `info`.\n\n```shell\n$ export DODO_PAYMENTS_LOG=info\n```\n\nOr to `debug` for more verbose logging.\n\n### How to tell whether `None` means `null` or missing\n\nIn an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:\n\n```py\nif response.my_field is None:\n if \'my_field\' not in response.model_fields_set:\n print(\'Got json like {}, without a "my_field" key present at all.\')\n else:\n print(\'Got json like {"my_field": null}.\')\n```\n\n### Accessing raw response data (e.g. headers)\n\nThe "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,\n\n```py\nfrom dodopayments import DodoPayments\n\nclient = DodoPayments()\nresponse = client.checkout_sessions.with_raw_response.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n)\nprint(response.headers.get(\'X-My-Header\'))\n\ncheckout_session = response.parse() # get the object that `checkout_sessions.create()` would have returned\nprint(checkout_session.session_id)\n```\n\nThese methods return an [`APIResponse`](https://github.com/dodopayments/dodopayments-python/tree/main/src/dodopayments/_response.py) object.\n\nThe async client returns an [`AsyncAPIResponse`](https://github.com/dodopayments/dodopayments-python/tree/main/src/dodopayments/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.\n\n#### `.with_streaming_response`\n\nThe above interface eagerly reads the full response body when you make the request, which may not always be what you want.\n\nTo stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.\n\n```python\nwith client.checkout_sessions.with_streaming_response.create(\n product_cart=[{\n "product_id": "pdt_example",\n "quantity": 1,\n }],\n) as response :\n print(response.headers.get(\'X-My-Header\'))\n\n for line in response.iter_lines():\n print(line)\n```\n\nThe context manager is required so that the response will reliably be closed.\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API.\n\nIf you need to access undocumented endpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other\nhttp verbs. Options on the client will be respected (such as retries) when making this request.\n\n```py\nimport httpx\n\nresponse = client.post(\n "/foo",\n cast_to=httpx.Response,\n body={"my_param": True},\n)\n\nprint(response.headers.get("x-foo"))\n```\n\n#### Undocumented request params\n\nIf you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You\ncan also get all the extra fields on the Pydantic model as a dict with\n[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).\n\n### Configuring the HTTP client\n\nYou can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:\n\n- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)\n- Custom [transports](https://www.python-httpx.org/advanced/transports/)\n- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality\n\n```python\nimport httpx\nfrom dodopayments import DodoPayments, DefaultHttpxClient\n\nclient = DodoPayments(\n # Or use the `DODO_PAYMENTS_BASE_URL` env var\n base_url="http://my.test.server.example.com:8083",\n http_client=DefaultHttpxClient(proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0")),\n)\n```\n\nYou can also customize the client on a per-request basis by using `with_options()`:\n\n```python\nclient.with_options(http_client=DefaultHttpxClient(...))\n```\n\n### Managing HTTP resources\n\nBy default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.\n\n```py\nfrom dodopayments import DodoPayments\n\nwith DodoPayments() as client:\n # make requests here\n ...\n\n# HTTP client is now closed\n```\n\n## Versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-python/issues) with questions, bugs, or suggestions.\n\n### Determining the installed version\n\nIf you\'ve upgraded to the latest version but aren\'t seeing any new features you were expecting then your python environment is likely still using an older version.\n\nYou can determine the version that is being used at runtime with:\n\n```py\nimport dodopayments\nprint(dodopayments.__version__)\n```\n\n## Requirements\n\nPython 3.9 or higher.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n',
|
|
6911
6921
|
},
|
|
6912
6922
|
{
|
|
6913
6923
|
language: 'java',
|
|
6914
|
-
content: '# Dodo Payments Java API Library\n\n<!-- x-release-please-start-version -->\n[](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-java/0.0.1)\n[](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-java/0.0.1)\n<!-- x-release-please-end -->\n\nThe Dodo Payments Java SDK provides convenient access to the [Dodo Payments REST API](https://docs.dodopayments.com/api-reference/introduction) from applications written in Java.\n\nThe Dodo Payments Java SDK is similar to the Dodo Payments Kotlin SDK but with minor differences that make it more ergonomic for use in Java, such as `Optional` instead of nullable values, `Stream` instead of `Sequence`, and `CompletableFuture` instead of suspend functions.\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n[](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22dodopayments-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22dodopayments-mcp%22%5D%2C%22env%22%3A%7B%22DODO_PAYMENTS_API_KEY%22%3A%22My%20Bearer%20Token%22%2C%22DODO_PAYMENTS_WEBHOOK_KEY%22%3A%22My%20Webhook%20Key%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n<!-- x-release-please-start-version -->\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-java/0.0.1).\n\n<!-- x-release-please-end -->\n\n## Installation\n\n<!-- x-release-please-start-version -->\n\n### Gradle\n\n~~~kotlin\nimplementation("com.dodopayments.api:dodo-payments-java:0.0.1")\n~~~\n\n### Maven\n\n~~~xml\n<dependency>\n <groupId>com.dodopayments.api</groupId>\n <artifactId>dodo-payments-java</artifactId>\n <version>0.0.1</version>\n</dependency>\n~~~\n\n<!-- x-release-please-end -->\n\n## Requirements\n\nThis library requires Java 8 or later.\n\n## Usage\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params);\n```\n\n## Client configuration\n\nConfigure the client using system properties or environment variables:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();\n```\n\nOr manually:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .bearerToken("My Bearer Token")\n .build();\n```\n\nOr using a combination of the two approaches:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n // Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n // Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\n .fromEnv()\n .bearerToken("My Bearer Token")\n .build();\n```\n\nSee this table for the available options:\n\n| Setter | System property | Environment variable | Required | Default value |\n| ------------- | ------------------------- | --------------------------- | -------- | --------------------------------- |\n| `bearerToken` | `dodopayments.apiKey` | `DODO_PAYMENTS_API_KEY` | true | - |\n| `webhookKey` | `dodopayments.webhookKey` | `DODO_PAYMENTS_WEBHOOK_KEY` | false | - |\n| `baseUrl` | `dodopayments.baseUrl` | `DODO_PAYMENTS_BASE_URL` | true | `"https://live.dodopayments.com"` |\n\nSystem properties take precedence over environment variables.\n\n> [!TIP]\n> Don\'t create more than one client in the same application. Each client has a connection pool and\n> thread pools, which are more efficient to share between requests.\n\n### Modifying configuration\n\nTo temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\n\nDodoPaymentsClient clientWithOptions = client.withOptions(optionsBuilder -> {\n optionsBuilder.baseUrl("https://example.com");\n optionsBuilder.maxRetries(42);\n});\n```\n\nThe `withOptions()` method does not affect the original client or service.\n\n## Requests and responses\n\nTo send a request to the Dodo Payments API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class.\n\nFor example, `client.checkoutSessions().create(...)` should be called with an instance of `CheckoutSessionCreateParams`, and it will return an instance of `CheckoutSessionResponse`.\n\n## Immutability\n\nEach class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it.\n\nEach class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy.\n\nBecause each class is immutable, builder modification will _never_ affect already built class instances.\n\n## Asynchronous execution\n\nThe default client is synchronous. To switch to asynchronous execution, call the `async()` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\nimport java.util.concurrent.CompletableFuture;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nCompletableFuture<CheckoutSessionResponse> checkoutSessionResponse = client.async().checkoutSessions().create(params);\n```\n\nOr create an asynchronous client from the beginning:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClientAsync;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\nimport java.util.concurrent.CompletableFuture;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClientAsync client = DodoPaymentsOkHttpClientAsync.fromEnv();\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nCompletableFuture<CheckoutSessionResponse> checkoutSessionResponse = client.checkoutSessions().create(params);\n```\n\nThe asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s.\n\n\n\n\n\n## Binary responses\n\nThe SDK defines methods that return binary responses, which are used for API responses that shouldn\'t necessarily be parsed, like non-JSON data.\n\nThese methods return [`HttpResponse`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/http/HttpResponse.kt):\n\n```java\nimport com.dodopayments.api.core.http.HttpResponse;\nimport com.dodopayments.api.models.invoices.payments.PaymentRetrieveParams;\n\nHttpResponse payment = client.invoices().payments().retrieve("payment_id");\n```\n\nTo save the response content to a file, use the [`Files.copy(...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-) method:\n\n```java\nimport com.dodopayments.api.core.http.HttpResponse;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\n\ntry (HttpResponse response = client.invoices().payments().retrieve(params)) {\n Files.copy(\n response.body(),\n Paths.get(path),\n StandardCopyOption.REPLACE_EXISTING\n );\n} catch (Exception e) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(e);\n}\n```\n\nOr transfer the response content to any [`OutputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html):\n\n```java\nimport com.dodopayments.api.core.http.HttpResponse;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\n\ntry (HttpResponse response = client.invoices().payments().retrieve(params)) {\n response.body().transferTo(Files.newOutputStream(Paths.get(path)));\n} catch (Exception e) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(e);\n}\n```\n\n## Raw responses\n\nThe SDK defines methods that deserialize responses into instances of Java classes. However, these methods don\'t provide access to the response headers, status code, or the raw response body.\n\nTo access this data, prefix any HTTP method call on a client or service with `withRawResponse()`:\n\n```java\nimport com.dodopayments.api.core.http.Headers;\nimport com.dodopayments.api.core.http.HttpResponseFor;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nHttpResponseFor<CheckoutSessionResponse> checkoutSessionResponse = client.checkoutSessions().withRawResponse().create(params);\n\nint statusCode = checkoutSessionResponse.statusCode();\nHeaders headers = checkoutSessionResponse.headers();\n```\n\nYou can still deserialize the response into an instance of a Java class if needed:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse parsedCheckoutSessionResponse = checkoutSessionResponse.parse();\n```\n\n## Error handling\n\nThe SDK throws custom unchecked exception types:\n\n- [`DodoPaymentsServiceException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:\n\n | Status | Exception |\n | ------ | -------------------------------------------------- |\n | 400 | [`BadRequestException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/BadRequestException.kt) |\n | 401 | [`UnauthorizedException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/UnauthorizedException.kt) |\n | 403 | [`PermissionDeniedException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/PermissionDeniedException.kt) |\n | 404 | [`NotFoundException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/NotFoundException.kt) |\n | 422 | [`UnprocessableEntityException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/UnprocessableEntityException.kt) |\n | 429 | [`RateLimitException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/RateLimitException.kt) |\n | 5xx | [`InternalServerException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/InternalServerException.kt) |\n | others | [`UnexpectedStatusCodeException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/UnexpectedStatusCodeException.kt) |\n\n- [`DodoPaymentsIoException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsIoException.kt): I/O networking errors.\n\n- [`DodoPaymentsRetryableException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsRetryableException.kt): Generic error indicating a failure that could be retried by the client.\n\n- [`DodoPaymentsInvalidDataException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that\'s supposed to be required, but the API unexpectedly omitted it from the response.\n\n- [`DodoPaymentsException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.\n\n## Pagination\n\nThe SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.\n\n### Auto-pagination\n\nTo iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed.\n\nWhen using the synchronous client, the method returns an [`Iterable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)\n\n```java\nimport com.dodopayments.api.models.payments.PaymentListPage;\nimport com.dodopayments.api.models.payments.PaymentListResponse;\n\nPaymentListPage page = client.payments().list();\n\n// Process as an Iterable\nfor (PaymentListResponse payment : page.autoPager()) {\n System.out.println(payment);\n}\n\n// Process as a Stream\npage.autoPager()\n .stream()\n .limit(50)\n .forEach(payment -> System.out.println(payment));\n```\n\nWhen using the asynchronous client, the method returns an [`AsyncStreamResponse`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/http/AsyncStreamResponse.kt):\n\n```java\nimport com.dodopayments.api.core.http.AsyncStreamResponse;\nimport com.dodopayments.api.models.payments.PaymentListPageAsync;\nimport com.dodopayments.api.models.payments.PaymentListResponse;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\n\nCompletableFuture<PaymentListPageAsync> pageFuture = client.async().payments().list();\n\npageFuture.thenRun(page -> page.autoPager().subscribe(payment -> {\n System.out.println(payment);\n}));\n\n// If you need to handle errors or completion of the stream\npageFuture.thenRun(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() {\n @Override\n public void onNext(PaymentListResponse payment) {\n System.out.println(payment);\n }\n\n @Override\n public void onComplete(Optional<Throwable> error) {\n if (error.isPresent()) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(error.get());\n } else {\n System.out.println("No more!");\n }\n }\n}));\n\n// Or use futures\npageFuture.thenRun(page -> page.autoPager()\n .subscribe(payment -> {\n System.out.println(payment);\n })\n .onCompleteFuture()\n .whenComplete((unused, error) -> {\n if (error != null) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(error);\n } else {\n System.out.println("No more!");\n }\n }));\n```\n\n### Manual pagination\n\nTo access individual page items and manually request the next page, use the `items()`,\n`hasNextPage()`, and `nextPage()` methods:\n\n```java\nimport com.dodopayments.api.models.payments.PaymentListPage;\nimport com.dodopayments.api.models.payments.PaymentListResponse;\n\nPaymentListPage page = client.payments().list();\nwhile (true) {\n for (PaymentListResponse payment : page.items()) {\n System.out.println(payment);\n }\n\n if (!page.hasNextPage()) {\n break;\n }\n\n page = page.nextPage();\n}\n```\n\n## Logging\n\nEnable logging by setting the `DODO_PAYMENTS_LOG` environment variable to `info`:\n\n```sh\nexport DODO_PAYMENTS_LOG=info\n```\n\nOr to `debug` for more verbose logging:\n\n```sh\nexport DODO_PAYMENTS_LOG=debug\n```\n\nOr configure the client manually using the `logLevel` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.core.LogLevel;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .logLevel(LogLevel.INFO)\n .build();\n```\n\n## ProGuard and R8\n\nAlthough the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `dodo-payments-java-core` is published with a [configuration file](dodo-payments-java-core/src/main/resources/META-INF/proguard/dodo-payments-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage).\n\nProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.\n\n\n\n\n\n## Jackson\n\nThe SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.\n\nThe SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).\n\nIf the SDK threw an exception, but you\'re _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt).\n\n> [!CAUTION]\n> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.\n\nAlso note that there are bugs in older Jackson versions that can affect the SDK. We don\'t work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead.\n\n## Network options\n\n### Retries\n\nThe SDK automatically retries 2 times by default, with a short exponential backoff between requests.\n\nOnly the following error types are retried:\n- Connection errors (for example, due to a network connectivity problem)\n- 408 Request Timeout\n- 409 Conflict\n- 429 Rate Limit\n- 5xx Internal\n\nThe API may also explicitly instruct the SDK to retry or not retry a request.\n\nTo set a custom number of retries, configure the client using the `maxRetries` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .maxRetries(4)\n .build();\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default.\n\nTo set a custom timeout, configure the method call using the `timeout` method:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()\n);\n```\n\nOr configure the default for all method calls at the client level:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport java.time.Duration;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .timeout(Duration.ofSeconds(30))\n .build();\n```\n\n### Proxies\n\nTo route requests through a proxy, configure the client using the `proxy` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport java.net.InetSocketAddress;\nimport java.net.Proxy;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(new Proxy(\n Proxy.Type.HTTP, new InetSocketAddress(\n "https://example.com", 8080\n )\n ))\n .build();\n```\n\nIf the proxy responds with `407 Proxy Authentication Required`, supply credentials by also configuring `proxyAuthenticator`:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.core.http.ProxyAuthenticator;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(...)\n // Or a custom implementation of `ProxyAuthenticator`.\n .proxyAuthenticator(ProxyAuthenticator.basic("username", "password"))\n .build();\n```\n\n### Connection pooling\n\nTo customize the underlying OkHttp connection pool, configure the client using the `maxIdleConnections` and `keepAliveDuration` methods:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport java.time.Duration;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa.\n .maxIdleConnections(10)\n .keepAliveDuration(Duration.ofMinutes(2))\n .build();\n```\n\nIf both options are unset, OkHttp\'s default connection pool settings are used.\n\n### HTTPS\n\n> [!NOTE]\n> Most applications should not call these methods, and instead use the system defaults. The defaults include\n> special optimizations that can be lost if the implementations are modified.\n\nTo configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa.\n .sslSocketFactory(yourSSLSocketFactory)\n .trustManager(yourTrustManager)\n .hostnameVerifier(yourHostnameVerifier)\n .build();\n```\n\n### Environments\n\nThe SDK sends requests to the live_mode by default. To send requests to a different environment, configure the client like so:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .testMode()\n .build();\n```\n\n### Custom HTTP client\n\nThe SDK consists of three artifacts:\n- `dodo-payments-java-core`\n - Contains core SDK logic\n - Does not depend on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsClient`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClient.kt), [`DodoPaymentsClientAsync`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsync.kt), [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt), and [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), all of which can work with any HTTP client\n- `dodo-payments-java-client-okhttp`\n - Depends on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) and [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), which provide a way to construct [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) and [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), respectively, using OkHttp\n- `dodo-payments-java`\n - Depends on and exposes the APIs of both `dodo-payments-java-core` and `dodo-payments-java-client-okhttp`\n - Does not have its own logic\n\nThis structure allows replacing the SDK\'s default HTTP client without pulling in unnecessary dependencies.\n\n#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html)\n\n> [!TIP]\n> Try the available [network options](#network-options) before replacing the default client.\n\nTo use a customized `OkHttpClient`:\n\n1. Replace your [`dodo-payments-java` dependency](#installation) with `dodo-payments-java-core`\n2. Copy `dodo-payments-java-client-okhttp`\'s [`OkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/OkHttpClient.kt) class into your code and customize it\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your customized client\n\n### Completely custom HTTP client\n\nTo use a completely custom HTTP client:\n\n1. Replace your [`dodo-payments-java` dependency](#installation) with `dodo-payments-java-core`\n2. Write a class that implements the [`HttpClient`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/http/HttpClient.kt) interface\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your new client class\n\n## Undocumented API functionality\n\nThe SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.\n\n### Parameters\n\nTo set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:\n\n```java\nimport com.dodopayments.api.core.JsonValue;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams;\n\nCheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder()\n .putAdditionalHeader("Secret-Header", "42")\n .putAdditionalQueryParam("secret_query_param", "42")\n .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))\n .build();\n```\n\nThese can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.\n\nTo set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) object to its setter:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\nCheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .build();\n```\n\nThe most straightforward way to create a [`JsonValue`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) is using its `from(...)` method:\n\n```java\nimport com.dodopayments.api.core.JsonValue;\nimport java.util.List;\nimport java.util.Map;\n\n// Create primitive JSON values\nJsonValue nullValue = JsonValue.from(null);\nJsonValue booleanValue = JsonValue.from(true);\nJsonValue numberValue = JsonValue.from(42);\nJsonValue stringValue = JsonValue.from("Hello World!");\n\n// Create a JSON array value equivalent to `["Hello", "World"]`\nJsonValue arrayValue = JsonValue.from(List.of(\n "Hello", "World"\n));\n\n// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`\nJsonValue objectValue = JsonValue.from(Map.of(\n "a", 1,\n "b", 2\n));\n\n// Create an arbitrarily nested JSON equivalent to:\n// {\n// "a": [1, 2],\n// "b": [3, 4]\n// }\nJsonValue complexValue = JsonValue.from(Map.of(\n "a", List.of(\n 1, 2\n ),\n "b", List.of(\n 3, 4\n )\n));\n```\n\nNormally a `Builder` class\'s `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.\n\nTo forcibly omit a required parameter or property, pass [`JsonMissing`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/Values.kt):\n\n```java\nimport com.dodopayments.api.core.JsonMissing;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\nCheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .productCart(JsonMissing.of())\n .build();\n```\n\n### Response properties\n\nTo access undocumented response properties, call the `_additionalProperties()` method:\n\n```java\nimport com.dodopayments.api.core.JsonValue;\nimport java.util.Map;\n\nMap<String, JsonValue> additionalProperties = client.checkoutSessions().create(params)._additionalProperties();\nJsonValue secretPropertyValue = additionalProperties.get("secretProperty");\n\nString result = secretPropertyValue.accept(new JsonValue.Visitor<>() {\n @Override\n public String visitNull() {\n return "It\'s null!";\n }\n\n @Override\n public String visitBoolean(boolean value) {\n return "It\'s a boolean!";\n }\n\n @Override\n public String visitNumber(Number value) {\n return "It\'s a number!";\n }\n\n // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`\n // The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden\n});\n```\n\nTo access a property\'s raw JSON value, which may be undocumented, call its `_` prefixed method:\n\n```java\nimport com.dodopayments.api.core.JsonField;\nimport java.util.Optional;\n\nJsonField<Object> field = client.checkoutSessions().create(params)._field();\n\nif (field.isMissing()) {\n // The property is absent from the JSON response\n} else if (field.isNull()) {\n // The property was set to literal null\n} else {\n // Check if value was provided as a string\n // Other methods include `asNumber()`, `asBoolean()`, etc.\n Optional<String> jsonString = field.asString();\n\n // Try to deserialize into a custom type\n MyClass myObject = field.asUnknown().orElseThrow().convert(MyClass.class);\n}\n```\n\n### Response validation\n\nIn rare cases, the API may return a response that doesn\'t match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else.\n\nBy default, the SDK will not throw an exception in this case. It will throw [`DodoPaymentsInvalidDataException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt) only if you directly access the property.\n\nValidating the response is _not_ forwards compatible with new types from the API for existing fields.\n\nIf you would still prefer to check that the response is completely well-typed upfront, then either call `validate()`:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params).validate();\n```\n\nOr configure the method call to validate the response using the `responseValidation` method:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().responseValidation(true).build()\n);\n```\n\nOr configure the default for all method calls at the client level:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .responseValidation(true)\n .build();\n```\n\n## FAQ\n\n### Why don\'t you use plain `enum` classes?\n\nJava `enum` classes are not trivially [forwards compatible](https://www.stainless.com/blog/making-java-enums-forwards-compatible). Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.\n\n### Why do you represent fields using `JsonField<T>` instead of just plain `T`?\n\nUsing `JsonField<T>` enables a few features:\n\n- Allowing usage of [undocumented API functionality](#undocumented-api-functionality)\n- Lazily [validating the API response against the expected shape](#response-validation)\n- Representing absent vs explicitly null values\n\n### Why don\'t you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)?\n\nIt is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don\'t want to introduce a breaking change every time we add a field to a class.\n\n### Why don\'t you use checked exceptions?\n\nChecked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.\n\nChecked exceptions:\n\n- Are verbose to handle\n- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error\n- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function)\n- Don\'t play well with lambdas (also due to the function coloring problem)\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-java/issues) with questions, bugs, or suggestions.\n',
|
|
6924
|
+
content: '# Dodo Payments Java API Library\n\n<!-- x-release-please-start-version -->\n[](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-java/0.0.1)\n[](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-java/0.0.1)\n<!-- x-release-please-end -->\n\nThe Dodo Payments Java SDK provides convenient access to the [Dodo Payments REST API](https://docs.dodopayments.com/api-reference/introduction) from applications written in Java.\n\nThe Dodo Payments Java SDK is similar to the Dodo Payments Kotlin SDK but with minor differences that make it more ergonomic for use in Java, such as `Optional` instead of nullable values, `Stream` instead of `Sequence`, and `CompletableFuture` instead of suspend functions.\n\n\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n\n> Note: You may need to set environment variables in your MCP client.\n\n<!-- x-release-please-start-version -->\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-java/0.0.1).\n\n<!-- x-release-please-end -->\n\n## Installation\n\n<!-- x-release-please-start-version -->\n\n### Gradle\n\n~~~kotlin\nimplementation("com.dodopayments.api:dodo-payments-java:0.0.1")\n~~~\n\n### Maven\n\n~~~xml\n<dependency>\n <groupId>com.dodopayments.api</groupId>\n <artifactId>dodo-payments-java</artifactId>\n <version>0.0.1</version>\n</dependency>\n~~~\n\n<!-- x-release-please-end -->\n\n## Requirements\n\nThis library requires Java 8 or later.\n\n## Usage\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params);\n```\n\n## Client configuration\n\nConfigure the client using system properties or environment variables:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();\n```\n\nOr manually:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .bearerToken("My Bearer Token")\n .build();\n```\n\nOr using a combination of the two approaches:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n // Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n // Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\n .fromEnv()\n .bearerToken("My Bearer Token")\n .build();\n```\n\nSee this table for the available options:\n\n| Setter | System property | Environment variable | Required | Default value |\n| ------------- | ------------------------- | --------------------------- | -------- | --------------------------------- |\n| `bearerToken` | `dodopayments.apiKey` | `DODO_PAYMENTS_API_KEY` | true | - |\n| `webhookKey` | `dodopayments.webhookKey` | `DODO_PAYMENTS_WEBHOOK_KEY` | false | - |\n| `baseUrl` | `dodopayments.baseUrl` | `DODO_PAYMENTS_BASE_URL` | true | `"https://live.dodopayments.com"` |\n\nSystem properties take precedence over environment variables.\n\n> [!TIP]\n> Don\'t create more than one client in the same application. Each client has a connection pool and\n> thread pools, which are more efficient to share between requests.\n\n### Modifying configuration\n\nTo temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\n\nDodoPaymentsClient clientWithOptions = client.withOptions(optionsBuilder -> {\n optionsBuilder.baseUrl("https://example.com");\n optionsBuilder.maxRetries(42);\n});\n```\n\nThe `withOptions()` method does not affect the original client or service.\n\n## Requests and responses\n\nTo send a request to the Dodo Payments API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class.\n\nFor example, `client.checkoutSessions().create(...)` should be called with an instance of `CheckoutSessionCreateParams`, and it will return an instance of `CheckoutSessionResponse`.\n\n## Immutability\n\nEach class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it.\n\nEach class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy.\n\nBecause each class is immutable, builder modification will _never_ affect already built class instances.\n\n## Asynchronous execution\n\nThe default client is synchronous. To switch to asynchronous execution, call the `async()` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\nimport java.util.concurrent.CompletableFuture;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv();\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nCompletableFuture<CheckoutSessionResponse> checkoutSessionResponse = client.async().checkoutSessions().create(params);\n```\n\nOr create an asynchronous client from the beginning:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClientAsync;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\nimport java.util.concurrent.CompletableFuture;\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nDodoPaymentsClientAsync client = DodoPaymentsOkHttpClientAsync.fromEnv();\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nCompletableFuture<CheckoutSessionResponse> checkoutSessionResponse = client.checkoutSessions().create(params);\n```\n\nThe asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s.\n\n\n\n\n\n## Binary responses\n\nThe SDK defines methods that return binary responses, which are used for API responses that shouldn\'t necessarily be parsed, like non-JSON data.\n\nThese methods return [`HttpResponse`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/http/HttpResponse.kt):\n\n```java\nimport com.dodopayments.api.core.http.HttpResponse;\nimport com.dodopayments.api.models.invoices.payments.PaymentRetrieveParams;\n\nHttpResponse payment = client.invoices().payments().retrieve("payment_id");\n```\n\nTo save the response content to a file, use the [`Files.copy(...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-) method:\n\n```java\nimport com.dodopayments.api.core.http.HttpResponse;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\n\ntry (HttpResponse response = client.invoices().payments().retrieve(params)) {\n Files.copy(\n response.body(),\n Paths.get(path),\n StandardCopyOption.REPLACE_EXISTING\n );\n} catch (Exception e) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(e);\n}\n```\n\nOr transfer the response content to any [`OutputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html):\n\n```java\nimport com.dodopayments.api.core.http.HttpResponse;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\n\ntry (HttpResponse response = client.invoices().payments().retrieve(params)) {\n response.body().transferTo(Files.newOutputStream(Paths.get(path)));\n} catch (Exception e) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(e);\n}\n```\n\n## Raw responses\n\nThe SDK defines methods that deserialize responses into instances of Java classes. However, these methods don\'t provide access to the response headers, status code, or the raw response body.\n\nTo access this data, prefix any HTTP method call on a client or service with `withRawResponse()`:\n\n```java\nimport com.dodopayments.api.core.http.Headers;\nimport com.dodopayments.api.core.http.HttpResponseFor;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\nCheckoutSessionRequest params = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build();\nHttpResponseFor<CheckoutSessionResponse> checkoutSessionResponse = client.checkoutSessions().withRawResponse().create(params);\n\nint statusCode = checkoutSessionResponse.statusCode();\nHeaders headers = checkoutSessionResponse.headers();\n```\n\nYou can still deserialize the response into an instance of a Java class if needed:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse parsedCheckoutSessionResponse = checkoutSessionResponse.parse();\n```\n\n## Error handling\n\nThe SDK throws custom unchecked exception types:\n\n- [`DodoPaymentsServiceException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:\n\n | Status | Exception |\n | ------ | -------------------------------------------------- |\n | 400 | [`BadRequestException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/BadRequestException.kt) |\n | 401 | [`UnauthorizedException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/UnauthorizedException.kt) |\n | 403 | [`PermissionDeniedException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/PermissionDeniedException.kt) |\n | 404 | [`NotFoundException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/NotFoundException.kt) |\n | 422 | [`UnprocessableEntityException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/UnprocessableEntityException.kt) |\n | 429 | [`RateLimitException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/RateLimitException.kt) |\n | 5xx | [`InternalServerException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/InternalServerException.kt) |\n | others | [`UnexpectedStatusCodeException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/UnexpectedStatusCodeException.kt) |\n\n- [`DodoPaymentsIoException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsIoException.kt): I/O networking errors.\n\n- [`DodoPaymentsRetryableException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsRetryableException.kt): Generic error indicating a failure that could be retried by the client.\n\n- [`DodoPaymentsInvalidDataException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that\'s supposed to be required, but the API unexpectedly omitted it from the response.\n\n- [`DodoPaymentsException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.\n\n## Pagination\n\nThe SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.\n\n### Auto-pagination\n\nTo iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed.\n\nWhen using the synchronous client, the method returns an [`Iterable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)\n\n```java\nimport com.dodopayments.api.models.payments.PaymentListPage;\nimport com.dodopayments.api.models.payments.PaymentListResponse;\n\nPaymentListPage page = client.payments().list();\n\n// Process as an Iterable\nfor (PaymentListResponse payment : page.autoPager()) {\n System.out.println(payment);\n}\n\n// Process as a Stream\npage.autoPager()\n .stream()\n .limit(50)\n .forEach(payment -> System.out.println(payment));\n```\n\nWhen using the asynchronous client, the method returns an [`AsyncStreamResponse`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/http/AsyncStreamResponse.kt):\n\n```java\nimport com.dodopayments.api.core.http.AsyncStreamResponse;\nimport com.dodopayments.api.models.payments.PaymentListPageAsync;\nimport com.dodopayments.api.models.payments.PaymentListResponse;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\n\nCompletableFuture<PaymentListPageAsync> pageFuture = client.async().payments().list();\n\npageFuture.thenRun(page -> page.autoPager().subscribe(payment -> {\n System.out.println(payment);\n}));\n\n// If you need to handle errors or completion of the stream\npageFuture.thenRun(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() {\n @Override\n public void onNext(PaymentListResponse payment) {\n System.out.println(payment);\n }\n\n @Override\n public void onComplete(Optional<Throwable> error) {\n if (error.isPresent()) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(error.get());\n } else {\n System.out.println("No more!");\n }\n }\n}));\n\n// Or use futures\npageFuture.thenRun(page -> page.autoPager()\n .subscribe(payment -> {\n System.out.println(payment);\n })\n .onCompleteFuture()\n .whenComplete((unused, error) -> {\n if (error != null) {\n System.out.println("Something went wrong!");\n throw new RuntimeException(error);\n } else {\n System.out.println("No more!");\n }\n }));\n```\n\n### Manual pagination\n\nTo access individual page items and manually request the next page, use the `items()`,\n`hasNextPage()`, and `nextPage()` methods:\n\n```java\nimport com.dodopayments.api.models.payments.PaymentListPage;\nimport com.dodopayments.api.models.payments.PaymentListResponse;\n\nPaymentListPage page = client.payments().list();\nwhile (true) {\n for (PaymentListResponse payment : page.items()) {\n System.out.println(payment);\n }\n\n if (!page.hasNextPage()) {\n break;\n }\n\n page = page.nextPage();\n}\n```\n\n## Logging\n\nEnable logging by setting the `DODO_PAYMENTS_LOG` environment variable to `info`:\n\n```sh\nexport DODO_PAYMENTS_LOG=info\n```\n\nOr to `debug` for more verbose logging:\n\n```sh\nexport DODO_PAYMENTS_LOG=debug\n```\n\nOr configure the client manually using the `logLevel` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.core.LogLevel;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .logLevel(LogLevel.INFO)\n .build();\n```\n\n## ProGuard and R8\n\nAlthough the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `dodo-payments-java-core` is published with a [configuration file](dodo-payments-java-core/src/main/resources/META-INF/proguard/dodo-payments-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage).\n\nProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.\n\n\n\n\n\n## Jackson\n\nThe SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.\n\nThe SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).\n\nIf the SDK threw an exception, but you\'re _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt).\n\n> [!CAUTION]\n> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.\n\nAlso note that there are bugs in older Jackson versions that can affect the SDK. We don\'t work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead.\n\n## Network options\n\n### Retries\n\nThe SDK automatically retries 2 times by default, with a short exponential backoff between requests.\n\nOnly the following error types are retried:\n- Connection errors (for example, due to a network connectivity problem)\n- 408 Request Timeout\n- 409 Conflict\n- 429 Rate Limit\n- 5xx Internal\n\nThe API may also explicitly instruct the SDK to retry or not retry a request.\n\nTo set a custom number of retries, configure the client using the `maxRetries` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .maxRetries(4)\n .build();\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default.\n\nTo set a custom timeout, configure the method call using the `timeout` method:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()\n);\n```\n\nOr configure the default for all method calls at the client level:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport java.time.Duration;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .timeout(Duration.ofSeconds(30))\n .build();\n```\n\n### Proxies\n\nTo route requests through a proxy, configure the client using the `proxy` method:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport java.net.InetSocketAddress;\nimport java.net.Proxy;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(new Proxy(\n Proxy.Type.HTTP, new InetSocketAddress(\n "https://example.com", 8080\n )\n ))\n .build();\n```\n\nIf the proxy responds with `407 Proxy Authentication Required`, supply credentials by also configuring `proxyAuthenticator`:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport com.dodopayments.api.core.http.ProxyAuthenticator;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(...)\n // Or a custom implementation of `ProxyAuthenticator`.\n .proxyAuthenticator(ProxyAuthenticator.basic("username", "password"))\n .build();\n```\n\n### Connection pooling\n\nTo customize the underlying OkHttp connection pool, configure the client using the `maxIdleConnections` and `keepAliveDuration` methods:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\nimport java.time.Duration;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa.\n .maxIdleConnections(10)\n .keepAliveDuration(Duration.ofMinutes(2))\n .build();\n```\n\nIf both options are unset, OkHttp\'s default connection pool settings are used.\n\n### HTTPS\n\n> [!NOTE]\n> Most applications should not call these methods, and instead use the system defaults. The defaults include\n> special optimizations that can be lost if the implementations are modified.\n\nTo configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa.\n .sslSocketFactory(yourSSLSocketFactory)\n .trustManager(yourTrustManager)\n .hostnameVerifier(yourHostnameVerifier)\n .build();\n```\n\n### Environments\n\nThe SDK sends requests to the live_mode by default. To send requests to a different environment, configure the client like so:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .testMode()\n .build();\n```\n\n### Custom HTTP client\n\nThe SDK consists of three artifacts:\n- `dodo-payments-java-core`\n - Contains core SDK logic\n - Does not depend on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsClient`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClient.kt), [`DodoPaymentsClientAsync`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsync.kt), [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt), and [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), all of which can work with any HTTP client\n- `dodo-payments-java-client-okhttp`\n - Depends on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) and [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), which provide a way to construct [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) and [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), respectively, using OkHttp\n- `dodo-payments-java`\n - Depends on and exposes the APIs of both `dodo-payments-java-core` and `dodo-payments-java-client-okhttp`\n - Does not have its own logic\n\nThis structure allows replacing the SDK\'s default HTTP client without pulling in unnecessary dependencies.\n\n#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html)\n\n> [!TIP]\n> Try the available [network options](#network-options) before replacing the default client.\n\nTo use a customized `OkHttpClient`:\n\n1. Replace your [`dodo-payments-java` dependency](#installation) with `dodo-payments-java-core`\n2. Copy `dodo-payments-java-client-okhttp`\'s [`OkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/OkHttpClient.kt) class into your code and customize it\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your customized client\n\n### Completely custom HTTP client\n\nTo use a completely custom HTTP client:\n\n1. Replace your [`dodo-payments-java` dependency](#installation) with `dodo-payments-java-core`\n2. Write a class that implements the [`HttpClient`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/http/HttpClient.kt) interface\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-java-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your new client class\n\n## Undocumented API functionality\n\nThe SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.\n\n### Parameters\n\nTo set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:\n\n```java\nimport com.dodopayments.api.core.JsonValue;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams;\n\nCheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder()\n .putAdditionalHeader("Secret-Header", "42")\n .putAdditionalQueryParam("secret_query_param", "42")\n .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))\n .build();\n```\n\nThese can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.\n\nTo set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) object to its setter:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\nCheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .build();\n```\n\nThe most straightforward way to create a [`JsonValue`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) is using its `from(...)` method:\n\n```java\nimport com.dodopayments.api.core.JsonValue;\nimport java.util.List;\nimport java.util.Map;\n\n// Create primitive JSON values\nJsonValue nullValue = JsonValue.from(null);\nJsonValue booleanValue = JsonValue.from(true);\nJsonValue numberValue = JsonValue.from(42);\nJsonValue stringValue = JsonValue.from("Hello World!");\n\n// Create a JSON array value equivalent to `["Hello", "World"]`\nJsonValue arrayValue = JsonValue.from(List.of(\n "Hello", "World"\n));\n\n// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`\nJsonValue objectValue = JsonValue.from(Map.of(\n "a", 1,\n "b", 2\n));\n\n// Create an arbitrarily nested JSON equivalent to:\n// {\n// "a": [1, 2],\n// "b": [3, 4]\n// }\nJsonValue complexValue = JsonValue.from(Map.of(\n "a", List.of(\n 1, 2\n ),\n "b", List.of(\n 3, 4\n )\n));\n```\n\nNormally a `Builder` class\'s `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.\n\nTo forcibly omit a required parameter or property, pass [`JsonMissing`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/core/Values.kt):\n\n```java\nimport com.dodopayments.api.core.JsonMissing;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams;\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest;\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq;\n\nCheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .productCart(JsonMissing.of())\n .build();\n```\n\n### Response properties\n\nTo access undocumented response properties, call the `_additionalProperties()` method:\n\n```java\nimport com.dodopayments.api.core.JsonValue;\nimport java.util.Map;\n\nMap<String, JsonValue> additionalProperties = client.checkoutSessions().create(params)._additionalProperties();\nJsonValue secretPropertyValue = additionalProperties.get("secretProperty");\n\nString result = secretPropertyValue.accept(new JsonValue.Visitor<>() {\n @Override\n public String visitNull() {\n return "It\'s null!";\n }\n\n @Override\n public String visitBoolean(boolean value) {\n return "It\'s a boolean!";\n }\n\n @Override\n public String visitNumber(Number value) {\n return "It\'s a number!";\n }\n\n // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`\n // The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden\n});\n```\n\nTo access a property\'s raw JSON value, which may be undocumented, call its `_` prefixed method:\n\n```java\nimport com.dodopayments.api.core.JsonField;\nimport java.util.Optional;\n\nJsonField<Object> field = client.checkoutSessions().create(params)._field();\n\nif (field.isMissing()) {\n // The property is absent from the JSON response\n} else if (field.isNull()) {\n // The property was set to literal null\n} else {\n // Check if value was provided as a string\n // Other methods include `asNumber()`, `asBoolean()`, etc.\n Optional<String> jsonString = field.asString();\n\n // Try to deserialize into a custom type\n MyClass myObject = field.asUnknown().orElseThrow().convert(MyClass.class);\n}\n```\n\n### Response validation\n\nIn rare cases, the API may return a response that doesn\'t match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else.\n\nBy default, the SDK will not throw an exception in this case. It will throw [`DodoPaymentsInvalidDataException`](dodo-payments-java-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt) only if you directly access the property.\n\nValidating the response is _not_ forwards compatible with new types from the API for existing fields.\n\nIf you would still prefer to check that the response is completely well-typed upfront, then either call `validate()`:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params).validate();\n```\n\nOr configure the method call to validate the response using the `responseValidation` method:\n\n```java\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse;\n\nCheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().responseValidation(true).build()\n);\n```\n\nOr configure the default for all method calls at the client level:\n\n```java\nimport com.dodopayments.api.client.DodoPaymentsClient;\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient;\n\nDodoPaymentsClient client = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .responseValidation(true)\n .build();\n```\n\n## FAQ\n\n### Why don\'t you use plain `enum` classes?\n\nJava `enum` classes are not trivially forwards compatible. Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.\n\n### Why do you represent fields using `JsonField<T>` instead of just plain `T`?\n\nUsing `JsonField<T>` enables a few features:\n\n- Allowing usage of [undocumented API functionality](#undocumented-api-functionality)\n- Lazily [validating the API response against the expected shape](#response-validation)\n- Representing absent vs explicitly null values\n\n### Why don\'t you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)?\n\nIt is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don\'t want to introduce a breaking change every time we add a field to a class.\n\n### Why don\'t you use checked exceptions?\n\nChecked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.\n\nChecked exceptions:\n\n- Are verbose to handle\n- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error\n- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function)\n- Don\'t play well with lambdas (also due to the function coloring problem)\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-java/issues) with questions, bugs, or suggestions.\n',
|
|
6915
6925
|
},
|
|
6916
6926
|
{
|
|
6917
6927
|
language: 'kotlin',
|
|
6918
|
-
content: '# Dodo Payments Kotlin API Library\n\n<!-- x-release-please-start-version -->\n[](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-kotlin/0.0.1)\n[](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-kotlin/0.0.1)\n<!-- x-release-please-end -->\n\nThe Dodo Payments Kotlin SDK provides convenient access to the [Dodo Payments REST API](https://docs.dodopayments.com/api-reference/introduction) from applications written in Kotlin.\n\nThe Dodo Payments Kotlin SDK is similar to the Dodo Payments Java SDK but with minor differences that make it more ergonomic for use in Kotlin, such as nullable values instead of `Optional`, `Sequence` instead of `Stream`, and suspend functions instead of `CompletableFuture`.\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n[](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22dodopayments-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22dodopayments-mcp%22%5D%2C%22env%22%3A%7B%22DODO_PAYMENTS_API_KEY%22%3A%22My%20Bearer%20Token%22%2C%22DODO_PAYMENTS_WEBHOOK_KEY%22%3A%22My%20Webhook%20Key%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n<!-- x-release-please-start-version -->\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). KDocs are available on [javadoc.io](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-kotlin/0.0.1).\n\n<!-- x-release-please-end -->\n\n## Installation\n\n<!-- x-release-please-start-version -->\n\n### Gradle\n\n~~~kotlin\nimplementation("com.dodopayments.api:dodo-payments-kotlin:0.0.1")\n~~~\n\n### Maven\n\n~~~xml\n<dependency>\n <groupId>com.dodopayments.api</groupId>\n <artifactId>dodo-payments-kotlin</artifactId>\n <version>0.0.1</version>\n</dependency>\n~~~\n\n<!-- x-release-please-end -->\n\n## Requirements\n\nThis library requires Java 8 or later.\n\n## Usage\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params)\n```\n\n## Client configuration\n\nConfigure the client using system properties or environment variables:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()\n```\n\nOr manually:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .bearerToken("My Bearer Token")\n .build()\n```\n\nOr using a combination of the two approaches:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n // Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n // Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\n .fromEnv()\n .bearerToken("My Bearer Token")\n .build()\n```\n\nSee this table for the available options:\n\n| Setter | System property | Environment variable | Required | Default value |\n| ------------- | ------------------------- | --------------------------- | -------- | --------------------------------- |\n| `bearerToken` | `dodopayments.apiKey` | `DODO_PAYMENTS_API_KEY` | true | - |\n| `webhookKey` | `dodopayments.webhookKey` | `DODO_PAYMENTS_WEBHOOK_KEY` | false | - |\n| `baseUrl` | `dodopayments.baseUrl` | `DODO_PAYMENTS_BASE_URL` | true | `"https://live.dodopayments.com"` |\n\nSystem properties take precedence over environment variables.\n\n> [!TIP]\n> Don\'t create more than one client in the same application. Each client has a connection pool and\n> thread pools, which are more efficient to share between requests.\n\n### Modifying configuration\n\nTo temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\n\nval clientWithOptions: DodoPaymentsClient = client.withOptions {\n it.baseUrl("https://example.com")\n it.maxRetries(42)\n}\n```\n\nThe `withOptions()` method does not affect the original client or service.\n\n## Requests and responses\n\nTo send a request to the Dodo Payments API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Kotlin class.\n\nFor example, `client.checkoutSessions().create(...)` should be called with an instance of `CheckoutSessionCreateParams`, and it will return an instance of `CheckoutSessionResponse`.\n\n## Immutability\n\nEach class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it.\n\nEach class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy.\n\nBecause each class is immutable, builder modification will _never_ affect already built class instances.\n\n## Asynchronous execution\n\nThe default client is synchronous. To switch to asynchronous execution, call the `async()` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: CheckoutSessionResponse = client.async().checkoutSessions().create(params)\n```\n\nOr create an asynchronous client from the beginning:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClientAsync\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClientAsync = DodoPaymentsOkHttpClientAsync.fromEnv()\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params)\n```\n\nThe asynchronous client supports the same options as the synchronous one, except most methods are [suspending](https://kotlinlang.org/docs/coroutines-guide.html).\n\n\n\n\n\n## Binary responses\n\nThe SDK defines methods that return binary responses, which are used for API responses that shouldn\'t necessarily be parsed, like non-JSON data.\n\nThese methods return [`HttpResponse`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/http/HttpResponse.kt):\n\n```kotlin\nimport com.dodopayments.api.core.http.HttpResponse\nimport com.dodopayments.api.models.invoices.payments.PaymentRetrieveParams\n\nval payment: HttpResponse = client.invoices().payments().retrieve("payment_id")\n```\n\nTo save the response content to a file, use the [`Files.copy(...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-) method:\n\n```kotlin\nimport java.nio.file.Files\nimport java.nio.file.Paths\nimport java.nio.file.StandardCopyOption\n\nclient.invoices().payments().retrieve(params).use {\n Files.copy(\n it.body(),\n Paths.get(path),\n StandardCopyOption.REPLACE_EXISTING\n )\n}\n```\n\nOr transfer the response content to any [`OutputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html):\n\n```kotlin\nimport java.nio.file.Files\nimport java.nio.file.Paths\n\nclient.invoices().payments().retrieve(params).use {\n it.body().transferTo(Files.newOutputStream(Paths.get(path)))\n}\n```\n\n## Raw responses\n\nThe SDK defines methods that deserialize responses into instances of Kotlin classes. However, these methods don\'t provide access to the response headers, status code, or the raw response body.\n\nTo access this data, prefix any HTTP method call on a client or service with `withRawResponse()`:\n\n```kotlin\nimport com.dodopayments.api.core.http.Headers\nimport com.dodopayments.api.core.http.HttpResponseFor\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: HttpResponseFor<CheckoutSessionResponse> = client.checkoutSessions().withRawResponse().create(params)\n\nval statusCode: Int = checkoutSessionResponse.statusCode()\nval headers: Headers = checkoutSessionResponse.headers()\n```\n\nYou can still deserialize the response into an instance of a Kotlin class if needed:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval parsedCheckoutSessionResponse: CheckoutSessionResponse = checkoutSessionResponse.parse()\n```\n\n## Error handling\n\nThe SDK throws custom unchecked exception types:\n\n- [`DodoPaymentsServiceException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:\n\n | Status | Exception |\n | ------ | -------------------------------------------------- |\n | 400 | [`BadRequestException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/BadRequestException.kt) |\n | 401 | [`UnauthorizedException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/UnauthorizedException.kt) |\n | 403 | [`PermissionDeniedException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/PermissionDeniedException.kt) |\n | 404 | [`NotFoundException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/NotFoundException.kt) |\n | 422 | [`UnprocessableEntityException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/UnprocessableEntityException.kt) |\n | 429 | [`RateLimitException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/RateLimitException.kt) |\n | 5xx | [`InternalServerException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/InternalServerException.kt) |\n | others | [`UnexpectedStatusCodeException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/UnexpectedStatusCodeException.kt) |\n\n- [`DodoPaymentsIoException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsIoException.kt): I/O networking errors.\n\n- [`DodoPaymentsRetryableException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsRetryableException.kt): Generic error indicating a failure that could be retried by the client.\n\n- [`DodoPaymentsInvalidDataException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that\'s supposed to be required, but the API unexpectedly omitted it from the response.\n\n- [`DodoPaymentsException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.\n\n## Pagination\n\nThe SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.\n\n### Auto-pagination\n\nTo iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed.\n\nWhen using the synchronous client, the method returns a [`Sequence`](https://kotlinlang.org/docs/sequences.html)\n\n```kotlin\nimport com.dodopayments.api.models.payments.PaymentListPage\n\nval page: PaymentListPage = client.payments().list()\npage.autoPager()\n .take(50)\n .forEach { payment -> println(payment) }\n```\n\nWhen using the asynchronous client, the method returns a [`Flow`](https://kotlinlang.org/docs/flow.html):\n\n```kotlin\nimport com.dodopayments.api.models.payments.PaymentListPageAsync\n\nval page: PaymentListPageAsync = client.async().payments().list()\npage.autoPager()\n .take(50)\n .forEach { payment -> println(payment) }\n```\n\n### Manual pagination\n\nTo access individual page items and manually request the next page, use the `items()`,\n`hasNextPage()`, and `nextPage()` methods:\n\n```kotlin\nimport com.dodopayments.api.models.payments.PaymentListPage\nimport com.dodopayments.api.models.payments.PaymentListResponse\n\nval page: PaymentListPage = client.payments().list()\nwhile (true) {\n for (payment in page.items()) {\n println(payment)\n }\n\n if (!page.hasNextPage()) {\n break\n }\n\n page = page.nextPage()\n}\n```\n\n## Logging\n\nEnable logging by setting the `DODO_PAYMENTS_LOG` environment variable to `info`:\n\n```sh\nexport DODO_PAYMENTS_LOG=info\n```\n\nOr to `debug` for more verbose logging:\n\n```sh\nexport DODO_PAYMENTS_LOG=debug\n```\n\nOr configure the client manually using the `logLevel` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.core.LogLevel\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .logLevel(LogLevel.INFO)\n .build()\n```\n\n## ProGuard and R8\n\nAlthough the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `dodo-payments-kotlin-core` is published with a [configuration file](dodo-payments-kotlin-core/src/main/resources/META-INF/proguard/dodo-payments-kotlin-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage).\n\nProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.\n\n\n\n\n\n## Jackson\n\nThe SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.\n\nThe SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).\n\nIf the SDK threw an exception, but you\'re _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt).\n\n> [!CAUTION]\n> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.\n\nAlso note that there are bugs in older Jackson versions that can affect the SDK. We don\'t work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead.\n\n## Network options\n\n### Retries\n\nThe SDK automatically retries 2 times by default, with a short exponential backoff between requests.\n\nOnly the following error types are retried:\n- Connection errors (for example, due to a network connectivity problem)\n- 408 Request Timeout\n- 409 Conflict\n- 429 Rate Limit\n- 5xx Internal\n\nThe API may also explicitly instruct the SDK to retry or not retry a request.\n\nTo set a custom number of retries, configure the client using the `maxRetries` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .maxRetries(4)\n .build()\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default.\n\nTo set a custom timeout, configure the method call using the `timeout` method:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()\n)\n```\n\nOr configure the default for all method calls at the client level:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport java.time.Duration\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .timeout(Duration.ofSeconds(30))\n .build()\n```\n\n### Proxies\n\nTo route requests through a proxy, configure the client using the `proxy` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport java.net.InetSocketAddress\nimport java.net.Proxy\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(Proxy(\n Proxy.Type.HTTP, InetSocketAddress(\n "https://example.com", 8080\n )\n ))\n .build()\n```\n\nIf the proxy responds with `407 Proxy Authentication Required`, supply credentials by also configuring `proxyAuthenticator`:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.core.http.ProxyAuthenticator\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(...)\n // Or a custom implementation of `ProxyAuthenticator`.\n .proxyAuthenticator(ProxyAuthenticator.basic("username", "password"))\n .build()\n```\n\n### Connection pooling\n\nTo customize the underlying OkHttp connection pool, configure the client using the `maxIdleConnections` and `keepAliveDuration` methods:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport java.time.Duration\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa.\n .maxIdleConnections(10)\n .keepAliveDuration(Duration.ofMinutes(2))\n .build()\n```\n\nIf both options are unset, OkHttp\'s default connection pool settings are used.\n\n### HTTPS\n\n> [!NOTE]\n> Most applications should not call these methods, and instead use the system defaults. The defaults include\n> special optimizations that can be lost if the implementations are modified.\n\nTo configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa.\n .sslSocketFactory(yourSSLSocketFactory)\n .trustManager(yourTrustManager)\n .hostnameVerifier(yourHostnameVerifier)\n .build()\n```\n\n### Environments\n\nThe SDK sends requests to the live_mode by default. To send requests to a different environment, configure the client like so:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .testMode()\n .build()\n```\n\n### Custom HTTP client\n\nThe SDK consists of three artifacts:\n- `dodo-payments-kotlin-core`\n - Contains core SDK logic\n - Does not depend on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsClient`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClient.kt), [`DodoPaymentsClientAsync`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsync.kt), [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt), and [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), all of which can work with any HTTP client\n- `dodo-payments-kotlin-client-okhttp`\n - Depends on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) and [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), which provide a way to construct [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) and [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), respectively, using OkHttp\n- `dodo-payments-kotlin`\n - Depends on and exposes the APIs of both `dodo-payments-kotlin-core` and `dodo-payments-kotlin-client-okhttp`\n - Does not have its own logic\n\nThis structure allows replacing the SDK\'s default HTTP client without pulling in unnecessary dependencies.\n\n#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html)\n\n> [!TIP]\n> Try the available [network options](#network-options) before replacing the default client.\n\nTo use a customized `OkHttpClient`:\n\n1. Replace your [`dodo-payments-kotlin` dependency](#installation) with `dodo-payments-kotlin-core`\n2. Copy `dodo-payments-kotlin-client-okhttp`\'s [`OkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/OkHttpClient.kt) class into your code and customize it\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your customized client\n\n### Completely custom HTTP client\n\nTo use a completely custom HTTP client:\n\n1. Replace your [`dodo-payments-kotlin` dependency](#installation) with `dodo-payments-kotlin-core`\n2. Write a class that implements the [`HttpClient`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/http/HttpClient.kt) interface\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your new client class\n\n## Undocumented API functionality\n\nThe SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.\n\n### Parameters\n\nTo set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:\n\n```kotlin\nimport com.dodopayments.api.core.JsonValue\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams\n\nval params: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder()\n .putAdditionalHeader("Secret-Header", "42")\n .putAdditionalQueryParam("secret_query_param", "42")\n .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))\n .build()\n```\n\nThese can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.\n\nTo set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) object to its setter:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\nval params: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .build()\n```\n\nThe most straightforward way to create a [`JsonValue`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) is using its `from(...)` method:\n\n```kotlin\nimport com.dodopayments.api.core.JsonValue\n\n// Create primitive JSON values\nval nullValue: JsonValue = JsonValue.from(null)\nval booleanValue: JsonValue = JsonValue.from(true)\nval numberValue: JsonValue = JsonValue.from(42)\nval stringValue: JsonValue = JsonValue.from("Hello World!")\n\n// Create a JSON array value equivalent to `["Hello", "World"]`\nval arrayValue: JsonValue = JsonValue.from(listOf(\n "Hello", "World"\n))\n\n// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`\nval objectValue: JsonValue = JsonValue.from(mapOf(\n "a" to 1, "b" to 2\n))\n\n// Create an arbitrarily nested JSON equivalent to:\n// {\n// "a": [1, 2],\n// "b": [3, 4]\n// }\nval complexValue: JsonValue = JsonValue.from(mapOf(\n "a" to listOf(\n 1, 2\n ), "b" to listOf(\n 3, 4\n )\n))\n```\n\nNormally a `Builder` class\'s `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.\n\nTo forcibly omit a required parameter or property, pass [`JsonMissing`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/Values.kt):\n\n```kotlin\nimport com.dodopayments.api.core.JsonMissing\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\nval params: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .productCart(JsonMissing.of())\n .build()\n```\n\n### Response properties\n\nTo access undocumented response properties, call the `_additionalProperties()` method:\n\n```kotlin\nimport com.dodopayments.api.core.JsonBoolean\nimport com.dodopayments.api.core.JsonNull\nimport com.dodopayments.api.core.JsonNumber\nimport com.dodopayments.api.core.JsonValue\n\nval additionalProperties: Map<String, JsonValue> = client.checkoutSessions().create(params)._additionalProperties()\nval secretPropertyValue: JsonValue = additionalProperties.get("secretProperty")\n\nval result = when (secretPropertyValue) {\n is JsonNull -> "It\'s null!"\n is JsonBoolean -> "It\'s a boolean!"\n is JsonNumber -> "It\'s a number!"\n // Other types include `JsonMissing`, `JsonString`, `JsonArray`, and `JsonObject`\n else -> "It\'s something else!"\n}\n```\n\nTo access a property\'s raw JSON value, which may be undocumented, call its `_` prefixed method:\n\n```kotlin\nimport com.dodopayments.api.core.JsonField\n\nval field: JsonField<Any> = client.checkoutSessions().create(params)._field()\n\nif (field.isMissing()) {\n // The property is absent from the JSON response\n} else if (field.isNull()) {\n // The property was set to literal null\n} else {\n // Check if value was provided as a string\n // Other methods include `asNumber()`, `asBoolean()`, etc.\n val jsonString: String? = field.asString();\n\n // Try to deserialize into a custom type\n val myObject: MyClass = field.asUnknown()!!.convert(MyClass::class.java)\n}\n```\n\n### Response validation\n\nIn rare cases, the API may return a response that doesn\'t match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else.\n\nBy default, the SDK will not throw an exception in this case. It will throw [`DodoPaymentsInvalidDataException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt) only if you directly access the property.\n\nValidating the response is _not_ forwards compatible with new types from the API for existing fields.\n\nIf you would still prefer to check that the response is completely well-typed upfront, then either call `validate()`:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params).validate()\n```\n\nOr configure the method call to validate the response using the `responseValidation` method:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().responseValidation(true).build()\n)\n```\n\nOr configure the default for all method calls at the client level:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .responseValidation(true)\n .build()\n```\n\n## FAQ\n\n### Why don\'t you use plain `enum` classes?\n\nKotlin `enum` classes are not trivially [forwards compatible](https://www.stainless.com/blog/making-java-enums-forwards-compatible). Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.\n\n### Why do you represent fields using `JsonField<T>` instead of just plain `T`?\n\nUsing `JsonField<T>` enables a few features:\n\n- Allowing usage of [undocumented API functionality](#undocumented-api-functionality)\n- Lazily [validating the API response against the expected shape](#response-validation)\n- Representing absent vs explicitly null values\n\n### Why don\'t you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)?\n\nIt is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don\'t want to introduce a breaking change every time we add a field to a class.\n\n### Why don\'t you use checked exceptions?\n\nChecked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.\n\nChecked exceptions:\n\n- Are verbose to handle\n- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error\n- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function)\n- Don\'t play well with lambdas (also due to the function coloring problem)\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-kotlin/issues) with questions, bugs, or suggestions.\n',
|
|
6928
|
+
content: '# Dodo Payments Kotlin API Library\n\n<!-- x-release-please-start-version -->\n[](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-kotlin/0.0.1)\n[](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-kotlin/0.0.1)\n<!-- x-release-please-end -->\n\nThe Dodo Payments Kotlin SDK provides convenient access to the [Dodo Payments REST API](https://docs.dodopayments.com/api-reference/introduction) from applications written in Kotlin.\n\nThe Dodo Payments Kotlin SDK is similar to the Dodo Payments Java SDK but with minor differences that make it more ergonomic for use in Kotlin, such as nullable values instead of `Optional`, `Sequence` instead of `Stream`, and suspend functions instead of `CompletableFuture`.\n\n\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n\n> Note: You may need to set environment variables in your MCP client.\n\n<!-- x-release-please-start-version -->\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction). KDocs are available on [javadoc.io](https://javadoc.io/doc/com.dodopayments.api/dodo-payments-kotlin/0.0.1).\n\n<!-- x-release-please-end -->\n\n## Installation\n\n<!-- x-release-please-start-version -->\n\n### Gradle\n\n~~~kotlin\nimplementation("com.dodopayments.api:dodo-payments-kotlin:0.0.1")\n~~~\n\n### Maven\n\n~~~xml\n<dependency>\n <groupId>com.dodopayments.api</groupId>\n <artifactId>dodo-payments-kotlin</artifactId>\n <version>0.0.1</version>\n</dependency>\n~~~\n\n<!-- x-release-please-end -->\n\n## Requirements\n\nThis library requires Java 8 or later.\n\n## Usage\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params)\n```\n\n## Client configuration\n\nConfigure the client using system properties or environment variables:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()\n```\n\nOr manually:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .bearerToken("My Bearer Token")\n .build()\n```\n\nOr using a combination of the two approaches:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n // Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n // Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\n .fromEnv()\n .bearerToken("My Bearer Token")\n .build()\n```\n\nSee this table for the available options:\n\n| Setter | System property | Environment variable | Required | Default value |\n| ------------- | ------------------------- | --------------------------- | -------- | --------------------------------- |\n| `bearerToken` | `dodopayments.apiKey` | `DODO_PAYMENTS_API_KEY` | true | - |\n| `webhookKey` | `dodopayments.webhookKey` | `DODO_PAYMENTS_WEBHOOK_KEY` | false | - |\n| `baseUrl` | `dodopayments.baseUrl` | `DODO_PAYMENTS_BASE_URL` | true | `"https://live.dodopayments.com"` |\n\nSystem properties take precedence over environment variables.\n\n> [!TIP]\n> Don\'t create more than one client in the same application. Each client has a connection pool and\n> thread pools, which are more efficient to share between requests.\n\n### Modifying configuration\n\nTo temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\n\nval clientWithOptions: DodoPaymentsClient = client.withOptions {\n it.baseUrl("https://example.com")\n it.maxRetries(42)\n}\n```\n\nThe `withOptions()` method does not affect the original client or service.\n\n## Requests and responses\n\nTo send a request to the Dodo Payments API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Kotlin class.\n\nFor example, `client.checkoutSessions().create(...)` should be called with an instance of `CheckoutSessionCreateParams`, and it will return an instance of `CheckoutSessionResponse`.\n\n## Immutability\n\nEach class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it.\n\nEach class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy.\n\nBecause each class is immutable, builder modification will _never_ affect already built class instances.\n\n## Asynchronous execution\n\nThe default client is synchronous. To switch to asynchronous execution, call the `async()` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv()\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: CheckoutSessionResponse = client.async().checkoutSessions().create(params)\n```\n\nOr create an asynchronous client from the beginning:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClientAsync\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\n// Configures using the `dodopayments.apiKey`, `dodopayments.webhookKey` and `dodopayments.baseUrl` system properties\n// Or configures using the `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` and `DODO_PAYMENTS_BASE_URL` environment variables\nval client: DodoPaymentsClientAsync = DodoPaymentsOkHttpClientAsync.fromEnv()\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params)\n```\n\nThe asynchronous client supports the same options as the synchronous one, except most methods are [suspending](https://kotlinlang.org/docs/coroutines-guide.html).\n\n\n\n\n\n## Binary responses\n\nThe SDK defines methods that return binary responses, which are used for API responses that shouldn\'t necessarily be parsed, like non-JSON data.\n\nThese methods return [`HttpResponse`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/http/HttpResponse.kt):\n\n```kotlin\nimport com.dodopayments.api.core.http.HttpResponse\nimport com.dodopayments.api.models.invoices.payments.PaymentRetrieveParams\n\nval payment: HttpResponse = client.invoices().payments().retrieve("payment_id")\n```\n\nTo save the response content to a file, use the [`Files.copy(...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-) method:\n\n```kotlin\nimport java.nio.file.Files\nimport java.nio.file.Paths\nimport java.nio.file.StandardCopyOption\n\nclient.invoices().payments().retrieve(params).use {\n Files.copy(\n it.body(),\n Paths.get(path),\n StandardCopyOption.REPLACE_EXISTING\n )\n}\n```\n\nOr transfer the response content to any [`OutputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html):\n\n```kotlin\nimport java.nio.file.Files\nimport java.nio.file.Paths\n\nclient.invoices().payments().retrieve(params).use {\n it.body().transferTo(Files.newOutputStream(Paths.get(path)))\n}\n```\n\n## Raw responses\n\nThe SDK defines methods that deserialize responses into instances of Kotlin classes. However, these methods don\'t provide access to the response headers, status code, or the raw response body.\n\nTo access this data, prefix any HTTP method call on a client or service with `withRawResponse()`:\n\n```kotlin\nimport com.dodopayments.api.core.http.Headers\nimport com.dodopayments.api.core.http.HttpResponseFor\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\nval params: CheckoutSessionRequest = CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build()\nval checkoutSessionResponse: HttpResponseFor<CheckoutSessionResponse> = client.checkoutSessions().withRawResponse().create(params)\n\nval statusCode: Int = checkoutSessionResponse.statusCode()\nval headers: Headers = checkoutSessionResponse.headers()\n```\n\nYou can still deserialize the response into an instance of a Kotlin class if needed:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval parsedCheckoutSessionResponse: CheckoutSessionResponse = checkoutSessionResponse.parse()\n```\n\n## Error handling\n\nThe SDK throws custom unchecked exception types:\n\n- [`DodoPaymentsServiceException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:\n\n | Status | Exception |\n | ------ | -------------------------------------------------- |\n | 400 | [`BadRequestException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/BadRequestException.kt) |\n | 401 | [`UnauthorizedException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/UnauthorizedException.kt) |\n | 403 | [`PermissionDeniedException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/PermissionDeniedException.kt) |\n | 404 | [`NotFoundException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/NotFoundException.kt) |\n | 422 | [`UnprocessableEntityException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/UnprocessableEntityException.kt) |\n | 429 | [`RateLimitException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/RateLimitException.kt) |\n | 5xx | [`InternalServerException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/InternalServerException.kt) |\n | others | [`UnexpectedStatusCodeException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/UnexpectedStatusCodeException.kt) |\n\n- [`DodoPaymentsIoException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsIoException.kt): I/O networking errors.\n\n- [`DodoPaymentsRetryableException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsRetryableException.kt): Generic error indicating a failure that could be retried by the client.\n\n- [`DodoPaymentsInvalidDataException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that\'s supposed to be required, but the API unexpectedly omitted it from the response.\n\n- [`DodoPaymentsException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.\n\n## Pagination\n\nThe SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.\n\n### Auto-pagination\n\nTo iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed.\n\nWhen using the synchronous client, the method returns a [`Sequence`](https://kotlinlang.org/docs/sequences.html)\n\n```kotlin\nimport com.dodopayments.api.models.payments.PaymentListPage\n\nval page: PaymentListPage = client.payments().list()\npage.autoPager()\n .take(50)\n .forEach { payment -> println(payment) }\n```\n\nWhen using the asynchronous client, the method returns a [`Flow`](https://kotlinlang.org/docs/flow.html):\n\n```kotlin\nimport com.dodopayments.api.models.payments.PaymentListPageAsync\n\nval page: PaymentListPageAsync = client.async().payments().list()\npage.autoPager()\n .take(50)\n .forEach { payment -> println(payment) }\n```\n\n### Manual pagination\n\nTo access individual page items and manually request the next page, use the `items()`,\n`hasNextPage()`, and `nextPage()` methods:\n\n```kotlin\nimport com.dodopayments.api.models.payments.PaymentListPage\nimport com.dodopayments.api.models.payments.PaymentListResponse\n\nval page: PaymentListPage = client.payments().list()\nwhile (true) {\n for (payment in page.items()) {\n println(payment)\n }\n\n if (!page.hasNextPage()) {\n break\n }\n\n page = page.nextPage()\n}\n```\n\n## Logging\n\nEnable logging by setting the `DODO_PAYMENTS_LOG` environment variable to `info`:\n\n```sh\nexport DODO_PAYMENTS_LOG=info\n```\n\nOr to `debug` for more verbose logging:\n\n```sh\nexport DODO_PAYMENTS_LOG=debug\n```\n\nOr configure the client manually using the `logLevel` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.core.LogLevel\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .logLevel(LogLevel.INFO)\n .build()\n```\n\n## ProGuard and R8\n\nAlthough the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `dodo-payments-kotlin-core` is published with a [configuration file](dodo-payments-kotlin-core/src/main/resources/META-INF/proguard/dodo-payments-kotlin-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage).\n\nProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.\n\n\n\n\n\n## Jackson\n\nThe SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.\n\nThe SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).\n\nIf the SDK threw an exception, but you\'re _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt).\n\n> [!CAUTION]\n> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.\n\nAlso note that there are bugs in older Jackson versions that can affect the SDK. We don\'t work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead.\n\n## Network options\n\n### Retries\n\nThe SDK automatically retries 2 times by default, with a short exponential backoff between requests.\n\nOnly the following error types are retried:\n- Connection errors (for example, due to a network connectivity problem)\n- 408 Request Timeout\n- 409 Conflict\n- 429 Rate Limit\n- 5xx Internal\n\nThe API may also explicitly instruct the SDK to retry or not retry a request.\n\nTo set a custom number of retries, configure the client using the `maxRetries` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .maxRetries(4)\n .build()\n```\n\n### Timeouts\n\nRequests time out after 1 minute by default.\n\nTo set a custom timeout, configure the method call using the `timeout` method:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()\n)\n```\n\nOr configure the default for all method calls at the client level:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport java.time.Duration\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .timeout(Duration.ofSeconds(30))\n .build()\n```\n\n### Proxies\n\nTo route requests through a proxy, configure the client using the `proxy` method:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport java.net.InetSocketAddress\nimport java.net.Proxy\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(Proxy(\n Proxy.Type.HTTP, InetSocketAddress(\n "https://example.com", 8080\n )\n ))\n .build()\n```\n\nIf the proxy responds with `407 Proxy Authentication Required`, supply credentials by also configuring `proxyAuthenticator`:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport com.dodopayments.api.core.http.ProxyAuthenticator\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .proxy(...)\n // Or a custom implementation of `ProxyAuthenticator`.\n .proxyAuthenticator(ProxyAuthenticator.basic("username", "password"))\n .build()\n```\n\n### Connection pooling\n\nTo customize the underlying OkHttp connection pool, configure the client using the `maxIdleConnections` and `keepAliveDuration` methods:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\nimport java.time.Duration\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa.\n .maxIdleConnections(10)\n .keepAliveDuration(Duration.ofMinutes(2))\n .build()\n```\n\nIf both options are unset, OkHttp\'s default connection pool settings are used.\n\n### HTTPS\n\n> [!NOTE]\n> Most applications should not call these methods, and instead use the system defaults. The defaults include\n> special optimizations that can be lost if the implementations are modified.\n\nTo configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa.\n .sslSocketFactory(yourSSLSocketFactory)\n .trustManager(yourTrustManager)\n .hostnameVerifier(yourHostnameVerifier)\n .build()\n```\n\n### Environments\n\nThe SDK sends requests to the live_mode by default. To send requests to a different environment, configure the client like so:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .testMode()\n .build()\n```\n\n### Custom HTTP client\n\nThe SDK consists of three artifacts:\n- `dodo-payments-kotlin-core`\n - Contains core SDK logic\n - Does not depend on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsClient`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClient.kt), [`DodoPaymentsClientAsync`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsync.kt), [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt), and [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), all of which can work with any HTTP client\n- `dodo-payments-kotlin-client-okhttp`\n - Depends on [OkHttp](https://square.github.io/okhttp)\n - Exposes [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) and [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), which provide a way to construct [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) and [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), respectively, using OkHttp\n- `dodo-payments-kotlin`\n - Depends on and exposes the APIs of both `dodo-payments-kotlin-core` and `dodo-payments-kotlin-client-okhttp`\n - Does not have its own logic\n\nThis structure allows replacing the SDK\'s default HTTP client without pulling in unnecessary dependencies.\n\n#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html)\n\n> [!TIP]\n> Try the available [network options](#network-options) before replacing the default client.\n\nTo use a customized `OkHttpClient`:\n\n1. Replace your [`dodo-payments-kotlin` dependency](#installation) with `dodo-payments-kotlin-core`\n2. Copy `dodo-payments-kotlin-client-okhttp`\'s [`OkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/OkHttpClient.kt) class into your code and customize it\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your customized client\n\n### Completely custom HTTP client\n\nTo use a completely custom HTTP client:\n\n1. Replace your [`dodo-payments-kotlin` dependency](#installation) with `dodo-payments-kotlin-core`\n2. Write a class that implements the [`HttpClient`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/http/HttpClient.kt) interface\n3. Construct [`DodoPaymentsClientImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientImpl.kt) or [`DodoPaymentsClientAsyncImpl`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/client/DodoPaymentsClientAsyncImpl.kt), similarly to [`DodoPaymentsOkHttpClient`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClient.kt) or [`DodoPaymentsOkHttpClientAsync`](dodo-payments-kotlin-client-okhttp/src/main/kotlin/com/dodopayments/api/client/okhttp/DodoPaymentsOkHttpClientAsync.kt), using your new client class\n\n## Undocumented API functionality\n\nThe SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.\n\n### Parameters\n\nTo set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:\n\n```kotlin\nimport com.dodopayments.api.core.JsonValue\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams\n\nval params: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder()\n .putAdditionalHeader("Secret-Header", "42")\n .putAdditionalQueryParam("secret_query_param", "42")\n .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))\n .build()\n```\n\nThese can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.\n\nTo set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) object to its setter:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\nval params: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .build()\n```\n\nThe most straightforward way to create a [`JsonValue`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/Values.kt) is using its `from(...)` method:\n\n```kotlin\nimport com.dodopayments.api.core.JsonValue\n\n// Create primitive JSON values\nval nullValue: JsonValue = JsonValue.from(null)\nval booleanValue: JsonValue = JsonValue.from(true)\nval numberValue: JsonValue = JsonValue.from(42)\nval stringValue: JsonValue = JsonValue.from("Hello World!")\n\n// Create a JSON array value equivalent to `["Hello", "World"]`\nval arrayValue: JsonValue = JsonValue.from(listOf(\n "Hello", "World"\n))\n\n// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`\nval objectValue: JsonValue = JsonValue.from(mapOf(\n "a" to 1, "b" to 2\n))\n\n// Create an arbitrarily nested JSON equivalent to:\n// {\n// "a": [1, 2],\n// "b": [3, 4]\n// }\nval complexValue: JsonValue = JsonValue.from(mapOf(\n "a" to listOf(\n 1, 2\n ), "b" to listOf(\n 3, 4\n )\n))\n```\n\nNormally a `Builder` class\'s `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.\n\nTo forcibly omit a required parameter or property, pass [`JsonMissing`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/core/Values.kt):\n\n```kotlin\nimport com.dodopayments.api.core.JsonMissing\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionCreateParams\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest\nimport com.dodopayments.api.models.checkoutsessions.ProductItemReq\n\nval params: CheckoutSessionCreateParams = CheckoutSessionCreateParams.builder()\n .checkoutSessionRequest(CheckoutSessionRequest.builder()\n .addProductCart(ProductItemReq.builder()\n .productId("product_id")\n .quantity(0)\n .build())\n .build())\n .productCart(JsonMissing.of())\n .build()\n```\n\n### Response properties\n\nTo access undocumented response properties, call the `_additionalProperties()` method:\n\n```kotlin\nimport com.dodopayments.api.core.JsonBoolean\nimport com.dodopayments.api.core.JsonNull\nimport com.dodopayments.api.core.JsonNumber\nimport com.dodopayments.api.core.JsonValue\n\nval additionalProperties: Map<String, JsonValue> = client.checkoutSessions().create(params)._additionalProperties()\nval secretPropertyValue: JsonValue = additionalProperties.get("secretProperty")\n\nval result = when (secretPropertyValue) {\n is JsonNull -> "It\'s null!"\n is JsonBoolean -> "It\'s a boolean!"\n is JsonNumber -> "It\'s a number!"\n // Other types include `JsonMissing`, `JsonString`, `JsonArray`, and `JsonObject`\n else -> "It\'s something else!"\n}\n```\n\nTo access a property\'s raw JSON value, which may be undocumented, call its `_` prefixed method:\n\n```kotlin\nimport com.dodopayments.api.core.JsonField\n\nval field: JsonField<Any> = client.checkoutSessions().create(params)._field()\n\nif (field.isMissing()) {\n // The property is absent from the JSON response\n} else if (field.isNull()) {\n // The property was set to literal null\n} else {\n // Check if value was provided as a string\n // Other methods include `asNumber()`, `asBoolean()`, etc.\n val jsonString: String? = field.asString();\n\n // Try to deserialize into a custom type\n val myObject: MyClass = field.asUnknown()!!.convert(MyClass::class.java)\n}\n```\n\n### Response validation\n\nIn rare cases, the API may return a response that doesn\'t match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else.\n\nBy default, the SDK will not throw an exception in this case. It will throw [`DodoPaymentsInvalidDataException`](dodo-payments-kotlin-core/src/main/kotlin/com/dodopayments/api/errors/DodoPaymentsInvalidDataException.kt) only if you directly access the property.\n\nValidating the response is _not_ forwards compatible with new types from the API for existing fields.\n\nIf you would still prefer to check that the response is completely well-typed upfront, then either call `validate()`:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params).validate()\n```\n\nOr configure the method call to validate the response using the `responseValidation` method:\n\n```kotlin\nimport com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse\n\nval checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(\n params, RequestOptions.builder().responseValidation(true).build()\n)\n```\n\nOr configure the default for all method calls at the client level:\n\n```kotlin\nimport com.dodopayments.api.client.DodoPaymentsClient\nimport com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient\n\nval client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder()\n .fromEnv()\n .responseValidation(true)\n .build()\n```\n\n## FAQ\n\n### Why don\'t you use plain `enum` classes?\n\nKotlin `enum` classes are not trivially forwards compatible. Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.\n\n### Why do you represent fields using `JsonField<T>` instead of just plain `T`?\n\nUsing `JsonField<T>` enables a few features:\n\n- Allowing usage of [undocumented API functionality](#undocumented-api-functionality)\n- Lazily [validating the API response against the expected shape](#response-validation)\n- Representing absent vs explicitly null values\n\n### Why don\'t you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)?\n\nIt is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don\'t want to introduce a breaking change every time we add a field to a class.\n\n### Why don\'t you use checked exceptions?\n\nChecked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.\n\nChecked exceptions:\n\n- Are verbose to handle\n- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error\n- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function)\n- Don\'t play well with lambdas (also due to the function coloring problem)\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-kotlin/issues) with questions, bugs, or suggestions.\n',
|
|
6919
6929
|
},
|
|
6920
6930
|
{
|
|
6921
6931
|
language: 'go',
|
|
6922
|
-
content: '# Dodo Payments Go API Library\n\n<a href="https://pkg.go.dev/github.com/dodopayments/dodopayments-go"><img src="https://pkg.go.dev/badge/github.com/dodopayments/dodopayments-go.svg" alt="Go Reference"></a>\n\nThe Dodo Payments Go library provides convenient access to the [Dodo Payments REST API](https://docs.dodopayments.com/api-reference/introduction)\nfrom applications written in Go.\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n[](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22dodopayments-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22dodopayments-mcp%22%5D%2C%22env%22%3A%7B%22DODO_PAYMENTS_API_KEY%22%3A%22My%20Bearer%20Token%22%2C%22DODO_PAYMENTS_WEBHOOK_KEY%22%3A%22My%20Webhook%20Key%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Installation\n\n<!-- x-release-please-start-version -->\n\n```go\nimport (\n\t"github.com/dodopayments/dodopayments-go" // imported as SDK_PackageName\n)\n```\n\n<!-- x-release-please-end -->\n\nOr to pin the version:\n\n<!-- x-release-please-start-version -->\n\n```sh\ngo get -u \'github.com/dodopayments/dodopayments-go@v0.0.1\'\n```\n\n<!-- x-release-please-end -->\n\n## Requirements\n\nThis library requires Go 1.22+.\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n```go\npackage main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/dodopayments/dodopayments-go"\n\t"github.com/dodopayments/dodopayments-go/option"\n)\n\nfunc main() {\n\tclient := dodopayments.NewClient(\n\t\toption.WithBearerToken("My Bearer Token"), // defaults to os.LookupEnv("DODO_PAYMENTS_API_KEY")\n\t\toption.WithEnvironmentTestMode(), // defaults to option.WithEnvironmentLiveMode()\n\t)\n\tcheckoutSessionResponse, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", checkoutSessionResponse.SessionID)\n}\n\n```\n\n### Request fields\n\nAll request parameters are wrapped in a generic `Field` type,\nwhich we use to distinguish zero values from null or omitted fields.\n\nThis prevents accidentally sending a zero value if you forget a required parameter,\nand enables explicitly sending `null`, `false`, `\'\'`, or `0` on optional parameters.\nAny field not specified is not sent.\n\nTo construct fields with values, use the helpers `String()`, `Int()`, `Float()`, or most commonly, the generic `F[T]()`.\nTo send a null, use `Null[T]()`, and to send a nonconforming value, use `Raw[T](any)`. For example:\n\n```go\nparams := FooParams{\n\tName: SDK_PackageName.F("hello"),\n\n\t// Explicitly send `"description": null`\n\tDescription: SDK_PackageName.Null[string](),\n\n\tPoint: SDK_PackageName.F(SDK_PackageName.Point{\n\t\tX: SDK_PackageName.Int(0),\n\t\tY: SDK_PackageName.Int(1),\n\n\t\t// In cases where the API specifies a given type,\n\t\t// but you want to send something else, use `Raw`:\n\t\tZ: SDK_PackageName.Raw[int64](0.01), // sends a float\n\t}),\n}\n```\n\n### Response objects\n\nAll fields in response structs are value types (not pointers or wrappers).\n\nIf a given field is `null`, not present, or invalid, the corresponding field\nwill simply be its zero value.\n\nAll response structs also include a special `JSON` field, containing more detailed\ninformation about each property, which you can use like so:\n\n```go\nif res.Name == "" {\n\t// true if `"name"` is either not present or explicitly null\n\tres.JSON.Name.IsNull()\n\n\t// true if the `"name"` key was not present in the response JSON at all\n\tres.JSON.Name.IsMissing()\n\n\t// When the API returns data that cannot be coerced to the expected type:\n\tif res.JSON.Name.IsInvalid() {\n\t\traw := res.JSON.Name.Raw()\n\n\t\tlegacyName := struct{\n\t\t\tFirst string `json:"first"`\n\t\t\tLast string `json:"last"`\n\t\t}{}\n\t\tjson.Unmarshal([]byte(raw), &legacyName)\n\t\tname = legacyName.First + " " + legacyName.Last\n\t}\n}\n```\n\nThese `.JSON` structs also include an `Extras` map containing\nany properties in the json response that were not specified\nin the struct. This can be useful for API features not yet\npresent in the SDK.\n\n```go\nbody := res.JSON.ExtraFields["my_unexpected_field"].Raw()\n```\n\n### RequestOptions\n\nThis library uses the functional options pattern. Functions defined in the\n`SDK_PackageOptionName` package return a `RequestOption`, which is a closure that mutates a\n`RequestConfig`. These options can be supplied to the client or at individual\nrequests. For example:\n\n```go\nclient := SDK_PackageName.SDK_ClientInitializerName(\n\t// Adds a header to every request made by the client\n\tSDK_PackageOptionName.WithHeader("X-Some-Header", "custom_header_info"),\n)\n\nclient.CheckoutSessions.New(context.TODO(), ...,\n\t// Override the header\n\tSDK_PackageOptionName.WithHeader("X-Some-Header", "some_other_custom_header_info"),\n\t// Add an undocumented field to the request body, using sjson syntax\n\tSDK_PackageOptionName.WithJSONSet("some.json.path", map[string]string{"my": "object"}),\n)\n```\n\nSee the [full list of request options](https://pkg.go.dev/github.com/dodopayments/dodopayments-go/SDK_PackageOptionName).\n\n### Pagination\n\nThis library provides some conveniences for working with paginated list endpoints.\n\nYou can use `.ListAutoPaging()` methods to iterate through items across all pages:\n\n```go\niter := client.Payments.ListAutoPaging(context.TODO(), dodopayments.PaymentListParams{})\n// Automatically fetches more pages as needed.\nfor iter.Next() {\n\tpaymentListResponse := iter.Current()\n\tfmt.Printf("%+v\\n", paymentListResponse)\n}\nif err := iter.Err(); err != nil {\n\tpanic(err.Error())\n}\n```\n\nOr you can use simple `.List()` methods to fetch a single page and receive a standard response object\nwith additional helper methods like `.GetNextPage()`, e.g.:\n\n```go\npage, err := client.Payments.List(context.TODO(), dodopayments.PaymentListParams{})\nfor page != nil {\n\tfor _, payment := range page.Items {\n\t\tfmt.Printf("%+v\\n", payment)\n\t}\n\tpage, err = page.GetNextPage()\n}\nif err != nil {\n\tpanic(err.Error())\n}\n```\n\n### Errors\n\nWhen the API returns a non-success status code, we return an error with type\n`*SDK_PackageName.Error`. This contains the `StatusCode`, `*http.Request`, and\n`*http.Response` values of the request, as well as the JSON of the error body\n(much like other response objects in the SDK).\n\nTo handle errors, we recommend that you use the `errors.As` pattern:\n\n```go\n_, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{\n\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t}}),\n\t},\n})\nif err != nil {\n\tvar apierr *dodopayments.Error\n\tif errors.As(err, &apierr) {\n\t\tprintln(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request\n\t\tprintln(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response\n\t}\n\tpanic(err.Error()) // GET "/checkouts": 400 Bad Request { ... }\n}\n```\n\nWhen other errors occur, they are returned unwrapped; for example,\nif HTTP transport fails, you might receive `*url.Error` wrapping `*net.OpError`.\n\n### Timeouts\n\nRequests do not time out by default; use context to configure a timeout for a request lifecycle.\n\nNote that if a request is [retried](#retries), the context timeout does not start over.\nTo set a per-retry timeout, use `SDK_PackageOptionName.WithRequestTimeout()`.\n\n```go\n// This sets the timeout for the request, including all the retries.\nctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\ndefer cancel()\nclient.CheckoutSessions.New(\n\tctx,\n\tdodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t},\n\t// This sets the per-retry timeout\n\toption.WithRequestTimeout(20*time.Second),\n)\n```\n\n### File uploads\n\nRequest parameters that correspond to file uploads in multipart requests are typed as\n`param.Field[io.Reader]`. The contents of the `io.Reader` will by default be sent as a multipart form\npart with the file name of "anonymous_file" and content-type of "application/octet-stream".\n\nThe file name and content-type can be customized by implementing `Name() string` or `ContentType()\nstring` on the run-time type of `io.Reader`. Note that `os.File` implements `Name() string`, so a\nfile returned by `os.Open` will be sent with the file name on disk.\n\nWe also provide a helper `SDK_PackageName.FileParam(reader io.Reader, filename string, contentType string)`\nwhich can be used to wrap any `io.Reader` with the appropriate file name and content type.\n\n\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nWe retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit,\nand >=500 Internal errors.\n\nYou can use the `WithMaxRetries` option to configure or disable this:\n\n```go\n// Configure the default for all requests:\nclient := dodopayments.NewClient(\n\toption.WithMaxRetries(0), // default is 2\n)\n\n// Override per-request:\nclient.CheckoutSessions.New(\n\tcontext.TODO(),\n\tdodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t},\n\toption.WithMaxRetries(5),\n)\n```\n\n\n### Accessing raw response data (e.g. response headers)\n\nYou can access the raw HTTP response data by using the `option.WithResponseInto()` request option. This is useful when\nyou need to examine response headers, status codes, or other details.\n\n```go\n// Create a variable to store the HTTP response\nvar response *http.Response\ncheckoutSessionResponse, err := client.CheckoutSessions.New(\n\tcontext.TODO(),\n\tdodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t},\n\toption.WithResponseInto(&response),\n)\nif err != nil {\n\t// handle error\n}\nfmt.Printf("%+v\\n", checkoutSessionResponse)\n\nfmt.Printf("Status Code: %d\\n", response.StatusCode)\nfmt.Printf("Headers: %+#v\\n", response.Header)\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.Get`, `client.Post`, and other HTTP verbs.\n`RequestOptions` on the client, such as retries, will be respected when making these requests.\n\n```go\nvar (\n // params can be an io.Reader, a []byte, an encoding/json serializable object,\n // or a "…Params" struct defined in this library.\n params map[string]interface{}\n\n // result can be an []byte, *http.Response, a encoding/json deserializable object,\n // or a model defined in this library.\n result *http.Response\n)\nerr := client.Post(context.Background(), "/unspecified", params, &result)\nif err != nil {\n …\n}\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use either the `SDK_PackageOptionName.WithQuerySet()`\nor the `SDK_PackageOptionName.WithJSONSet()` methods.\n\n```go\nparams := FooNewParams{\n ID: SDK_PackageName.F("id_xxxx"),\n Data: SDK_PackageName.F(FooNewParamsData{\n FirstName: SDK_PackageName.F("John"),\n }),\n}\nclient.Foo.New(context.Background(), params, SDK_PackageOptionName.WithJSONSet("data.last_name", "Doe"))\n```\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may either access the raw JSON of the response as a string\nwith `result.JSON.RawJSON()`, or get the raw JSON of a particular field on the result with\n`result.JSON.Foo.Raw()`.\n\nAny fields that are not present on the response struct will be saved and can be accessed by `result.JSON.ExtraFields()` which returns the extra fields as a `map[string]Field`.\n\n### Middleware\n\nWe provide `SDK_PackageOptionName.WithMiddleware` which applies the given\nmiddleware to requests.\n\n```go\nfunc Logger(req *http.Request, next SDK_PackageOptionName.MiddlewareNext) (res *http.Response, err error) {\n\t// Before the request\n\tstart := time.Now()\n\tLogReq(req)\n\n\t// Forward the request to the next handler\n\tres, err = next(req)\n\n\t// Handle stuff after the request\n\tend := time.Now()\n\tLogRes(res, err, start - end)\n\n return res, err\n}\n\nclient := SDK_PackageName.SDK_ClientInitializerName(\n\tSDK_PackageOptionName.WithMiddleware(Logger),\n)\n```\n\nWhen multiple middlewares are provided as variadic arguments, the middlewares\nare applied left to right. If `SDK_PackageOptionName.WithMiddleware` is given\nmultiple times, for example first in the client then the method, the\nmiddleware in the client will run first and the middleware given in the method\nwill run next.\n\nYou may also replace the default `http.Client` with\n`SDK_PackageOptionName.WithHTTPClient(client)`. Only one http client is\naccepted (this overwrites any previous client) and receives requests after any\nmiddleware has been applied.\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-go/issues) with questions, bugs, or suggestions.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n',
|
|
6932
|
+
content: '# Dodo Payments Go API Library\n\n<a href="https://pkg.go.dev/github.com/dodopayments/dodopayments-go"><img src="https://pkg.go.dev/badge/github.com/dodopayments/dodopayments-go.svg" alt="Go Reference"></a>\n\nThe Dodo Payments Go library provides convenient access to the [Dodo Payments REST API](https://docs.dodopayments.com/api-reference/introduction)\nfrom applications written in Go.\n\n\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Installation\n\n<!-- x-release-please-start-version -->\n\n```go\nimport (\n\t"github.com/dodopayments/dodopayments-go" // imported as SDK_PackageName\n)\n```\n\n<!-- x-release-please-end -->\n\nOr to pin the version:\n\n<!-- x-release-please-start-version -->\n\n```sh\ngo get -u \'github.com/dodopayments/dodopayments-go@v0.0.1\'\n```\n\n<!-- x-release-please-end -->\n\n## Requirements\n\nThis library requires Go 1.22+.\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n```go\npackage main\n\nimport (\n\t"context"\n\t"fmt"\n\n\t"github.com/dodopayments/dodopayments-go"\n\t"github.com/dodopayments/dodopayments-go/option"\n)\n\nfunc main() {\n\tclient := dodopayments.NewClient(\n\t\toption.WithBearerToken("My Bearer Token"), // defaults to os.LookupEnv("DODO_PAYMENTS_API_KEY")\n\t\toption.WithEnvironmentTestMode(), // defaults to option.WithEnvironmentLiveMode()\n\t)\n\tcheckoutSessionResponse, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf("%+v\\n", checkoutSessionResponse.SessionID)\n}\n\n```\n\n### Request fields\n\nAll request parameters are wrapped in a generic `Field` type,\nwhich we use to distinguish zero values from null or omitted fields.\n\nThis prevents accidentally sending a zero value if you forget a required parameter,\nand enables explicitly sending `null`, `false`, `\'\'`, or `0` on optional parameters.\nAny field not specified is not sent.\n\nTo construct fields with values, use the helpers `String()`, `Int()`, `Float()`, or most commonly, the generic `F[T]()`.\nTo send a null, use `Null[T]()`, and to send a nonconforming value, use `Raw[T](any)`. For example:\n\n```go\nparams := FooParams{\n\tName: SDK_PackageName.F("hello"),\n\n\t// Explicitly send `"description": null`\n\tDescription: SDK_PackageName.Null[string](),\n\n\tPoint: SDK_PackageName.F(SDK_PackageName.Point{\n\t\tX: SDK_PackageName.Int(0),\n\t\tY: SDK_PackageName.Int(1),\n\n\t\t// In cases where the API specifies a given type,\n\t\t// but you want to send something else, use `Raw`:\n\t\tZ: SDK_PackageName.Raw[int64](0.01), // sends a float\n\t}),\n}\n```\n\n### Response objects\n\nAll fields in response structs are value types (not pointers or wrappers).\n\nIf a given field is `null`, not present, or invalid, the corresponding field\nwill simply be its zero value.\n\nAll response structs also include a special `JSON` field, containing more detailed\ninformation about each property, which you can use like so:\n\n```go\nif res.Name == "" {\n\t// true if `"name"` is either not present or explicitly null\n\tres.JSON.Name.IsNull()\n\n\t// true if the `"name"` key was not present in the response JSON at all\n\tres.JSON.Name.IsMissing()\n\n\t// When the API returns data that cannot be coerced to the expected type:\n\tif res.JSON.Name.IsInvalid() {\n\t\traw := res.JSON.Name.Raw()\n\n\t\tlegacyName := struct{\n\t\t\tFirst string `json:"first"`\n\t\t\tLast string `json:"last"`\n\t\t}{}\n\t\tjson.Unmarshal([]byte(raw), &legacyName)\n\t\tname = legacyName.First + " " + legacyName.Last\n\t}\n}\n```\n\nThese `.JSON` structs also include an `Extras` map containing\nany properties in the json response that were not specified\nin the struct. This can be useful for API features not yet\npresent in the SDK.\n\n```go\nbody := res.JSON.ExtraFields["my_unexpected_field"].Raw()\n```\n\n### RequestOptions\n\nThis library uses the functional options pattern. Functions defined in the\n`SDK_PackageOptionName` package return a `RequestOption`, which is a closure that mutates a\n`RequestConfig`. These options can be supplied to the client or at individual\nrequests. For example:\n\n```go\nclient := SDK_PackageName.SDK_ClientInitializerName(\n\t// Adds a header to every request made by the client\n\tSDK_PackageOptionName.WithHeader("X-Some-Header", "custom_header_info"),\n)\n\nclient.CheckoutSessions.New(context.TODO(), ...,\n\t// Override the header\n\tSDK_PackageOptionName.WithHeader("X-Some-Header", "some_other_custom_header_info"),\n\t// Add an undocumented field to the request body, using sjson syntax\n\tSDK_PackageOptionName.WithJSONSet("some.json.path", map[string]string{"my": "object"}),\n)\n```\n\nSee the [full list of request options](https://pkg.go.dev/github.com/dodopayments/dodopayments-go/SDK_PackageOptionName).\n\n### Pagination\n\nThis library provides some conveniences for working with paginated list endpoints.\n\nYou can use `.ListAutoPaging()` methods to iterate through items across all pages:\n\n```go\niter := client.Payments.ListAutoPaging(context.TODO(), dodopayments.PaymentListParams{})\n// Automatically fetches more pages as needed.\nfor iter.Next() {\n\tpaymentListResponse := iter.Current()\n\tfmt.Printf("%+v\\n", paymentListResponse)\n}\nif err := iter.Err(); err != nil {\n\tpanic(err.Error())\n}\n```\n\nOr you can use simple `.List()` methods to fetch a single page and receive a standard response object\nwith additional helper methods like `.GetNextPage()`, e.g.:\n\n```go\npage, err := client.Payments.List(context.TODO(), dodopayments.PaymentListParams{})\nfor page != nil {\n\tfor _, payment := range page.Items {\n\t\tfmt.Printf("%+v\\n", payment)\n\t}\n\tpage, err = page.GetNextPage()\n}\nif err != nil {\n\tpanic(err.Error())\n}\n```\n\n### Errors\n\nWhen the API returns a non-success status code, we return an error with type\n`*SDK_PackageName.Error`. This contains the `StatusCode`, `*http.Request`, and\n`*http.Response` values of the request, as well as the JSON of the error body\n(much like other response objects in the SDK).\n\nTo handle errors, we recommend that you use the `errors.As` pattern:\n\n```go\n_, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{\n\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t}}),\n\t},\n})\nif err != nil {\n\tvar apierr *dodopayments.Error\n\tif errors.As(err, &apierr) {\n\t\tprintln(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request\n\t\tprintln(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response\n\t}\n\tpanic(err.Error()) // GET "/checkouts": 400 Bad Request { ... }\n}\n```\n\nWhen other errors occur, they are returned unwrapped; for example,\nif HTTP transport fails, you might receive `*url.Error` wrapping `*net.OpError`.\n\n### Timeouts\n\nRequests do not time out by default; use context to configure a timeout for a request lifecycle.\n\nNote that if a request is [retried](#retries), the context timeout does not start over.\nTo set a per-retry timeout, use `SDK_PackageOptionName.WithRequestTimeout()`.\n\n```go\n// This sets the timeout for the request, including all the retries.\nctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\ndefer cancel()\nclient.CheckoutSessions.New(\n\tctx,\n\tdodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t},\n\t// This sets the per-retry timeout\n\toption.WithRequestTimeout(20*time.Second),\n)\n```\n\n### File uploads\n\nRequest parameters that correspond to file uploads in multipart requests are typed as\n`param.Field[io.Reader]`. The contents of the `io.Reader` will by default be sent as a multipart form\npart with the file name of "anonymous_file" and content-type of "application/octet-stream".\n\nThe file name and content-type can be customized by implementing `Name() string` or `ContentType()\nstring` on the run-time type of `io.Reader`. Note that `os.File` implements `Name() string`, so a\nfile returned by `os.Open` will be sent with the file name on disk.\n\nWe also provide a helper `SDK_PackageName.FileParam(reader io.Reader, filename string, contentType string)`\nwhich can be used to wrap any `io.Reader` with the appropriate file name and content type.\n\n\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nWe retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit,\nand >=500 Internal errors.\n\nYou can use the `WithMaxRetries` option to configure or disable this:\n\n```go\n// Configure the default for all requests:\nclient := dodopayments.NewClient(\n\toption.WithMaxRetries(0), // default is 2\n)\n\n// Override per-request:\nclient.CheckoutSessions.New(\n\tcontext.TODO(),\n\tdodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t},\n\toption.WithMaxRetries(5),\n)\n```\n\n\n### Accessing raw response data (e.g. response headers)\n\nYou can access the raw HTTP response data by using the `option.WithResponseInto()` request option. This is useful when\nyou need to examine response headers, status codes, or other details.\n\n```go\n// Create a variable to store the HTTP response\nvar response *http.Response\ncheckoutSessionResponse, err := client.CheckoutSessions.New(\n\tcontext.TODO(),\n\tdodopayments.CheckoutSessionNewParams{\n\t\tCheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{\n\t\t\tProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{\n\t\t\t\tProductID: dodopayments.F("product_id"),\n\t\t\t\tQuantity: dodopayments.F(int64(0)),\n\t\t\t}}),\n\t\t},\n\t},\n\toption.WithResponseInto(&response),\n)\nif err != nil {\n\t// handle error\n}\nfmt.Printf("%+v\\n", checkoutSessionResponse)\n\nfmt.Printf("Status Code: %d\\n", response.StatusCode)\nfmt.Printf("Headers: %+#v\\n", response.Header)\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.Get`, `client.Post`, and other HTTP verbs.\n`RequestOptions` on the client, such as retries, will be respected when making these requests.\n\n```go\nvar (\n // params can be an io.Reader, a []byte, an encoding/json serializable object,\n // or a "…Params" struct defined in this library.\n params map[string]interface{}\n\n // result can be an []byte, *http.Response, a encoding/json deserializable object,\n // or a model defined in this library.\n result *http.Response\n)\nerr := client.Post(context.Background(), "/unspecified", params, &result)\nif err != nil {\n …\n}\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use either the `SDK_PackageOptionName.WithQuerySet()`\nor the `SDK_PackageOptionName.WithJSONSet()` methods.\n\n```go\nparams := FooNewParams{\n ID: SDK_PackageName.F("id_xxxx"),\n Data: SDK_PackageName.F(FooNewParamsData{\n FirstName: SDK_PackageName.F("John"),\n }),\n}\nclient.Foo.New(context.Background(), params, SDK_PackageOptionName.WithJSONSet("data.last_name", "Doe"))\n```\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may either access the raw JSON of the response as a string\nwith `result.JSON.RawJSON()`, or get the raw JSON of a particular field on the result with\n`result.JSON.Foo.Raw()`.\n\nAny fields that are not present on the response struct will be saved and can be accessed by `result.JSON.ExtraFields()` which returns the extra fields as a `map[string]Field`.\n\n### Middleware\n\nWe provide `SDK_PackageOptionName.WithMiddleware` which applies the given\nmiddleware to requests.\n\n```go\nfunc Logger(req *http.Request, next SDK_PackageOptionName.MiddlewareNext) (res *http.Response, err error) {\n\t// Before the request\n\tstart := time.Now()\n\tLogReq(req)\n\n\t// Forward the request to the next handler\n\tres, err = next(req)\n\n\t// Handle stuff after the request\n\tend := time.Now()\n\tLogRes(res, err, start - end)\n\n return res, err\n}\n\nclient := SDK_PackageName.SDK_ClientInitializerName(\n\tSDK_PackageOptionName.WithMiddleware(Logger),\n)\n```\n\nWhen multiple middlewares are provided as variadic arguments, the middlewares\nare applied left to right. If `SDK_PackageOptionName.WithMiddleware` is given\nmultiple times, for example first in the client then the method, the\nmiddleware in the client will run first and the middleware given in the method\nwill run next.\n\nYou may also replace the default `http.Client` with\n`SDK_PackageOptionName.WithHTTPClient(client)`. Only one http client is\naccepted (this overwrites any previous client) and receives requests after any\nmiddleware has been applied.\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/dodopayments/dodopayments-go/issues) with questions, bugs, or suggestions.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n',
|
|
6923
6933
|
},
|
|
6924
6934
|
{
|
|
6925
6935
|
language: 'ruby',
|
|
6926
|
-
content: '# Dodo Payments Ruby API library\n\nThe Dodo Payments Ruby library provides convenient access to the Dodo Payments REST API from any Ruby 3.2.0+ application. It ships with comprehensive types & docstrings in Yard, RBS, and RBI – [see below](https://github.com/dodopayments/dodopayments-ruby#Sorbet) for usage with Sorbet. The standard library\'s `net/http` is used as the HTTP transport, with connection pooling via the `connection_pool` gem.\n\n\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n[](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22dodopayments-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22dodopayments-mcp%22%5D%2C%22env%22%3A%7B%22DODO_PAYMENTS_API_KEY%22%3A%22My%20Bearer%20Token%22%2C%22DODO_PAYMENTS_WEBHOOK_KEY%22%3A%22My%20Webhook%20Key%22%7D%7D)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Documentation\n\nDocumentation for releases of this gem can be found [on RubyDoc](https://gemdocs.org/gems/dodopayments).\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction).\n\n## Installation\n\nTo use this gem, install via Bundler by adding the following to your application\'s `Gemfile`:\n\n<!-- x-release-please-start-version -->\n\n```ruby\ngem "dodopayments", "~> 0.0.1"\n```\n\n<!-- x-release-please-end -->\n\n## Usage\n\n```ruby\nrequire "bundler/setup"\nrequire "dodopayments"\n\ndodo_payments = Dodopayments::Client.new(\n bearer_token: ENV["DODO_PAYMENTS_API_KEY"], # This is the default and can be omitted\n environment: "test_mode" # defaults to "live_mode"\n)\n\ncheckout_session_response = dodo_payments.checkout_sessions.create(product_cart: [{product_id: "pdt_example", quantity: 1}])\n\nputs(checkout_session_response.session_id)\n```\n\n\n\n### Pagination\n\nList methods in the Dodo Payments API are paginated.\n\nThis library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:\n\n```ruby\npage = dodo_payments.payments.list\n\n# Fetch single item from page.\npayment = page.items[0]\nputs(payment.brand_id)\n\n# Automatically fetches more pages as needed.\npage.auto_paging_each do |payment|\n puts(payment.brand_id)\nend\n```\n\nAlternatively, you can use the `#next_page?` and `#next_page` methods for more granular control working with pages.\n\n```ruby\nif page.next_page?\n new_page = page.next_page\n puts(new_page.items[0].brand_id)\nend\n```\n\n\n\n### Handling errors\n\nWhen the library is unable to connect to the API, or if the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of `Dodopayments::Errors::APIError` will be thrown:\n\n```ruby\nbegin\n checkout_session = dodo_payments.checkout_sessions.create(product_cart: [{product_id: "pdt_example", quantity: 1}])\nrescue Dodopayments::Errors::APIConnectionError => e\n puts("The server could not be reached")\n puts(e.cause) # an underlying Exception, likely raised within `net/http`\nrescue Dodopayments::Errors::RateLimitError => e\n puts("A 429 status code was received; we should back off a bit.")\nrescue Dodopayments::Errors::APIStatusError => e\n puts("Another non-200-range status code was received")\n puts(e.status)\nend\n```\n\nError codes are as follows:\n\n| Cause | Error Type |\n| ---------------- | -------------------------- |\n| HTTP 400 | `BadRequestError` |\n| HTTP 401 | `AuthenticationError` |\n| HTTP 403 | `PermissionDeniedError` |\n| HTTP 404 | `NotFoundError` |\n| HTTP 409 | `ConflictError` |\n| HTTP 422 | `UnprocessableEntityError` |\n| HTTP 429 | `RateLimitError` |\n| HTTP >= 500 | `InternalServerError` |\n| Other HTTP error | `APIStatusError` |\n| Timeout | `APITimeoutError` |\n| Network error | `APIConnectionError` |\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\n\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts will all be retried by default.\n\nYou can use the `max_retries` option to configure or disable this:\n\n```ruby\n# Configure the default for all requests:\ndodo_payments = Dodopayments::Client.new(\n max_retries: 0 # default is 2\n)\n\n# Or, configure per-request:\ndodo_payments.checkout_sessions.create(\n product_cart: [{product_id: "pdt_example", quantity: 1}],\n request_options: {max_retries: 5}\n)\n```\n\n### Timeouts\n\nBy default, requests will time out after 60 seconds. You can use the timeout option to configure or disable this:\n\n```ruby\n# Configure the default for all requests:\ndodo_payments = Dodopayments::Client.new(\n timeout: nil # default is 60\n)\n\n# Or, configure per-request:\ndodo_payments.checkout_sessions.create(\n product_cart: [{product_id: "pdt_example", quantity: 1}],\n request_options: {timeout: 5}\n)\n```\n\nOn timeout, `Dodopayments::Errors::APITimeoutError` is raised.\n\nNote that requests that time out are retried by default.\n\n## Advanced concepts\n\n### BaseModel\n\nAll parameter and response objects inherit from `Dodopayments::Internal::Type::BaseModel`, which provides several conveniences, including:\n\n1. All fields, including unknown ones, are accessible with `obj[:prop]` syntax, and can be destructured with `obj => {prop: prop}` or pattern-matching syntax.\n\n2. Structural equivalence for equality; if two API calls return the same values, comparing the responses with == will return true.\n\n3. Both instances and the classes themselves can be pretty-printed.\n\n4. Helpers such as `#to_h`, `#deep_to_h`, `#to_json`, and `#to_yaml`.\n\n### Making custom or undocumented requests\n\n#### Undocumented properties\n\nYou can send undocumented parameters to any endpoint, and read undocumented response properties, like so:\n\nNote: the `extra_` parameters of the same name overrides the documented parameters.\n\n```ruby\ncheckout_session_response =\n dodo_payments.checkout_sessions.create(\n product_cart: [{product_id: "pdt_example", quantity: 1}],\n request_options: {\n extra_query: {my_query_parameter: value},\n extra_body: {my_body_parameter: value},\n extra_headers: {"my-header": value}\n }\n )\n\nputs(checkout_session_response[:my_undocumented_property])\n```\n\n#### Undocumented request params\n\nIf you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` under the `request_options:` parameter when making a request, as seen in the examples above.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints while retaining the benefit of auth, retries, and so on, you can make requests using `client.request`, like so:\n\n```ruby\nresponse = client.request(\n method: :post,\n path: \'/undocumented/endpoint\',\n query: {"dog": "woof"},\n headers: {"useful-header": "interesting-value"},\n body: {"hello": "world"}\n)\n```\n\n### Concurrency & connection pooling\n\nThe `Dodopayments::Client` instances are threadsafe, but are only are fork-safe when there are no in-flight HTTP requests.\n\nEach instance of `Dodopayments::Client` has its own HTTP connection pool with a default size of 99. As such, we recommend instantiating the client once per application in most settings.\n\nWhen all available connections from the pool are checked out, requests wait for a new connection to become available, with queue time counting towards the request timeout.\n\nUnless otherwise specified, other classes in the SDK do not have locks protecting their underlying data structure.\n\n## Sorbet\n\nThis library provides comprehensive [RBI](https://sorbet.org/docs/rbi) definitions, and has no dependency on sorbet-runtime.\n\nYou can provide typesafe request parameters like so:\n\n```ruby\ndodo_payments.checkout_sessions.create(\n product_cart: [Dodopayments::ProductItemReq.new(product_id: "pdt_example", quantity: 1)]\n)\n```\n\nOr, equivalently:\n\n```ruby\n# Hashes work, but are not typesafe:\ndodo_payments.checkout_sessions.create(product_cart: [{product_id: "pdt_example", quantity: 1}])\n\n# You can also splat a full Params class:\nparams = Dodopayments::CheckoutSessionCreateParams.new(\n product_cart: [Dodopayments::ProductItemReq.new(product_id: "pdt_example", quantity: 1)]\n)\ndodo_payments.checkout_sessions.create(**params)\n```\n\n### Enums\n\nSince this library does not depend on `sorbet-runtime`, it cannot provide [`T::Enum`](https://sorbet.org/docs/tenum) instances. Instead, we provide "tagged symbols" instead, which is always a primitive at runtime:\n\n```ruby\n# :AED\nputs(Dodopayments::Currency::AED)\n\n# Revealed type: `T.all(Dodopayments::Currency, Symbol)`\nT.reveal_type(Dodopayments::Currency::AED)\n```\n\nEnum parameters have a "relaxed" type, so you can either pass in enum constants or their literal value:\n\n```ruby\n# Using the enum constants preserves the tagged type information:\ndodo_payments.checkout_sessions.create(\n billing_currency: Dodopayments::Currency::AED,\n # …\n)\n\n# Literal values are also permissible:\ndodo_payments.checkout_sessions.create(\n billing_currency: :AED,\n # …\n)\n```\n\n## Versioning\n\nThis package follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions. As the library is in initial development and has a major version of `0`, APIs may change at any time.\n\nThis package considers improvements to the (non-runtime) `*.rbi` and `*.rbs` type definitions to be non-breaking changes.\n\n## Requirements\n\nRuby 3.2.0 or higher.\n\n## Contributing\n\nSee [the contributing documentation](https://github.com/dodopayments/dodopayments-ruby/tree/main/CONTRIBUTING.md).\n',
|
|
6936
|
+
content: '# Dodo Payments Ruby API library\n\nThe Dodo Payments Ruby library provides convenient access to the Dodo Payments REST API from any Ruby 3.2.0+ application. It ships with comprehensive types & docstrings in Yard, RBS, and RBI – [see below](https://github.com/dodopayments/dodopayments-ruby#Sorbet) for usage with Sorbet. The standard library\'s `net/http` is used as the HTTP transport, with connection pooling via the `connection_pool` gem.\n\n\n\n\n\n## MCP Server\n\nUse the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.\n\n[](https://cursor.com/en-US/install-mcp?name=dodopayments-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImRvZG9wYXltZW50cy1tY3AiXSwiZW52Ijp7IkRPRE9fUEFZTUVOVFNfQVBJX0tFWSI6Ik15IEJlYXJlciBUb2tlbiIsIkRPRE9fUEFZTUVOVFNfV0VCSE9PS19LRVkiOiJNeSBXZWJob29rIEtleSJ9fQ)\n\n> Note: You may need to set environment variables in your MCP client.\n\n## Documentation\n\nDocumentation for releases of this gem can be found [on RubyDoc](https://gemdocs.org/gems/dodopayments).\n\nThe REST API documentation can be found on [docs.dodopayments.com](https://docs.dodopayments.com/api-reference/introduction).\n\n## Installation\n\nTo use this gem, install via Bundler by adding the following to your application\'s `Gemfile`:\n\n<!-- x-release-please-start-version -->\n\n```ruby\ngem "dodopayments", "~> 0.0.1"\n```\n\n<!-- x-release-please-end -->\n\n## Usage\n\n```ruby\nrequire "bundler/setup"\nrequire "dodopayments"\n\ndodo_payments = Dodopayments::Client.new(\n bearer_token: ENV["DODO_PAYMENTS_API_KEY"], # This is the default and can be omitted\n environment: "test_mode" # defaults to "live_mode"\n)\n\ncheckout_session_response = dodo_payments.checkout_sessions.create(product_cart: [{product_id: "pdt_example", quantity: 1}])\n\nputs(checkout_session_response.session_id)\n```\n\n\n\n### Pagination\n\nList methods in the Dodo Payments API are paginated.\n\nThis library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:\n\n```ruby\npage = dodo_payments.payments.list\n\n# Fetch single item from page.\npayment = page.items[0]\nputs(payment.brand_id)\n\n# Automatically fetches more pages as needed.\npage.auto_paging_each do |payment|\n puts(payment.brand_id)\nend\n```\n\nAlternatively, you can use the `#next_page?` and `#next_page` methods for more granular control working with pages.\n\n```ruby\nif page.next_page?\n new_page = page.next_page\n puts(new_page.items[0].brand_id)\nend\n```\n\n\n\n### Handling errors\n\nWhen the library is unable to connect to the API, or if the API returns a non-success status code (i.e., 4xx or 5xx response), a subclass of `Dodopayments::Errors::APIError` will be thrown:\n\n```ruby\nbegin\n checkout_session = dodo_payments.checkout_sessions.create(product_cart: [{product_id: "pdt_example", quantity: 1}])\nrescue Dodopayments::Errors::APIConnectionError => e\n puts("The server could not be reached")\n puts(e.cause) # an underlying Exception, likely raised within `net/http`\nrescue Dodopayments::Errors::RateLimitError => e\n puts("A 429 status code was received; we should back off a bit.")\nrescue Dodopayments::Errors::APIStatusError => e\n puts("Another non-200-range status code was received")\n puts(e.status)\nend\n```\n\nError codes are as follows:\n\n| Cause | Error Type |\n| ---------------- | -------------------------- |\n| HTTP 400 | `BadRequestError` |\n| HTTP 401 | `AuthenticationError` |\n| HTTP 403 | `PermissionDeniedError` |\n| HTTP 404 | `NotFoundError` |\n| HTTP 409 | `ConflictError` |\n| HTTP 422 | `UnprocessableEntityError` |\n| HTTP 429 | `RateLimitError` |\n| HTTP >= 500 | `InternalServerError` |\n| Other HTTP error | `APIStatusError` |\n| Timeout | `APITimeoutError` |\n| Network error | `APIConnectionError` |\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\n\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts will all be retried by default.\n\nYou can use the `max_retries` option to configure or disable this:\n\n```ruby\n# Configure the default for all requests:\ndodo_payments = Dodopayments::Client.new(\n max_retries: 0 # default is 2\n)\n\n# Or, configure per-request:\ndodo_payments.checkout_sessions.create(\n product_cart: [{product_id: "pdt_example", quantity: 1}],\n request_options: {max_retries: 5}\n)\n```\n\n### Timeouts\n\nBy default, requests will time out after 60 seconds. You can use the timeout option to configure or disable this:\n\n```ruby\n# Configure the default for all requests:\ndodo_payments = Dodopayments::Client.new(\n timeout: nil # default is 60\n)\n\n# Or, configure per-request:\ndodo_payments.checkout_sessions.create(\n product_cart: [{product_id: "pdt_example", quantity: 1}],\n request_options: {timeout: 5}\n)\n```\n\nOn timeout, `Dodopayments::Errors::APITimeoutError` is raised.\n\nNote that requests that time out are retried by default.\n\n## Advanced concepts\n\n### BaseModel\n\nAll parameter and response objects inherit from `Dodopayments::Internal::Type::BaseModel`, which provides several conveniences, including:\n\n1. All fields, including unknown ones, are accessible with `obj[:prop]` syntax, and can be destructured with `obj => {prop: prop}` or pattern-matching syntax.\n\n2. Structural equivalence for equality; if two API calls return the same values, comparing the responses with == will return true.\n\n3. Both instances and the classes themselves can be pretty-printed.\n\n4. Helpers such as `#to_h`, `#deep_to_h`, `#to_json`, and `#to_yaml`.\n\n### Making custom or undocumented requests\n\n#### Undocumented properties\n\nYou can send undocumented parameters to any endpoint, and read undocumented response properties, like so:\n\nNote: the `extra_` parameters of the same name overrides the documented parameters.\n\n```ruby\ncheckout_session_response =\n dodo_payments.checkout_sessions.create(\n product_cart: [{product_id: "pdt_example", quantity: 1}],\n request_options: {\n extra_query: {my_query_parameter: value},\n extra_body: {my_body_parameter: value},\n extra_headers: {"my-header": value}\n }\n )\n\nputs(checkout_session_response[:my_undocumented_property])\n```\n\n#### Undocumented request params\n\nIf you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` under the `request_options:` parameter when making a request, as seen in the examples above.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints while retaining the benefit of auth, retries, and so on, you can make requests using `client.request`, like so:\n\n```ruby\nresponse = client.request(\n method: :post,\n path: \'/undocumented/endpoint\',\n query: {"dog": "woof"},\n headers: {"useful-header": "interesting-value"},\n body: {"hello": "world"}\n)\n```\n\n### Concurrency & connection pooling\n\nThe `Dodopayments::Client` instances are threadsafe, but are only are fork-safe when there are no in-flight HTTP requests.\n\nEach instance of `Dodopayments::Client` has its own HTTP connection pool with a default size of 99. As such, we recommend instantiating the client once per application in most settings.\n\nWhen all available connections from the pool are checked out, requests wait for a new connection to become available, with queue time counting towards the request timeout.\n\nUnless otherwise specified, other classes in the SDK do not have locks protecting their underlying data structure.\n\n## Sorbet\n\nThis library provides comprehensive [RBI](https://sorbet.org/docs/rbi) definitions, and has no dependency on sorbet-runtime.\n\nYou can provide typesafe request parameters like so:\n\n```ruby\ndodo_payments.checkout_sessions.create(\n product_cart: [Dodopayments::ProductItemReq.new(product_id: "pdt_example", quantity: 1)]\n)\n```\n\nOr, equivalently:\n\n```ruby\n# Hashes work, but are not typesafe:\ndodo_payments.checkout_sessions.create(product_cart: [{product_id: "pdt_example", quantity: 1}])\n\n# You can also splat a full Params class:\nparams = Dodopayments::CheckoutSessionCreateParams.new(\n product_cart: [Dodopayments::ProductItemReq.new(product_id: "pdt_example", quantity: 1)]\n)\ndodo_payments.checkout_sessions.create(**params)\n```\n\n### Enums\n\nSince this library does not depend on `sorbet-runtime`, it cannot provide [`T::Enum`](https://sorbet.org/docs/tenum) instances. Instead, we provide "tagged symbols" instead, which is always a primitive at runtime:\n\n```ruby\n# :AED\nputs(Dodopayments::Currency::AED)\n\n# Revealed type: `T.all(Dodopayments::Currency, Symbol)`\nT.reveal_type(Dodopayments::Currency::AED)\n```\n\nEnum parameters have a "relaxed" type, so you can either pass in enum constants or their literal value:\n\n```ruby\n# Using the enum constants preserves the tagged type information:\ndodo_payments.checkout_sessions.create(\n billing_currency: Dodopayments::Currency::AED,\n # …\n)\n\n# Literal values are also permissible:\ndodo_payments.checkout_sessions.create(\n billing_currency: :AED,\n # …\n)\n```\n\n## Versioning\n\nThis package follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions. As the library is in initial development and has a major version of `0`, APIs may change at any time.\n\nThis package considers improvements to the (non-runtime) `*.rbi` and `*.rbs` type definitions to be non-breaking changes.\n\n## Requirements\n\nRuby 3.2.0 or higher.\n\n## Contributing\n\nSee [the contributing documentation](https://github.com/dodopayments/dodopayments-ruby/tree/main/CONTRIBUTING.md).\n',
|
|
6927
6937
|
},
|
|
6928
6938
|
{
|
|
6929
6939
|
language: 'php',
|