> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Ruby

> Use the Dodo Payments Ruby SDK to create checkout sessions, customers, and subscriptions from Ruby 3.2+, with auto-pagination, retries, and Sorbet types.

The Ruby SDK gives Ruby applications access to the Dodo Payments REST API. It sends requests with the standard library's `net/http` and a connection pool, retries failed requests, iterates through paginated lists for you, and ships RBI and RBS type definitions.

## Installation

Add the gem to your Gemfile:

```ruby Gemfile theme={null}
gem "dodopayments", "~> 2.30"
```

<Tip>
  SDK releases add support for API changes. Run `bundle update dodopayments` regularly to stay up to date.
</Tip>

Then install it:

```bash theme={null}
bundle install
```

<Info>
  The SDK requires Ruby 3.2.0 or later.
</Info>

## Quick Start

Create a client, then create a checkout session:

```ruby theme={null}
require "bundler/setup"
require "dodopayments"

dodo_payments = Dodopayments::Client.new(
  bearer_token: ENV["DODO_PAYMENTS_API_KEY"], # This is the default and can be omitted
  environment: "test_mode" # defaults to "live_mode"
)

checkout_session_response = dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "pdt_123", quantity: 1}]
)

puts(checkout_session_response.session_id)
```

If you omit `bearer_token`, the client reads the `DODO_PAYMENTS_API_KEY` environment variable. If you omit `environment`, the client connects to live mode. A test mode API key works only with `environment: "test_mode"`.

<Warning>
  Keep API keys in environment variables or a secrets manager. Never commit them to version control or expose them in your code.
</Warning>

## Core Features

<CardGroup cols={2}>
  <Card title="Ruby Conventions" icon="gem">
    Snake\_case methods and keyword arguments, with plain hashes accepted for nested parameters.
  </Card>

  <Card title="Elegant Syntax" icon="code">
    Responses are objects with attribute readers, and `obj[:prop]` also reads fields the SDK doesn't define.
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    `auto_paging_each` iterates over every item and fetches the next page when needed.
  </Card>

  <Card title="Type Safety" icon="shield-check">
    RBI definitions for Sorbet, with no dependency on `sorbet-runtime`.
  </Card>
</CardGroup>

## Configuration

`Dodopayments::Client.new` takes `bearer_token`, `webhook_key`, `environment`, `base_url`, `max_retries`, `timeout`, `initial_retry_delay`, and `max_retry_delay`. When you omit them, it reads `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` (your webhook signing secret), and `DODO_PAYMENTS_BASE_URL` from the environment. The client is thread-safe and keeps its own connection pool, so create one client for your application and reuse it.

To verify a webhook, pass the raw request body and headers to `dodo_payments.webhooks.unwrap(payload, headers: headers)`. It checks the signature with your webhook key and returns the parsed event. `dodo_payments.webhooks.unsafe_unwrap(payload)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks).

### Timeout Configuration

Requests time out after 60 seconds by default. Set `timeout`, in seconds, on the client or on a single request:

```ruby theme={null}
# Configure default for all requests (default is 60 seconds)
dodo_payments = Dodopayments::Client.new(
  timeout: nil # disable timeout
)

# Or, configure per-request
dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "pdt_123", quantity: 1}],
  request_options: {timeout: 5}
)
```

When a request times out, the SDK raises `Dodopayments::Errors::APITimeoutError`. Timed-out requests are retried by default.

### Retry Configuration

The SDK retries connection errors, timeouts, and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with a short exponential backoff. Set `max_retries` on the client or on a single request:

```ruby theme={null}
# Configure default for all requests (default is 2)
dodo_payments = Dodopayments::Client.new(
  max_retries: 0 # disable retries
)

# Or, configure per-request
dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "pdt_123", quantity: 1}],
  request_options: {max_retries: 5}
)
```

## Common Operations

The examples in this section use the `dodo_payments` client from [Quick Start](#quick-start).

### Create a Checkout Session

Create a checkout session, then redirect the customer to the returned `checkout_url`:

```ruby theme={null}
session = dodo_payments.checkout_sessions.create(
  product_cart: [
    {
      product_id: "pdt_123",
      quantity: 1
    }
  ],
  return_url: "https://yourdomain.com/return"
)

