Skip to main content

Installation

1

Install the package

Run the following command in your project root:
bun add @dodopayments/bun
2

Set up environment variables

Create a .env file in your project root:
DODO_PAYMENTS_API_KEY=your-api-key
DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret
DODO_PAYMENTS_ENVIRONMENT="test_mode" or "live_mode"
DODO_PAYMENTS_RETURN_URL=your-return-url
Never commit your .env file or secrets to version control.

Route Handler Examples

All examples assume you are using Bun’s native server with Bun.serve().
Use this handler to integrate Dodo Payments checkout into your Bun server. Supports static (GET), dynamic (POST), and session (POST) payment flows.
import { Checkout } from '@dodopayments/bun';

const staticCheckoutHandler = Checkout({
    bearerToken: process.env.DODO_PAYMENTS_API_KEY,
    returnUrl: process.env.DODO_PAYMENTS_RETURN_URL,
    environment: process.env.DODO_PAYMENTS_ENVIRONMENT,
    type: "static"
});

const sessionCheckoutHandler = Checkout({
    bearerToken: process.env.DODO_PAYMENTS_API_KEY,
    returnUrl: process.env.DODO_PAYMENTS_RETURN_URL,
    environment: process.env.DODO_PAYMENTS_ENVIRONMENT,
    type: "session"
});

const dynamicCheckoutHandler = Checkout({
    bearerToken: process.env.DODO_PAYMENTS_API_KEY,
    returnUrl: process.env.DODO_PAYMENTS_RETURN_URL,
    environment: process.env.DODO_PAYMENTS_ENVIRONMENT,
    type: "dynamic"
});

Bun.serve({
  port: 3000,
  fetch(request) {
    const url = new URL(request.url);
    
    if (url.pathname === "/api/checkout") {
      if (request.method === "GET") {
        return staticCheckoutHandler(request);
      }
      if (request.method === "POST") {
        return sessionCheckoutHandler(request);
        // or return dynamicCheckoutHandler(request);
      }
    }
    
    return new Response("Not Found", { status: 404 });
  },
});
curl --request GET \
--url 'https://example.com/api/checkout?productId=pdt_xxx' \
--header 'User-Agent: insomnia/11.2.0' \
--cookie mode=test
curl --request POST \
--url https://example.com/api/checkout \
--header 'Content-Type: application/json' \
--header 'User-Agent: insomnia/11.2.0' \
--cookie mode=test \
--data '{
"billing": {
  "city": "Texas",
  "country": "US",
  "state": "Texas",
  "street": "56, hhh",
  "zipcode": "560000"
},
"customer": {
  "email": "[email protected]",
  	"name": "test"
},
"metadata": {},
"payment_link": true,
  "product_id": "pdt_xxx",
  "quantity": 1,
  "billing_currency": "USD",
  "discount_code": "IKHZ23M9GQ",
  "return_url": "https://example.com",
  "trial_period_days": 10
}'
curl --request POST \
--url https://example.com/api/checkout \
--header 'Content-Type: application/json' \
--header 'User-Agent: insomnia/11.2.0' \
--cookie mode=test \
--data '{
"product_cart": [
  {
    "product_id": "pdt_xxx",
    "quantity": 1
  }
],
"customer": {
  "email": "[email protected]",
  "name": "test"
},
"return_url": "https://example.com/success"
}'

Checkout Route Handler

Dodo Payments supports three types of payment flows for integrating payments into your website, this adaptor supports all types of payment flows.
  • Static Payment Links: Instantly shareable URLs for quick, no-code payment collection.
  • Dynamic Payment Links: Programmatically generate payment links with custom details using the API or SDKs.
  • Checkout Sessions: Create secure, customizable checkout experiences with pre-configured product carts and customer details.

Supported Query Parameters

