メインコンテンツへスキップ
PHP SDKは、Dodo PaymentsをPHPアプリケーションに統合するための堅牢で柔軟な方法を提供します。モダンなPHP標準に従ってPSR-4オートローディングで構築されており、広範なテストカバレッジと詳細なドキュメントを提供します。

インストール

Composer を使用して SDK をインストールします:
composer require "dodopayments/client 5.8.1"
SDK には PHP 8.1.0 以上と依存関係管理のための Composer が必要です。

クイックスタート

クライアントを初期化し、チェックアウトセッションを作成します:
<?php

use Dodopayments\Client;

$client = new Client(
  bearerToken: getenv('DODO_PAYMENTS_API_KEY') ?: 'My Bearer Token',
  environment: 'test_mode',
);

$checkoutSessionResponse = $client->checkoutSessions->create(
  productCart: [["productID" => "product_id", "quantity" => 1]]
);

var_dump($checkoutSessionResponse->session_id);
API キーは環境変数で安全に保管してください。コードベースやバージョン管理に絶対に公開しないでください。

コア機能

PSR-4 Compliant

最新の PHP 開発のための PHP Standards Recommendations に準拠しています

Modern PHP

型宣言と厳密な型を備えた PHP 8.1+ 向けに構築されています

Extensive Testing

信頼性と安定性のための包括的なテストカバレッジ

Exception Handling

異なるエラーシナリオに対する明確な例外タイプ

値オブジェクト

SDK は名前付きパラメータを使用してオプション引数を指定します。静的 with コンストラクタを使用して値オブジェクトを初期化できます:
<?php

use Dodopayments\Customers\AttachExistingCustomer;

// Recommended: Use static 'with' constructor with named parameters
$customer = AttachExistingCustomer::with(customerID: "customer_id");
ビルダーも代替パターンとして利用できます:
<?php

use Dodopayments\Customers\AttachExistingCustomer;

// Alternative: Use builder pattern
$customer = (new AttachExistingCustomer)->withCustomerID("customer_id");

設定

再試行設定

特定のエラーは短い指数バックオフでデフォルトで 2 回自動的に再試行されます。以下のエラーが自動再試行をトリガーします:
  • 接続エラー(ネットワーク接続の問題)
  • 408 Request Timeout
  • 409 Conflict
  • 429 Rate Limit
  • 500以上の内部エラー
  • タイムアウト
再試行の動作はグローバルまたはリクエストごとに構成できます:
<?php

use Dodopayments\Client;

// Configure default for all requests (disable retries)
$client = new Client(requestOptions: ['maxRetries' => 0]);

// Or, configure per-request
$result = $client->checkoutSessions->create(
  productCart: [["productID" => "product_id", "quantity" => 1]],
  requestOptions: ['maxRetries' => 5],
);

共通操作

チェックアウトセッションを作成する

チェックアウトセッションを生成する:
$session = $client->checkoutSessions->create(
  productCart: [
    ["productID" => "prod_123", "quantity" => 1]
  ],
  returnUrl: "https://yourdomain.com/return"
);

header('Location: ' . $session->url);

顧客の管理

顧客情報を作成および取得する:
// Create a customer
$customer = $client->customers->create(
  email: "customer@example.com",
  name: "John Doe",
  metadata: [
    "user_id" => "12345"
  ]
);

// Retrieve customer
$customer = $client->customers->retrieve("cus_123");
echo "Customer: {$customer->name} ({$customer->email})";

サブスクリプションの処理

定期購読を作成および管理する:
// Create a subscription
$subscription = $client->subscriptions->create(
  customerID: "cus_123",
  productID: "prod_456",
  priceID: "price_789"
);

// Cancel subscription
$client->subscriptions->cancel($subscription->id);

ページネーション

ページネーションされたリスト応答を処理する:
$page = $client->payments->list();

var_dump($page);

// Fetch items from the current page
foreach ($page->getItems() as $item) {
  var_dump($item->brand_id);
}