# In a Rails controller, redirect to checkout
redirect_to session.checkout_url, allow_other_host: true
```

Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session).

### Manage Customers

Create a customer with an email address and name, then retrieve it by ID:

```ruby theme={null}
# Create a customer
customer = dodo_payments.customers.create(
  email: "customer@example.com",
  name: "John Doe",
  metadata: {
    user_id: "12345"
  }
)

# Retrieve customer
customer = dodo_payments.customers.retrieve("cus_123")
puts "Customer: #{customer.name} (#{customer.email})"
```

### Handle Subscriptions

Create a subscription, charge an on-demand subscription, and update a subscription's metadata.

<Warning>
  `POST /subscriptions` (the SDK's `subscriptions.create` method) is **deprecated**. It still works for existing integrations, but new integrations should create subscriptions through a [Checkout Session](/developer-resources/checkout-session).
</Warning>

```ruby theme={null}
# Create a subscription
subscription = dodo_payments.subscriptions.create(
  billing: {
    country: "US",
    city: "San Francisco",
    state: "CA",
    street: "1 Market St",
    zipcode: "94105"
  },
  customer: { customer_id: "cus_123" }, # or { email: "...", name: "..." } for a new customer
  product_id: "pdt_456",
  quantity: 1
)

# Charge an on-demand subscription
# product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
charge = dodo_payments.subscriptions.charge(
  subscription.subscription_id,
  product_price: 2500
)

# Update subscription metadata
updated = dodo_payments.subscriptions.update(
  subscription.subscription_id,
  metadata: { plan_type: "premium" }
)
```

<Info>
  `billing` requires only `country`, a two-letter ISO country code. `customer` takes `{ customer_id: "..." }` to attach an existing customer or `{ email: "...", name: "..." }` to create one. `charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `product_price` is in the smallest currency unit.
</Info>

## Pagination

### Auto-Pagination

List methods return a page. Read `items` for the current page, or call `auto_paging_each` to iterate over every item. It fetches the next page when it needs it:

```ruby theme={null}
page = dodo_payments.payments.list

# Fetch single item from page
payment = page.items[0]
puts(payment.brand_id)

# Automatically fetches more pages as needed
page.auto_paging_each do |payment|
  puts(payment.brand_id)
end
```

### Manual Pagination

To move one page at a time, call `next_page?` and `next_page`:

```ruby theme={null}
page = dodo_payments.payments.list

if page.next_page?
  new_page = page.next_page
  puts(new_page.items[0].brand_id)
end
```

## Error Handling

When the SDK can't connect to the API, or the API returns a 4xx or 5xx status, the SDK raises a subclass of `Dodopayments::Errors::APIError`:

```ruby theme={null}
begin
  checkout_session = dodo_payments.checkout_sessions.create(
    product_cart: [{product_id: "pdt_123", quantity: 1}]
  )
rescue Dodopayments::Errors::APIConnectionError => e
  puts("The server could not be reached")
  puts(e.cause)  # an underlying Exception, likely raised within `net/http`
rescue Dodopayments::Errors::RateLimitError => e
  puts("A 429 status code was received; we should back off a bit.")
rescue Dodopayments::Errors::APIStatusError => e
  puts("Another non-200-range status code was received")
  puts(e.status)
end
```

The error class depends on the cause. Each error has `status`, `headers`, and `body` attributes:

| Cause | Error class |
| - | - |
| HTTP 400 | `BadRequestError` |
| HTTP 401 | `AuthenticationError` |
| HTTP 403 | `PermissionDeniedError` |
| HTTP 404 | `NotFoundError` |
| HTTP 409 | `ConflictError` |
| HTTP 422 | `UnprocessableEntityError` |
| HTTP 429 | `RateLimitError` |
| HTTP 500 and above | `InternalServerError` |
| Other HTTP error | `APIStatusError` |
| Timeout | `APITimeoutError` |
| Network error | `APIConnectionError` |

<Tip>
  The SDK already retries 429 responses with exponential backoff. A `RateLimitError` means those retries also failed, so wait longer before you send the request again.
</Tip>

## Type Safety with Sorbet

The SDK ships RBI definitions and doesn't depend on `sorbet-runtime`. To get type-checked request parameters, pass model classes instead of hashes:

