メインコンテンツへスキップ
Ruby SDKは、Dodo PaymentsをRubyアプリケーションに統合するためのシンプルで直感的な方法を提供します。Rubyの慣習とベストプラクティスに従い、包括的なエラーハンドリング、ページネーション、およびミドルウェアサポートを提供します。

インストール

Gemfileにgemを追加します:
Gemfile
gem "dodopayments", "~> 1.61.5"
最新の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の慣習

Rubyの命名慣習とイディオムパターンに従います

エレガントな構文

Ruby開発者にとって自然に感じられるクリーンで読みやすいAPI

自動ページネーション

リストレスポンス用の組み込み自動ページイテレータ

型安全性

強化された型安全性のためのオプションの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: 0}],
  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: 0}],
  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.url

顧客の管理

顧客情報を作成および取得します:
# Create a customer
customer = dodo_payments.customers.create(
  email: "[email protected]",
  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(
  customer_id: "cus_123",
  product_id: "prod_456",
  price_id: "price_789"
)

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

# Cancel subscription
dodo_payments.subscriptions.cancel(subscription.id)

ページネーション

自動ページネーション

すべてのページを自動的にイテレートします:
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: 0}]
  )
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::CheckoutSessionRequest::ProductCart.new(
      product_id: "product_id",
      quantity: 0
    )
  ]
)

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

# You can also splat a full Params class
params = Dodopayments::CheckoutSessionCreateParams.new(
  product_cart: [
    Dodopayments::CheckoutSessionRequest::ProductCart.new(
      product_id: "product_id",
      quantity: 0
    )
  ]
)
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: 0}],
  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統合

イニシャライザの作成

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

コントローラー統合

Railsコントローラーで使用します:
# app/controllers/checkouts_controller.rb
class CheckoutsController < ApplicationController
  def create
    service = PaymentService.new
    session = service.create_checkout(checkout_params[:items])
    
    redirect_to session.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統合

Sinatraアプリケーションで使用します:
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.url }.to_json
  rescue Dodopayments::Errors::APIError => e
    status 400
    { error: e.message }.to_json
  end
end

リソース

サポート

Ruby SDKに関して助けが必要ですか?

貢献

貢献を歓迎します!始めるための貢献ガイドラインを確認してください。