// Auto-paginate: fetch items from all pages
foreach ($page->pagingEachItem() as $item) {
  var_dump($item->brand_id);
}

エラーハンドリング

ライブラリが API に接続できないか、成功ステータスコード(4xx または 5xx)以外を受け取ると APIException のサブクラスがスローされます:
<?php

use Dodopayments\Core\Exceptions\APIConnectionException;
use Dodopayments\Core\Exceptions\RateLimitException;
use Dodopayments\Core\Exceptions\APIStatusException;

try {
  $checkoutSessionResponse = $client->checkoutSessions->create(
    productCart: [["productID" => "product_id", "quantity" => 1]]
  );
} catch (APIConnectionException $e) {
  echo "The server could not be reached", PHP_EOL;
  var_dump($e->getPrevious());
} catch (RateLimitException $_) {
  echo "A 429 status code was received; we should back off a bit.", PHP_EOL;
} catch (APIStatusException $e) {
  echo "Another non-200-range status code was received", PHP_EOL;
  echo $e->getMessage();
}

エラータイプ

原因エラータイプ
HTTP 400BadRequestException
HTTP 401AuthenticationException
HTTP 403PermissionDeniedException
HTTP 404NotFoundException
HTTP 409ConflictException
HTTP 422UnprocessableEntityException
HTTP 429RateLimitException
HTTP >= 500InternalServerException
その他の HTTP エラーAPIStatusException
タイムアウトAPITimeoutException
ネットワークエラーAPIConnectionException
API コールを常に try-catch ブロックでラップして、潜在的なエラーを優雅に処理し、ユーザーに意味のあるフィードバックを提供してください。

高度な使用法

文書化されていないエンドポイント

文書化されていないエンドポイントにリクエストを送信する:
<?php

$response = $client->request(
  method: "post",
  path: '/undocumented/endpoint',
  query: ['dog' => 'woof'],
  headers: ['useful-header' => 'interesting-value'],
  body: ['hello' => 'world']
);

文書化されていないパラメータ

任意のエンドポイントに文書化されていないパラメータを送信したり、文書化されていない応答プロパティを読み取ったりする:
<?php

use Dodopayments\RequestOptions;

$checkoutSessionResponse = $client->checkoutSessions->create(
  productCart: [["productID" => "product_id", "quantity" => 1]],
  requestOptions: [
    'extraQueryParams' => ["my_query_parameter" => "value"],
    'extraBodyParams' => ["my_body_parameter" => "value"],
    'extraHeaders' => ["my-header" => "value"],
  ],
);
同じ名前の extra* パラメータは文書化されたパラメータを上書きします。

フレームワーク統合

Laravel

Laravel アプリケーション向けにサービスを作成する:
<?php

namespace App\Services;

use Dodopayments\Client;

class PaymentService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client(
            bearerToken: config('services.dodo.api_key')
        );
    }

    public function createCheckout(array $items)
    {
        return $this->client->checkoutSessions->create(
            productCart: $items,
            returnUrl: route('checkout.return')
        );
    }
}
config/services.php に設定を追加:
'dodo' => [
    'api_key' => env('DODO_API_KEY'),
    'environment' => env('DODO_ENVIRONMENT', 'sandbox')
],

Symfony

Symfony でサービスを作成する:
<?php

namespace App\Service;

use Dodopayments\Client;

class DodoPaymentService
{
    private Client $client;

    public function __construct(string $apiKey)
    {
        $this->client = new Client(bearerToken: $apiKey);
    }

    public function createPayment(int $amount, string $currency, string $customerId): object
    {
        return $this->client->payments->create(
            amount: $amount,
            currency: $currency,
            customerID: $customerId
        );
    }
}
config/services.yaml に登録:
services:
  App\Service\DodoPaymentService:
    arguments:
      $apiKey: "%env(DODO_API_KEY)%"

リソース

サポート

PHP SDK に関するサポートが必要ですか?

コントリビューション

ご協力を歓迎します! はじめるには contributing guidelines をご確認ください。