```ruby theme={null}
# Type-safe using Sorbet RBI definitions
dodo_payments.checkout_sessions.create(
  product_cart: [
    Dodopayments::ProductItemReq.new(
      product_id: "pdt_123",
      quantity: 1
    )
  ]
)

# Hashes work, but are not typesafe
dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "pdt_123", quantity: 1}]
)

# You can also splat a full Params class
params = Dodopayments::CheckoutSessionCreateParams.new(
  product_cart: [
    Dodopayments::ProductItemReq.new(
      product_id: "pdt_123",
      quantity: 1
    )
  ]
)
dodo_payments.checkout_sessions.create(**params)
```

## Advanced Usage

### Undocumented Endpoints

To call an endpoint that has no SDK method, use `request`. It applies the same authentication and retries as the SDK methods:

```ruby theme={null}
response = dodo_payments.request(
  method: :post,
  path: '/undocumented/endpoint',
  query: {"dog": "woof"},
  headers: {"useful-header": "interesting-value"},
  body: {"hello": "world"}
)
```

### Undocumented Parameters

To send parameters that the SDK doesn't define, pass them in `request_options`. An `extra_*` parameter that has the same name as a documented parameter overrides it:

```ruby theme={null}
checkout_session_response = dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "pdt_123", quantity: 1}],
  request_options: {
    extra_query: {my_query_parameter: "value"},
    extra_body: {my_body_parameter: "value"},
    extra_headers: {"my-header": "value"}
  }
)

# Access undocumented response properties
puts(checkout_session_response[:my_undocumented_property])
```

## Rails Integration

### Create an Initializer

Create one client when Rails starts, in `config/initializers/dodo_payments.rb`:

```ruby theme={null}
require "dodopayments"

DODO_CLIENT = Dodopayments::Client.new(
  bearer_token: Rails.application.credentials.dodo_api_key,
  environment: Rails.env.production? ? "live_mode" : "test_mode"
)
```

### Service Object Pattern

Wrap the client in a service object:

```ruby theme={null}
# app/services/payment_service.rb
class PaymentService
  def initialize
    @client = DODO_CLIENT
  end

  def create_checkout(items)
    @client.checkout_sessions.create(
      product_cart: items,
      return_url: Rails.application.routes.url_helpers.checkout_return_url
    )
  end

  def process_payment(product_id:, customer_id:, billing:)
    # Note: POST /payments is deprecated — prefer checkout sessions for new integrations
    @client.payments.create(
      billing: billing,
      customer: { customer_id: customer_id },
      product_cart: [{ product_id: product_id, quantity: 1 }]
    )
  end
end
```

### Controller Integration

Call the service from a controller and redirect to the checkout page:

```ruby theme={null}
# app/controllers/checkouts_controller.rb
class CheckoutsController < ApplicationController
  def create
    service = PaymentService.new
    session = service.create_checkout(checkout_params[:items])
    
    redirect_to session.checkout_url, allow_other_host: true
  rescue Dodopayments::Errors::APIError => e
    flash[:error] = "Payment error: #{e.message}"
    redirect_to cart_path
  end

  private

  def checkout_params
    params.require(:checkout).permit(items: [:product_id, :quantity])
  end
end
```

## Sinatra Integration

Create the client once in a `configure` block and use it in your routes:

```ruby theme={null}
require "sinatra"
require "dodopayments"

configure do
  set :dodo_client, Dodopayments::Client.new(
    bearer_token: ENV["DODO_PAYMENTS_API_KEY"]
  )
end

post "/create-checkout" do
  content_type :json
  
  begin
    session = settings.dodo_client.checkout_sessions.create(
      product_cart: JSON.parse(request.body.read)["items"],
      return_url: "#{request.base_url}/return"
    )
    
    { checkout_url: session.checkout_url }.to_json
  rescue Dodopayments::Errors::APIError => e
    status 400
    { error: e.message }.to_json
  end
end
```

## Resources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-ruby">
    Source code, releases, and the full method list.
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Every endpoint, parameter, and response.
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Ask questions and talk with other developers.
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-ruby/issues">
    Report bugs or request features.
  </Card>
</CardGroup>

## Support

For help with the Ruby SDK:

* **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help.
* **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com).
* **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-ruby).

## Contributing

To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-ruby/blob/main/CONTRIBUTING.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.