메인 콘텐츠로 건너뛰기
루비 SDK는 Ruby 애플리케이션에 Dodo Payments를 통합하는 간단하고 직관적인 방법을 제공합니다. Ruby 관습과 모범 사례를 따르며, 포괄적인 오류 처리, 페이지 매김 및 미들웨어 지원을 제공합니다.

설치

Gemfile에 gem을 추가하세요:
Gemfile
gem "dodopayments", "~> 2.9"
항상 최신 SDK 버전을 사용하여 최신 Dodo Payments 기능에 액세스하세요. 최신 상태를 유지하려면 bundle update dodopayments를 정기적으로 실행하세요.
그런 다음 실행하세요:
bundle install
이 SDK는 Ruby 3.2.0 이상을 지원하며 포괄적인 타입, 오류 처리 및 재시도 메커니즘을 제공합니다.

빠른 시작

클라이언트를 초기화하고 체크아웃 세션을 생성하세요:
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: "product_id", quantity: 1}]
)

puts(checkout_session_response.session_id)
환경 변수를 사용하여 API 키를 안전하게 저장하세요. 절대 버전 관리에 커밋하거나 코드에 노출하지 마세요.

주요 기능

Ruby Conventions

Ruby 명명 규칙 및 관용 패턴을 따름

Elegant Syntax

Ruby 개발자에게 자연스럽게 느껴지는 깔끔하고 읽기 쉬운 API

Auto-Pagination

목록 응답을 위한 내장 자동 페이징 반복자

Type Safety

향상된 타입 안전성을 위한 선택적 Sorbet 타입

구성

타임아웃 구성

요청 타임아웃을 구성하세요:
# 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: "product_id", quantity: 1}],
  request_options: {timeout: 5}
)

재시도 구성

자동 재시도 동작을 구성하세요:
# 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: "product_id", quantity: 1}],
  request_options: {max_retries: 5}
)

일반 작업

체크아웃 세션 생성

체크아웃 세션을 생성하세요:
session = dodo_payments.checkout_sessions.create(
  product_cart: [
    {
      product_id: "prod_123",
      quantity: 1
    }
  ],
  return_url: "https://yourdomain.com/return"
)

# Redirect to checkout
redirect_to session.checkout_url

고객 관리

고객 정보를 생성하고 검색하세요:
# 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})"

구독 처리

정기 구독을 생성하고 관리하세요:
# 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" }
)
billing 최소한 ISO 2자리 country 코드가 필요합니다. customer 기존 고객을 연결하기 위한 { customer_id: "..." } 또는 새 고객을 생성하기 위한 { email: "...", name: "..." } 중 하나를 허용합니다. product_price는 가장 낮은 통화 단위에 있습니다.

페이지 매김

자동 페이지 매김

모든 페이지를 자동으로 탐색하세요:
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

수동 페이지 매김

페이지 매김에 대한 더 많은 제어:
page = dodo_payments.payments.list

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

오류 처리

다양한 Dodo Payments API 오류 처리:
begin
  checkout_session = dodo_payments.checkout_sessions.create(
product_cart: [{product_id: "product_id", 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
고용량 시나리오를 우아하게 처리할 수 있도록 속도 제한 오류에 대한 지수 백오프를 사용한 재시도 로직을 구현하세요.

Sorbet를 사용한 유형 안전성

타입 안전한 요청 파라미터를 위해 Sorbet 사용:
# Type-safe using Sorbet RBI definitions
dodo_payments.checkout_sessions.create(
  product_cart: [
    Dodopayments::ProductItemReq.new(
      product_id: "product_id",
      quantity: 1
    )
  ]
)

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

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

고급 사용법

문서화되지 않은 엔드포인트

문서화되지 않은 엔드포인트에 요청하기:
response = dodo_payments.request(
  method: :post,
  path: '/undocumented/endpoint',
  query: {"dog": "woof"},
  headers: {"useful-header": "interesting-value"},
  body: {"hello": "world"}
)

문서화되지 않은 매개변수

문서화되지 않은 매개변수 보내기:
checkout_session_response = dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "product_id", 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])

레일즈 통합

초기화 파일 생성

config/initializers/dodo_payments.rb 생성하기:
require "dodopayments"

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

서비스 오브젝트 패턴

결제 서비스를 생성하세요:
# 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(amount:, currency:, customer_id:)
    @client.payments.create(
      amount: amount,
      currency: currency,
      customer_id: customer_id
    )
  end
end

컨트롤러 통합

레일즈 컨트롤러에서 사용하기:
# 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

시나트라 통합

시나트라 애플리케이션과 함께 사용하기:
require "sinatra"
require "dodopayments"

configure do
  set :dodo_client, Dodopayments::Client.new(
    bearer_token: ENV["DODO_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

리소스

GitHub Repository

소스 코드 보기 및 기여하기

API Reference

전체 API 설명서

Discord Community

도움말 받기 및 개발자와 연결

Report Issues

버그 신고 또는 기능 요청

지원

Ruby SDK에 대한 도움이 필요하신가요?

기여

기여를 환영합니다! 기여 가이드라인을 확인하여 시작하세요.
Last modified on May 28, 2026