C# SDK는 C#으로 작성된 애플리케이션에서 Dodo Payments REST API에 편리하게 액세스할 수 있도록 합니다. 강력한 타이핑과 비동기 Task 기반 API를 제공합니다.
Installation
다음 .NET CLI 명령으로 SDK를 설치하세요:
dotnet add package DodoPayments.Client
SDK는 .NET Standard 2.0 이상을 요구합니다. ASP.NET Core, 콘솔 애플리케이션 및 기타 .NET 프로젝트 형식과 함께 작동합니다.
Quick Start
클라이언트를 초기화하고 체크아웃 세션을 생성하세요:
using System;
using DodoPayments.Client;
using DodoPayments.Client.Models.CheckoutSessions;
// Configured using the DODO_PAYMENTS_API_KEY and DODO_PAYMENTS_BASE_URL environment variables
DodoPaymentsClient client = new();
CheckoutSessionCreateParams parameters = new()
{
ProductCart =
[
new()
{
ProductID = "product_id",
Quantity = 1,
},
],
};
var checkoutSessionResponse = await client.CheckoutSessions.Create(parameters);
Console.WriteLine(checkoutSessionResponse.SessionId);
API 키는 환경 변수, 사용자 비밀 또는 Azure Key Vault를 사용하여 언제나 안전하게 저장해야 합니다. 절대 소스 코드에 하드코딩하거나 버전 관리 시스템에 커밋하지 마세요.
Core Features
Async/Await
논블로킹 작업을 위한 완전한 비동기 Task 기반 API
Strong Typing
널 허용 참조 형식을 통한 포괄적인 타입 안전성
Dependency Injection
.NET 종속성 주입에 대한 우수한 지원
Configuration
환경 변수 또는 appsettings.json을 통한 간편한 구성
Configuration
Environment Variables
환경 변수를 사용하여 구성하세요:
DODO_PAYMENTS_API_KEY=your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new();
사용 가능한 옵션은 다음 표를 참고하세요:
| Property | Environment variable | Required | Default value |
|---|
BearerToken | DODO_PAYMENTS_API_KEY | true | - |
WebhookKey | DODO_PAYMENTS_WEBHOOK_KEY | false | - |
BaseUrl | DODO_PAYMENTS_BASE_URL | true | "https://live.dodopayments.com" |
Manual Configuration
베어러 토큰을 사용하여 수동으로 구성하세요:
DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };
Common Operations
Create a Checkout Session
체크아웃 세션을 생성하세요:
var parameters = new CheckoutSessionCreateParams
{
ProductCart =
[
new()
{
ProductID = "prod_123",
Quantity = 1
}
],
ReturnUrl = "https://yourdomain.com/return"
};
var session = await client.CheckoutSessions.Create(parameters);
Console.WriteLine($"Checkout URL: {session.Url}");
Manage Customers
고객 정보를 생성하고 검색하세요:
// Create a customer
var createParams = new CustomerCreateParams
{
Email = "customer@example.com",
Name = "John Doe",
Metadata = new Dictionary<string, string>
{
{ "user_id", "12345" }
}
};
var customer = await client.Customers.Create(createParams);
// Retrieve customer
var retrieved = await client.Customers.Retrieve("cus_123");
Console.WriteLine($"Customer: {retrieved.Name} ({retrieved.Email})");
Handle Subscriptions
정기 구독을 생성하고 관리하세요:
// Create a subscription
var subscriptionParams = new SubscriptionCreateParams
{
CustomerID = "cus_123",
ProductID = "prod_456",
PriceID = "price_789"
};
var subscription = await client.Subscriptions.Create(subscriptionParams);
// Cancel subscription
await client.Subscriptions.Cancel(subscription.Id);
SDK는 결과를 페이지로 나누어 반환하는 메서드를 정의하며, 각 페이지별로 또는 모든 페이지에서 항목별로 접근할 수 있는 편리한 방법을 제공합니다.
모든 페이지의 결과를 반복하려면 Paginate 메서드를 사용하세요:
using System;
var page = await client.Payments.List(parameters);
await foreach (var item in page.Paginate())
{
Console.WriteLine(item);
}
개별 페이지 항목에 접근하고 다음 페이지를 수동으로 요청하려면:
using System;
var page = await client.Payments.List();
while (true)
{
foreach (var item in page.Items)
{
Console.WriteLine(item);
}
if (!page.HasNext())
{
break;
}
page = await page.Next();
}
ASP.NET Core Integration
Service Registration
Program.cs에서 클라이언트를 등록하세요:
using DodoPayments.Client;
var builder = WebApplication.CreateBuilder(args);
// Register DodoPayments client
builder.Services.AddSingleton<DodoPaymentsClient>(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
return new DodoPaymentsClient
{
BearerToken = configuration["DodoPayments:ApiKey"]
};
});
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
Configuration
appsettings.json에 구성을 추가하세요:
{
"DodoPayments": {
"ApiKey": "your_api_key_here"
}
}
API Controller
의존성 주입을 사용하여 컨트롤러를 생성하세요:
using Microsoft.AspNetCore.Mvc;
using DodoPayments.Client;
using DodoPayments.Client.Models.CheckoutSessions;
[ApiController]
[Route("api/[controller]")]
public class PaymentsController : ControllerBase
{
private readonly DodoPaymentsClient _client;
private readonly ILogger<PaymentsController> _logger;
public PaymentsController(DodoPaymentsClient client, ILogger<PaymentsController> logger)
{
_client = client;
_logger = logger;
}
[HttpPost("checkout")]
public async Task<IActionResult> CreateCheckout([FromBody] CheckoutRequest request)
{
try
{
var parameters = new CheckoutSessionCreateParams
{
ProductCart = request.Items,
ReturnUrl = Url.Action("Return", "Checkout", null, Request.Scheme)
};
var session = await _client.CheckoutSessions.Create(parameters);
return Ok(new { checkoutUrl = session.Url });
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to create checkout");
return BadRequest(new { error = ex.Message });
}
}
}
public record CheckoutRequest(List<ProductCartItem> Items);
Service Layer Pattern
비즈니스 로직을 위한 서비스를 생성하세요:
public interface IPaymentService
{
Task<CheckoutSessionResponse> CreateCheckoutAsync(List<ProductCartItem> items);
Task<PaymentResponse> ProcessPaymentAsync(decimal amount, string currency, string customerId);
}
public class PaymentService : IPaymentService
{
private readonly DodoPaymentsClient _client;
private readonly ILogger<PaymentService> _logger;
public PaymentService(DodoPaymentsClient client, ILogger<PaymentService> logger)
{
_client = client;
_logger = logger;
}
public async Task<CheckoutSessionResponse> CreateCheckoutAsync(List<ProductCartItem> items)
{
var parameters = new CheckoutSessionCreateParams
{
ProductCart = items,
ReturnUrl = "https://yourdomain.com/return"
};
return await _client.CheckoutSessions.Create(parameters);
}
public async Task<PaymentResponse> ProcessPaymentAsync(
decimal amount,
string currency,
string customerId)
{
try
{
var parameters = new PaymentCreateParams
{
Amount = (long)(amount * 100), // Convert to cents
Currency = currency,
CustomerID = customerId
};
return await _client.Payments.Create(parameters);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to process payment");
throw;
}
}
}
사용자 비밀(개발)
개발 환경에서는 사용자 비밀을 사용하여 API 키를 저장하세요:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"
Testing
xUnit을 사용하는 예제 단위 테스트:
using Xunit;
using DodoPayments.Client;
using DodoPayments.Client.Models.CheckoutSessions;
public class PaymentServiceTests
{
private readonly DodoPaymentsClient _client;
public PaymentServiceTests()
{
_client = new DodoPaymentsClient
{
BearerToken = "test_key"
};
}
[Fact]
public async Task CreateCheckout_ShouldReturnSession()
{
// Arrange
var parameters = new CheckoutSessionCreateParams
{
ProductCart =
[
new()
{
ProductID = "prod_test",
Quantity = 1
}
]
};
// Act
var session = await _client.CheckoutSessions.Create(parameters);
// Assert
Assert.NotNull(session);
Assert.NotNull(session.SessionId);
}
}
Resources
Support
C# SDK에 도움이 필요하신가요?
Contributing
기여를 환영합니다! 시작하려면 기여 가이드라인을 확인하세요.