SDK C# menyediakan akses yang nyaman ke Dodo Payments REST API dari aplikasi yang ditulis dalam C#. Ini menampilkan API berbasis Task async dengan pengetikan yang kuat.
Instalasi
Pasang SDK menggunakan .NET CLI:
dotnet add package DodoPayments.Client
SDK ini memerlukan .NET Standard 2.0 atau yang lebih baru. Ini bekerja dengan ASP.NET Core, aplikasi Konsol, dan jenis proyek .NET lainnya.
Memulai Cepat
Inisialisasi klien dan buat sesi checkout:
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 );
Selalu simpan kunci API Anda dengan aman menggunakan variabel lingkungan, user secrets, atau Azure Key Vault. Jangan pernah menyematkannya langsung ke kode sumber atau mengkomitnya ke pengontrol versi.
Fitur Utama
Async/Await API berbasis Task async penuh untuk operasi tanpa blok
Strong Typing Keamanan tipe menyeluruh dengan nullable reference types
Dependency Injection Dukungan kelas satu untuk dependency injection .NET
Configuration Konfigurasi sederhana melalui variabel lingkungan atau appsettings.json
Konfigurasi
Variabel Lingkungan
Konfigurasikan menggunakan variabel lingkungan:
DODO_PAYMENTS_API_KEY = your_api_key_here
// Automatically reads from environment variables
DodoPaymentsClient client = new ();
Lihat tabel ini untuk opsi yang tersedia:
Properti Variabel lingkungan Wajib Nilai bawaan BearerTokenDODO_PAYMENTS_API_KEYtrue - WebhookKeyDODO_PAYMENTS_WEBHOOK_KEYfalse - BaseUrlDODO_PAYMENTS_BASE_URLtrue "https://live.dodopayments.com"
Konfigurasi Manual
Konfigurasikan secara manual dengan token bearer:
DodoPaymentsClient client = new () { BearerToken = "My Bearer Token" };
Operasi Umum
Buat Sesi Checkout
Hasilkan sesi checkout:
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 } " );
Kelola Pelanggan
Buat dan ambil informasi pelanggan:
// 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 } )" );
Kelola Langganan
Buat dan kelola langganan berulang:
// 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 );
Paginasi
SDK mendefinisikan metode yang mengembalikan daftar hasil berpaginasi dengan cara mudah untuk mengakses hasil baik satu halaman pada satu waktu maupun item demi item di seluruh halaman.
Paginasi Otomatis
Untuk menelusuri semua hasil di seluruh halaman, gunakan metode Paginate:
using System ;
var page = await client . Payments . List ( parameters );
await foreach ( var item in page . Paginate ())
{
Console . WriteLine ( item );
}
Paginasi Manual
Untuk mengakses item halaman individual dan secara manual meminta halaman berikutnya:
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 ();
}
Integrasi ASP.NET Core
Registrasi Layanan
Daftarkan klien di 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 ();
Konfigurasi
Tambahkan konfigurasi di appsettings.json:
{
"DodoPayments" : {
"ApiKey" : "your_api_key_here"
}
}
Kontroler API
Buat kontroler menggunakan dependency injection:
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 );
Pola Lapisan Layanan
Buat layanan untuk logika bisnis:
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 ;
}
}
}
User Secrets (Pengembangan)
Untuk pengembangan, gunakan user secrets untuk menyimpan kunci API:
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"
Pengujian
Contoh uji unit menggunakan 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 );
}
}
Sumber Daya
Dukungan
Butuh bantuan dengan SDK C#?
Kontribusi
Kami menyambut kontribusi! Periksa panduan kontribusi untuk memulai.