productId
string
required
Product identifier (e.g., ?productId=pdt_xxx).
quantity
integer
Quantity of the product.
fullName
string
Customer’s full name.
firstName
string
Customer’s first name.
lastName
string
Customer’s last name.
email
string
Customer’s email address.
country
string
Customer’s country.
addressLine
string
Customer’s address line.
city
string
Customer’s city.
state
string
Customer’s state/province.
zipCode
string
Customer’s zip/postal code.
disableFullName
boolean
Disable full name field.
disableFirstName
boolean
Disable first name field.
disableLastName
boolean
Disable last name field.
disableEmail
boolean
Disable email field.
disableCountry
boolean
Disable country field.
disableAddressLine
boolean
Disable address line field.
disableCity
boolean
Disable city field.
disableState
boolean
Disable state field.
disableZipCode
boolean
Disable zip code field.
paymentCurrency
string
Specify the payment currency (e.g., USD).
showCurrencySelector
boolean
Show currency selector.
paymentAmount
integer
Specify the payment amount (e.g., 1000 for $10.00).
showDiscounts
boolean
Show discount fields.
metadata_*
string
Any query parameter starting with metadata_ will be passed as metadata.
If productId is missing, the handler returns a 400 response. Invalid query parameters also result in a 400 response.

Response Format

Static checkout returns a JSON response with the checkout URL:
{
  "checkout_url": "https://checkout.dodopayments.com/..."
}

Response Format

Dynamic checkout returns a JSON response with the checkout URL:
{
  "checkout_url": "https://checkout.dodopayments.com/..."
}
Checkout sessions provide a more secure, hosted checkout experience that handles the complete payment flow for both one-time purchases and subscriptions with full customization control.Refer to Checkout Sessions Integration Guide for more details and a complete list of supported fields.

Response Format

Checkout sessions return a JSON response with the checkout URL:
{
  "checkout_url": "https://checkout.dodopayments.com/session/..."
}

Customer Portal Route Handler

The Customer Portal Route Handler enables you to seamlessly integrate the Dodo Payments customer portal into your Bun server application.

Query Parameters

customer_id
string
required
The customer ID for the portal session (e.g., ?customer_id=cus_123).
send_email
boolean
If set to true, sends an email to the customer with the portal link.
Returns 400 if customer_id is missing.

Webhook Route Handler

  • Method: Only POST requests are supported. Other methods return 405.
  • Signature Verification: Verifies the webhook signature using webhookKey. Returns 401 if verification fails.
  • Payload Validation: Validated with Zod. Returns 400 for invalid payloads.
  • Error Handling:
    • 401: Invalid signature
    • 400: Invalid payload
    • 500: Internal error during verification
  • Event Routing: Calls the appropriate event handler based on the payload type.

Supported Webhook Event Handlers

onPayload?: (payload: WebhookPayload) => Promise<void>;
onPaymentSucceeded?: (payload: WebhookPayload) => Promise<void>;
onPaymentFailed?: (payload: WebhookPayload) => Promise<void>;
onPaymentProcessing?: (payload: WebhookPayload) => Promise<void>;
onPaymentCancelled?: (payload: WebhookPayload) => Promise<void>;
onRefundSucceeded?: (payload: WebhookPayload) => Promise<void>;
onRefundFailed?: (payload: WebhookPayload) => Promise<void>;
onDisputeOpened?: (payload: WebhookPayload) => Promise<void>;
onDisputeExpired?: (payload: WebhookPayload) => Promise<void>;
onDisputeAccepted?: (payload: WebhookPayload) => Promise<void>;
onDisputeCancelled?: (payload: WebhookPayload) => Promise<void>;
onDisputeChallenged?: (payload: WebhookPayload) => Promise<void>;
onDisputeWon?: (payload: WebhookPayload) => Promise<void>;
onDisputeLost?: (payload: WebhookPayload) => Promise<void>;
onSubscriptionActive?: (payload: WebhookPayload) => Promise<void>;
onSubscriptionOnHold?: (payload: WebhookPayload) => Promise<void>;
onSubscriptionRenewed?: (payload: WebhookPayload) => Promise<void>;
onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise<void>;
onSubscriptionCancelled?: (payload: WebhookPayload) => Promise<void>;
onSubscriptionFailed?: (payload: WebhookPayload) => Promise<void>;
onSubscriptionExpired?: (payload: WebhookPayload) => Promise<void>;
onLicenseKeyCreated?: (payload: WebhookPayload) => Promise<void>;

