メインコンテンツへスキップ
PHP SDKは、Dodo PaymentsをPHPアプリケーションに統合するための堅牢で柔軟な方法を提供します。モダンなPHP標準に従ってPSR-4オートローディングで構築されており、広範なテストカバレッジと詳細なドキュメントを提供します。
Dodo Payments PHP APIライブラリは現在ベータ版です。ぜひお試しください!提案、バグレポート、機能リクエストは、issueを提出することでお知らせください。

インストール

Composerを使用してSDKをインストールします:
composer require "dodopayments/client:^3.5.0"
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準拠

モダンなPHP開発のためのPHP標準推奨に従っています

モダンPHP

型宣言と厳密な型を持つPHP 8.1+用に構築されています

広範なテスト

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

例外処理

異なるエラーシナリオのための明確な例外タイプ

値オブジェクト

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 リクエストタイムアウト
  • 409 競合
  • 429 レート制限
  • 500以上の内部エラー
  • タイムアウト
リトライ動作をグローバルまたはリクエストごとに設定します:
<?php

use Dodopayments\Client;
use Dodopayments\RequestOptions;

// Configure default for all requests (disable retries)
$client = new Client(maxRetries: 0);

// Or, configure per-request
$result = $client->checkoutSessions->create(
  productCart: [["productID" => "product_id", "quantity" => 1]],
  requestOptions: RequestOptions::with(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: "[email protected]",
  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: RequestOptions::with(
    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に関して助けが必要ですか?

貢献

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