Skip to content

odinsoft-lab/polar.net

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

32 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PolarNet

NuGet .NET License Downloads API Coverage

Thin C# client library for Polar.sh API - Modern billing infrastructure for developers.

πŸš€ v1.1.2 - Now with Payments, Refunds, and Webhook management!

Supported frameworks: .NET Standard 2.0, .NET Standard 2.1, .NET 8, .NET 9

πŸ“‹ Features

  • βœ… Core Payment Processing - Checkout sessions, orders, payments, and refunds
  • βœ… Subscription Management - Full subscription lifecycle with customer state tracking
  • βœ… Webhook Infrastructure - Complete webhook endpoint management with signature verification
  • βœ… Customer Management - CRUD operations with state and meter usage tracking
  • ⚠️ Products & Benefits - Read-only access (full CRUD coming in v1.2.0)
  • πŸ”œ Coming Soon - Discounts, License Keys, Files, OAuth2/OIDC authentication

Project structure

polar.net/
β”œβ”€β”€ src/                      # Class library (NuGet package)
β”‚   β”œβ”€β”€ Models/               # Typed API models
β”‚   β”‚   β”œβ”€β”€ Resources/        # API resources (Product, Order, etc.)
β”‚   β”‚   β”œβ”€β”€ Requests/         # Request DTOs
β”‚   β”‚   β”œβ”€β”€ Webhooks/         # Webhook event models
β”‚   β”‚   └── CustomerState/    # Customer state models
β”‚   β”œβ”€β”€ Services/             
β”‚   β”‚   β”œβ”€β”€ PolarClient/      # API endpoint implementations
β”‚   β”‚   └── Webhooks/         # Webhook handling services
β”‚   └── polar.net.csproj
β”œβ”€β”€ samples/
β”‚   β”œβ”€β”€ polar.sample/         # Console app demonstrating API calls
β”‚   └── polar.webhook/        # ASP.NET webhook receiver with event store
β”œβ”€β”€ tests/                    # xUnit tests with 90%+ coverage
β”œβ”€β”€ docs/                     
β”‚   β”œβ”€β”€ TASK.md              # Implementation status vs official API
β”‚   β”œβ”€β”€ ROADMAP.md           # Development roadmap
β”‚   └── releases/            # Release notes
└── README.md

πŸš€ Quick start

Install from NuGet

dotnet add package PolarNet --version 1.1.2

Or via Package Manager:

Install-Package PolarNet -Version 1.1.2

Build from source

git clone https://github.com/odinsoft-lab/polar.net.git
cd polar.net
dotnet restore
dotnet build -c Release

Run samples

# Console sample
cd samples/polar.sample
dotnet run

# Webhook receiver (ASP.NET)
cd samples/polar.webhook
dotnet run

Notes:

  • The samples read configuration from appsettings.json (no code edits required). Set your values in:
    • samples/polar.sample/appsettings.json
    • samples/polar.webhook/appsettings.json
  • Start the ASP.NET webhook sample from samples/polar.webhook with dotnet run.

Minimal config used by samples/tests:

{
	"PolarSettings": {
        "AccessToken": "<YOUR_SANDBOX_OAT>",
        "WebhookSecret": "<YOUR_WEBHOOK_SECRET>",
        "OrganizationId": "<YOUR_ORGANIZATION_ID>",
        "ProductId": "<YOUR_PRODUCT_ID>",
        "PriceId": "<YOUR_PRICE_ID>",
        "WebhookBaseUrl": "<YOUR_WEBHOOK_BASE_URL>",
        "SandboxApiUrl": "https://sandbox-api.polar.sh",
        "ProductionApiUrl": "https://api.polar.sh",
        "UseSandbox": true
	}
}

πŸ’» Using the library

Basic setup

using PolarNet;

var client = new PolarClient(new PolarClientOptions
{
    AccessToken = "<YOUR_ACCESS_TOKEN>",
    BaseUrl = "https://sandbox-api.polar.sh", // or production URL
    OrganizationId = "<YOUR_ORG_ID>"
});

// Get organization details
var org = await client.GetOrganizationAsync();
Console.WriteLine($"Organization: {org.Name}");

Example: Create checkout and process payment