Prompt for LLM


You are an expert Bun developer assistant. Your task is to guide a user through integrating the @dodopayments/bun adapter into their existing Bun project.

The @dodopayments/bun adapter provides handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for Bun's native server with Bun.serve().

First, install the necessary package:

bun add @dodopayments/bun

Here's how you should structure your response:

    Ask the user which functionalities they want to integrate.

"Which parts of the @dodopayments/bun adapter would you like to integrate into your project? You can choose one or more of the following:
1. Checkout (static, dynamic, or session-based)
2. Customer Portal
3. Webhooks"

    Based on the user's selection, provide step-by-step integration instructions.

For each selected functionality, show:

    The environment variables required
    The exact code to add to their server file
    Where to place the code in their Bun.serve() configuration

Provide complete, working examples that the user can copy and paste directly into their project.

    Environment Variables Setup

Always include instructions for setting up the .env file:

DODO_PAYMENTS_API_KEY=your-api-key
DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret
DODO_PAYMENTS_ENVIRONMENT="test_mode" or "live_mode"
DODO_PAYMENTS_RETURN_URL=your-return-url

Remind the user to never commit their .env file to version control.

    For Checkout Integration

If the user selects Checkout, ask which type they need:

    Static checkout (GET requests with query parameters)
    Dynamic checkout (POST requests with JSON body)
    Checkout sessions (POST requests with product cart)

Provide the appropriate handler code for their selection.

    For Customer Portal Integration

Provide a complete example showing how to integrate the customer portal handler into their Bun server.

    For Webhook Integration

Provide a complete example showing how to integrate the webhook handler with available event handlers for granular control.

    Full Example

If the user wants to integrate all three functionalities, provide a complete Bun server example that combines all handlers.

```typescript
import { Checkout, CustomerPortal, Webhooks } from "@dodopayments/bun";

const staticCheckoutHandler = Checkout({
  bearerToken: process.env.DODO_PAYMENTS_API_KEY,
  returnUrl: process.env.DODO_PAYMENTS_RETURN_URL,
  environment: process.env.DODO_PAYMENTS_ENVIRONMENT,
  type: "static",
});

const sessionCheckoutHandler = Checkout({
  bearerToken: process.env.DODO_PAYMENTS_API_KEY,
  returnUrl: process.env.DODO_PAYMENTS_RETURN_URL,
  environment: process.env.DODO_PAYMENTS_ENVIRONMENT,
  type: "session",
});

const customerPortalHandler = CustomerPortal({
  bearerToken: process.env.DODO_PAYMENTS_API_KEY,
  environment: process.env.DODO_PAYMENTS_ENVIRONMENT,
});

const webhookHandler = Webhooks({
  webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY,
  onPaymentSucceeded: async (payload) => {
    console.log("Payment succeeded:", payload);
    // Your business logic here
  },
  onSubscriptionActive: async (payload) => {
    console.log("Subscription activated:", payload);
    // Your business logic here
  },
});

Bun.serve({
  port: 3000,
  fetch(request) {
    const url = new URL(request.url);
    
    // Checkout routes
    if (url.pathname === "/api/checkout") {
      if (request.method === "GET") {
        return staticCheckoutHandler(request);
      }
      if (request.method === "POST") {
        return sessionCheckoutHandler(request);
      }
    }
    
    // Customer portal route
    if (url.pathname === "/api/customer-portal" && request.method === "GET") {
      return customerPortalHandler(request);
    }
    
    // Webhook route
    if (url.pathname === "/api/webhook/dodo-payments" && request.method === "POST") {
      return webhookHandler(request);
    }
    
    return new Response("Not Found", { status: 404 });
  },
});

console.log("Server running on http://localhost:3000");

Additional Guidance:
• Explain that the handlers are Bun-native and work seamlessly with Bun.serve()
• Highlight the use of Web Standard Request and Response objects
• Mention that error handling is built-in and returns appropriate HTTP status codes
• Provide links to the Dodo Payments documentation for more details