> ## 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.

# PHP

> Dodo PaymentsをPHPアプリケーションに統合するためのモダンなPSR-4準拠のSDK

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

## インストール

Composer を使用して SDK をインストールします:

```bash theme={null}
composer require "dodopayments/client 6.7.1"
```

<Info>
  SDK には PHP 8.1.0 以上と依存関係管理のための Composer が必要です。
</Info>

## クイックスタート

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

```php theme={null}
<?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);
```

<Warning>
  API キーは環境変数で安全に保管してください。コードベースやバージョン管理に絶対に公開しないでください。
</Warning>

## コア機能

<CardGroup cols={2}>
  <Card title="PSR-4 Compliant" icon="check">
    最新の PHP 開発のための PHP Standards Recommendations に準拠しています
  </Card>

  <Card title="Modern PHP" icon="php">
    型宣言と厳密な型を備えた PHP 8.1+ 向けに構築されています
  </Card>

  <Card title="Extensive Testing" icon="vial">
    信頼性と安定性のための包括的なテストカバレッジ
  </Card>

  <Card title="Exception Handling" icon="shield-check">
    異なるエラーシナリオに対する明確な例外タイプ
  </Card>
</CardGroup>

## 値オブジェクト

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

```php theme={null}
<?php

use Dodopayments\Customers\AttachExistingCustomer;

// Recommended: Use static 'with' constructor with named parameters
$customer = AttachExistingCustomer::with(customerID: "customer_id");
```

ビルダーも代替パターンとして利用できます:

```php theme={null}
<?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 theme={null}
<?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],
);
```

## 共通操作

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

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

```php theme={null}
$session = $client->checkoutSessions->create(
  productCart: [
    ["productID" => "prod_123", "quantity" => 1]
  ],
  returnUrl: "https://yourdomain.com/return"
);

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

### 顧客の管理

顧客情報を作成および取得する:

```php theme={null}
// 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})";
```

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

定期購読を作成および管理する:

```php theme={null}
use Dodopayments\Customers\AttachExistingCustomer;
use Dodopayments\Payments\BillingAddress;

// Create a subscription
$subscription = $client->subscriptions->create(
  billing: BillingAddress::with(
    country: 'US',
    city: 'San Francisco',
    state: 'CA',
    street: '1 Market St',
    zipcode: '94105',
  ),
  customer: AttachExistingCustomer::with(customerID: 'cus_123'),
  productID: 'pdt_456',
  quantity: 1,
);

// Charge an on-demand subscription
// productPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
$charge = $client->subscriptions->charge(
  $subscription->subscription_id,
  productPrice: 2500,
);
```

<Info>
  `billing` は少なくとも2文字のISO `country` コードが必要です。既存の顧客を接続するには `AttachExistingCustomer::with(customerID: '...')` を、または作成するには `NewCustomer::with(email: '...', name: '...')` を渡します。`productPrice` は最小単位の通貨です。
</Info>

## ページネーション

ページネーションされたリストレスポンスを扱う：

```php theme={null}
$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 theme={null}
<?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 400    | `BadRequestException`          |
| HTTP 401    | `AuthenticationException`      |
| HTTP 403    | `PermissionDeniedException`    |
| HTTP 404    | `NotFoundException`            |
| HTTP 409    | `ConflictException`            |
| HTTP 422    | `UnprocessableEntityException` |
| HTTP 429    | `RateLimitException`           |
| HTTP >= 500 | `InternalServerException`      |
| その他のHTTPエラー | `APIStatusException`           |
| タイムアウト      | `APITimeoutException`          |
| ネットワークエラー   | `APIConnectionException`       |

<Tip>
  潜在的なエラーを優雅に処理し、ユーザーに意味のあるフィードバックを提供するために、常にtry-catchブロックでAPI呼び出しをラップしてください。
</Tip>

## 高度な使用法

### 非公開のエンドポイント

非公開のエンドポイントにリクエストを送信する：

```php theme={null}
<?php

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

### 非公開のパラメータ

どのエンドポイントにも非公開のパラメータを送信する、または非公開のレスポンスプロパティを読む：

```php theme={null}
<?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"],
  ],
);
```

<Note>
  同じ名前の `extra*` パラメータが、ドキュメント化されたパラメータを上書きします。
</Note>

## フレームワーク統合

### Laravel

Laravelアプリケーション向けのサービスを作成する：

```php theme={null}
<?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` に設定を追加する：

```php theme={null}
'dodo' => [
    'api_key' => env('DODO_API_KEY'),
    'environment' => env('DODO_ENVIRONMENT', 'sandbox')
],
```

### Symfony

Symfonyでサービスを作成する：

```php theme={null}
<?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` に登録する：

```yaml theme={null}
services:
  App\Service\DodoPaymentService:
    arguments:
      $apiKey: "%env(DODO_API_KEY)%"
```

## リソース

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-php">
    ソースコードを表示し、コントリビュートする
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    完全なAPIドキュメント
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    開発者とつながり、サポートを得る
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-php/issues">
    バグを報告するか、機能をリクエストする
  </Card>
</CardGroup>

## サポート

PHP SDKに関するヘルプが必要ですか？

* **Discord**: リアルタイムサポートのために[コミュニティサーバー](https://discord.gg/bYqAp4ayYh)に参加してください
* **Email**: [support@dodopayments.com](mailto:support@dodopayments.com) にご連絡ください
* **GitHub**: [リポジトリ](https://github.com/dodopayments/dodopayments-php)で問題をオープンしてください

## 貢献

貢献を歓迎します！始めるには[ガイドライン](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md)を確認してください。