// Create a checkout session
var checkout = await client.CreateCheckoutAsync(new CreateCheckoutRequest
{
    OrganizationId = client.Options.OrganizationId,
    ProductId = "product_123",
    PriceId = "price_456",
    SuccessUrl = "https://example.com/success",
    CustomerEmail = "[email protected]"
});

// Later, check payment status
var payments = await client.ListPaymentsAsync(new ListPaymentsRequest
{
    OrderId = checkout.OrderId
});

if (payments.Items.Any(p => p.Status == "succeeded"))
{
    Console.WriteLine("Payment successful!");
}

Example: Handle webhooks

// In your ASP.NET controller
[HttpPost("webhook")]
public async Task<IActionResult> HandleWebhook(
    [FromBody] string payload,
    [FromHeader(Name = "X-Polar-Signature")] string signature)
{
    var service = new PolarWebhookService("your_webhook_secret");
    
    if (!service.VerifySignature(payload, signature))
        return Unauthorized();
    
    var envelope = service.ParseEnvelope(payload);
    
    switch (envelope.Event)
    {
        case "order.created":
            var order = JsonSerializer.Deserialize<PolarOrder>(envelope.Data);
            // Process order...
            break;
        case "subscription.updated":
            var subscription = JsonSerializer.Deserialize<PolarSubscription>(envelope.Data);
            // Handle subscription change...
            break;
    }
    
    return Ok();
}

πŸ“Š API Implementation Status

βœ… Fully Implemented (8/22 endpoints)

  • Checkout - Create and retrieve custom checkout sessions
  • Customers - Full CRUD operations with state management
  • Subscriptions - Complete lifecycle management (create, list, get, cancel, revoke)
  • Orders - List and retrieve order details
  • Refunds - Create (full/partial), list, and retrieve refunds
  • Payments - List and retrieve payment details with filtering
  • Webhook Endpoints - Full CRUD + testing capabilities
  • Customer State - Track usage meters and granted benefits

⚠️ Partially Implemented (3/22 endpoints)

  • Products - Read-only (list, get) - Full CRUD in v1.2.0
  • Benefits - List only - Full management in v1.2.0
  • Organizations - Get only - Update operations in v1.3.0

πŸ”œ Coming Soon (11/22 endpoints)

  • v1.2.0 - Discounts, License Keys, Files, Product CRUD
  • v1.3.0 - OAuth2/OIDC, Customer Portal, Sessions
  • v1.4.0 - Metrics, Events, Meters, Custom Fields

For detailed implementation status, see docs/TASK.md.
For development roadmap, see docs/ROADMAP.md.

πŸ§ͺ Testing

Test cards for Sandbox

Stripe test cards for payment testing:

Card Number Scenario
4242 4242 4242 4242 Success
4000 0000 0000 0002 Failure
4000 0025 0000 3155 3D Secure authentication
4000 0000 0000 9995 Decline

Running tests

cd tests/PolarNet.Tests
dotnet test --logger "console;verbosity=detailed"

πŸ”§ Troubleshooting

Error Cause Solution
401 Unauthorized Invalid/expired token Verify token is valid for environment (sandbox/production)
404 Not Found Resource doesn't exist Check IDs exist in your environment
422 Unprocessable Entity Invalid request Verify required fields and data types
429 Too Many Requests Rate limit exceeded Implement retry with exponential backoff

βš™οΈ Configuration

Authentication

  • Organization Access Token (OAT) - Server-side operations
  • Customer Access Token - Customer-specific operations (coming in v1.3.0)
  • OAuth2/OIDC - Third-party integrations (coming in v1.3.0)

Environment URLs

  • Production: https://api.polar.sh
  • Sandbox: https://sandbox-api.polar.sh

Rate Limits

  • 300 requests/minute per organization
  • 1 request/second for license key validation

πŸ“š Documentation

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development setup

git clone https://github.com/odinsoft-lab/polar.net.git
cd polar.net
dotnet restore
dotnet build
dotnet test

πŸ‘₯ Team

Core Development Team

πŸ“ž Support

πŸ“„ License

MIT License - see LICENSE.md for details.


Built with ❀️ by the ODINSOFT Team

⭐ Star us on GitHub | πŸ“¦ NuGet Package | 🌐 Polar.sh

About

Thin C# client library for Polar API (https://docs.polar.sh/). Supports sandbox and production with simple, typed access.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published