메인 콘텐츠로 건너뛰기
PHP SDK는 Dodo Payments를 PHP 애플리케이션에 통합하는 강력하고 유연한 방법을 제공합니다. PSR-4 자동 로딩을 따르는 현대 PHP 표준에 따라 구축되었으며, 광범위한 테스트 커버리지와 상세한 문서를 제공합니다.

설치

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 표준 권고(PSR)를 따릅니다

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 요청 시간 초과
  • 409 충돌
  • 429 요율 제한
  • 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에 도움이 필요하신가요?

기여

기여를 환영합니다! 시작하려면 기여 지침을 확인하세요.