> ## Documentation Index
> Fetch the complete documentation index at: https://dodopayments-mintlify-external-integration-datafast-autosen.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# C#

> Integrate Dodo Payments into your .NET applications with modern async/await support

The C# SDK provides convenient access to the Dodo Payments REST API from applications written in C#. It features an async Task-based API with strong typing and is currently in beta.

<Info>
  The C# SDK is currently in beta. We're actively working on improvements and welcome your feedback.
</Info>

## Installation

Install the SDK using the .NET CLI:

```bash theme={null}
dotnet add package DodoPayments.Client
```

<Info>
  The SDK requires .NET 8.0 or higher. It works with ASP.NET Core, Console applications, and other .NET project types.
</Info>

## Quick Start

Initialize the client and create a checkout session:

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

<Warning>
  Always store your API keys securely using environment variables, user secrets, or Azure Key Vault. Never hardcode them in your source code or commit them to version control.
</Warning>

## Core Features

<CardGroup cols={2}>
  <Card title="Async/Await" icon="bolt">
    Full async Task-based API for non-blocking operations
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Comprehensive type safety with nullable reference types
  </Card>

  <Card title="Dependency Injection" icon="layer-group">
    First-class support for .NET dependency injection
  </Card>

  <Card title="Configuration" icon="gear">
    Simple configuration via environment variables or appsettings.json
  </Card>
</CardGroup>

## Configuration

### Environment Variables

Configure using environment variables:

```bash .env theme={null}
DODO_PAYMENTS_API_KEY=your_api_key_here
```

```csharp theme={null}
// Automatically reads from environment variables
DodoPaymentsClient client = new();
```

### Manual Configuration

Configure manually with bearer token:

```csharp theme={null}
DodoPaymentsClient client = new() { BearerToken = "My Bearer Token" };
```

## Common Operations

### Create a Checkout Session

Generate a checkout session:

```csharp theme={null}
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 and retrieve customer information:

```csharp theme={null}
// 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 and manage recurring subscriptions:

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

## ASP.NET Core Integration

### Service Registration

Register the client in `Program.cs`:

```csharp Program.cs theme={null}
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

Add configuration in `appsettings.json`:

```json appsettings.json theme={null}
{
  "DodoPayments": {
    "ApiKey": "your_api_key_here"
  }
}
```

### API Controller

Create a controller using dependency injection:

```csharp theme={null}
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

Create a service for business logic:

```csharp theme={null}
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 (Development)

For development, use user secrets to store API keys:

```bash theme={null}
dotnet user-secrets init
dotnet user-secrets set "DodoPayments:ApiKey" "your_api_key_here"
```

## Testing

Example unit test using xUnit:

```csharp theme={null}
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

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-csharp">
    View source code and contribute
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Complete API documentation
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Get help and connect with developers
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-csharp/issues">
    Report bugs or request features
  </Card>
</CardGroup>

## Support

Need help with the C# SDK?

* **Discord**: Join our [community server](https://discord.gg/bYqAp4ayYh) for real-time support
* **Email**: Contact us at [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-csharp)

## Contributing

Since the SDK is in beta, your feedback and contributions are especially valuable! Check the [contributing guidelines](https://github.com/dodopayments/dodopayments-csharp/blob/main/CONTRIBUTING.md) to get started.
