BuyProxy logo
Log inSign up

SDKs

C# / .NET SDK

The official C# / .NET library for BuyProxy: generate residential, mobile, ISP and datacenter proxies, check bandwidth, buy more by card or crypto, and run a reseller business. .NET 6 and later (net6.0, net8.0). Async-first, nullable reference types enabled, no NuGet dependencies.

  • Async API with CancellationToken on every call

  • Immutable record models with nullable reference types

  • Automatic retries with back-off for rate limits and transient errors

  • ProxyEndpoint.CreateHttpClient() returns an HttpClient already routed through the proxy

Source, issues and releases: github.com/DishantSinghDev2/buyproxy-dotnet

Installation

bash
dotnet add package BuyProxy

.NET 6 and later (net6.0, net8.0). No NuGet dependencies.

Authentication

Create an API key under Dashboard → API keys — personal keys start bp_key_, reseller keys bp_live_. The SDK reads BUYPROXY_API_KEY from the environment automatically; you can also pass the key explicitly. A missing key fails immediately with an authentication error, without a network call.

csharp
// 1. Environment variable (recommended)
var bp = new BuyProxyClient();

// 2. Explicit key, e.g. from IConfiguration / Key Vault
var bp2 = new BuyProxyClient(new BuyProxyOptions { ApiKey = config["BuyProxy:ApiKey"] });

// 3. Which kind of key is it?
Console.WriteLine(bp.KeyKind); // "personal" | "reseller" | null
Never put an API key in client-side code, a mobile app, a public repository or a log line. Revoke a leaked key from the dashboard and create a new one.

Quick start

csharp
using BuyProxy;

var bp = new BuyProxyClient(Environment.GetEnvironmentVariable("BUYPROXY_API_KEY")!); // or new BuyProxyClient() — reads BUYPROXY_API_KEY

var plan = (await bp.Plans.ListAsync())[0];
var result = await bp.Plans.GenerateAsync(plan.Id, new GenerateParams { Country = "US", City = "Austin", Count = 5 });

Console.WriteLine(result.Proxies[0].Url); // http://user-country-us-city-austin:pass@gw.buyproxy.org:6969

Set StickyMinutes = 10 to keep the same IP for ten minutes, or Protocol = "socks5" for SOCKS5.

Generating proxies

Generation is free and instant — bandwidth is only consumed when traffic flows through a proxy. Every parameter is optional; omit one and the API's default applies. (Names follow each language's conventions, e.g. stickyMinutes / sticky_minutes / StickyMinutes.)

ParameterTypeWhat it does
protocol"http" \"socks5"Proxy protocol. Default http (which also carries HTTPS). Check plan.generate.protocols for what a product supports
countinteger 1–1000How many proxy lines to return. Default 1
countryISO 3166-1 alpha-2e.g. US, DE, JP. Omit for a worldwide IP
statestringState or region, where the product supports it
citystringCity, where the product supports it
ispstringNetwork / carrier, where the product supports it
stickyMinutesintegerKeep the same IP for this many minutes. Omit for a fresh IP on every request. The maximum is plan.generate.maxStickyMinutes; 0 there means the product has no sticky sessions

Each returned line is username:password@host:port with your targeting encoded in the username. Lines are on-demand and not persistent — generate fresh ones when you need them instead of storing them, because credentials can rotate when the pool moves.

csharp
// Country, state and city — what a plan supports is in plan.Generate.Targeting
await bp.Plans.GenerateAsync(plan.Id, new GenerateParams { Country = "US", State = "California", City = "Los Angeles" });

// Sticky session: keep one IP for 30 minutes (max is plan.Generate.MaxStickyMinutes)
await bp.Plans.GenerateAsync(plan.Id, new GenerateParams { Country = "DE", StickyMinutes = 30 });

// SOCKS5 instead of HTTP
await bp.Plans.GenerateAsync(plan.Id, new GenerateParams { Protocol = "socks5", Count = 10 });

// Bulk: up to 1000 lines per call
var result = await bp.Plans.GenerateAsync(plan.Id, new GenerateParams { Count = 1000 });
await File.WriteAllLinesAsync("proxies.txt", result.Lines);

Every top-up and allocation call takes a product key. Live prices come from the catalog call, so you never hard-code a rate.

KeyProductMin orderBest for
residentialCore Residential1 GBEveryday rotating residential IPs with country targeting
premiumPremium Residential2 GBCity-level targeting, sticky sessions and priority routing
ispISP Rotating1 GBDatacenter speed with ISP-grade trust
mobileMobile Proxies1 GBReal carrier IPs for mobile-only targets
ipv4Datacenter IPv41 GBFast, cheap per-GB datacenter traffic
ipv6IPv6 Proxies1 GBHuge address diversity at the lowest per-GB rate

Pay-as-you-go top-ups of 100 GB or more include a 10% volume bonus, and a single order is capped at 10,000 GB.

Using the proxies with your stack

Each generated proxy is a small object (host, port, username, password, protocol) with helpers that return exactly what common clients expect, so you never hand-build a proxy URL or worry about percent-encoding special characters in a password.

HttpClient

csharp
using var http = result.Proxies[0].CreateHttpClient();
Console.WriteLine(await http.GetStringAsync("https://api.ipify.org"));

ASP.NET Core / dependency injection

csharp
builder.Services.AddSingleton(_ => new BuyProxyClient(new BuyProxyOptions
{
    ApiKey = builder.Configuration["BuyProxy:ApiKey"],
}));

Playwright for .NET

csharp
var p = result.Proxies[0];
await using var browser = await playwright.Chromium.LaunchAsync(new()
{
    Proxy = new Microsoft.Playwright.Proxy { Server = p.Server, Username = p.Username, Password = p.Password },
});

curl & shell

csharp
foreach (var (k, v) in result.Proxies[0].Env()) Console.WriteLine($"export {k}='{v}'");

Account, balances & history

Read-only calls for building dashboards, alerts and pre-flight checks. balances is the one to watch: it shows spendable GB per product, including GB from a payment that's still being added (pending).

csharp
var catalog = await bp.Products.ListAsync();         // product keys & live prices — no API key needed
var account = await bp.Account.GetAsync();            // email, plan, lifetime GB
var balances = await bp.Balances.ListAsync();         // spendable GB per product (+ GB still arriving)
var plans = await bp.Plans.ListAsync();               // plan ids and what each can generate
var history = await bp.Transactions.ListAsync(limit: 20);

Buying bandwidth

  1. Call the top-up method — it returns a hosted payment URL and a transaction id. Card payments are processed by Stripe Checkout; crypto by an invoice page.
  2. Send your user (or yourself) to that URL to pay.
  3. Poll the transaction (or use the SDK's wait helper) until status is succeeded or failed. Crypto payments are checked live on every poll, so they settle even if a webhook is delayed.
  4. The GB shows up under balances within seconds — pendingGb while it's arriving, activeGb once it's live.

Plans are subscriptions billed monthly or yearly by card (crypto only covers pay-as-you-go top-ups). If the account already has a subscription, the call returns the subscription settings page as the URL and a null transaction id — switching plans is prorated there, and you can't accidentally subscribe twice.

csharp
// Buy 10 GB of Core Residential by card — send the customer to PayUrl
var checkout = await bp.Topup.CardAsync(CardCheckoutParams.Topup("residential", 10));
Console.WriteLine(checkout.PayUrl);

// Or subscribe to a plan (monthly or yearly)
await bp.Topup.CardAsync(CardCheckoutParams.Plan("pro", "year"));

// Crypto (pay-as-you-go top-ups only)
await bp.Topup.CryptoAsync("residential", 50);

// Wait for the payment to settle — GB appears on bp.Balances.ListAsync() right after
var tx = await bp.Transactions.WaitAsync(checkout.TransactionId!);
Console.WriteLine(tx.Status); // "succeeded"

Card payments are processed by Stripe; crypto top-ups are pay-as-you-go only. Subscriptions can be managed or cancelled from Dashboard → Billing.

Reseller API

The reseller API lets you build a proxy product on top of BuyProxy. The flow is always the same:

  1. Fund your pool — buy GB per product into your reseller pool by card or crypto. Pool GB is priced like a normal top-up (including the volume bonus), fixed at purchase time.
  2. Create a customer — an isolated sub-account with its own credentials and no bandwidth. Store the returned username.
  3. Allocate — move whole GB of one product from your pool onto that customer, with an idempotency key. The first allocation of a product creates the plan; later ones add to it.
  4. Generate — produce proxy lines for the customer from their plan id (found on the customer record), with all the usual targeting options.
  5. Monitor — read the customer's usage (remaining, used, total per plan, plus any GB still arriving) to bill or alert.
  6. Suspend / reactivate — a suspended customer can't generate new lines (403). Lines already handed out may keep working until they rotate, so stop distributing them at the same time. You can also rename a customer.

Allocated GB can't be moved back to the pool, so allocate what a customer has paid for.

csharp
var reseller = new BuyProxyClient("bp_live_…");

await reseller.Reseller.Pool.TopupCardAsync("residential", 500);                 // buy into your pool
var customer = await reseller.Reseller.Customers.CreateAsync("Acme Inc");        // isolated sub-account

await reseller.Reseller.Customers.AllocateAsync(customer.Username, "residential", 20, idempotencyKey: "order-1042");

var detail = await reseller.Reseller.Customers.GetAsync(customer.Username);
var result = await reseller.Reseller.Customers.GenerateAsync(customer.Username, detail.Plans[0].Id, new GenerateParams { Country = "DE" });

await reseller.Reseller.Customers.UpdateAsync(customer.Username, status: "suspended");

Allocating bandwidth to a customer moves real GB, so it accepts an idempotency key. Send the same key twice and the second call moves nothing and returns alreadyApplied: true with the same result — safe to retry after a timeout or crash.

Use a value you can derive again from your own data (an order id, an invoice number), not a random value created per attempt. Keys are scoped to your account and may be up to 200 characters.

Errors & retries

Every non-success response becomes a typed error carrying the HTTP status and the API's own message, so you can branch on the failure instead of parsing strings.

HTTPExceptionMeaning
400ValidationExceptionA parameter was missing or invalid
401AuthenticationExceptionMissing or invalid API key (also thrown locally when no key is set)
402InsufficientBandwidthExceptionEmpty reseller pool, or a plan with no GB left
403PermissionDeniedExceptionSuspended account/customer, or the plan doesn't include this endpoint
404NotFoundExceptionPlan, customer or transaction not found on this account
429RateLimitExceptionOver 60 requests/minute — has RetryAfterSeconds
5xxServerExceptionBuyProxy or an upstream provider is unavailable
—ConnectionExceptionNo response (DNS, reset, timeout, offline)
csharp
try
{
    await bp.Plans.GenerateAsync(planId);
}
catch (InsufficientBandwidthException)
{
    Console.WriteLine("Out of GB — top up first");
}
catch (RateLimitException e)
{
    Console.WriteLine($"Slow down; retry in {e.RetryAfterSeconds}s");
}
catch (AuthenticationException)
{
    Console.WriteLine("Check your API key");
}

Every exception derives from BuyProxyException and exposes Status and Body.

Every SDK retries for you, with the same rules:

  • Rate limits (`429`) are always retried, waiting for the Retry-After the API sends (capped at 30 s) or an exponential back-off with jitter.
  • Reads (GET) are also retried on 502/503/504 and on network failures.
  • Writes are not retried on server errors — a repeated checkout or allocation must never double-charge — unless you attach an idempotency key (see below), which makes the retry provably safe.
  • The default is 2 retries; set it to 0 to turn retries off. After the last attempt you get the typed error.

The API allows 60 requests per minute per key. Batch with count (up to 1000 lines per call) rather than looping over single-proxy calls.

Configuration

csharp
new BuyProxyClient(new BuyProxyOptions
{
    ApiKey = "bp_key_…",                    // default: BUYPROXY_API_KEY
    BaseUrl = "https://www.buyproxy.org",
    Timeout = TimeSpan.FromSeconds(30),
    MaxRetries = 2,                          // 429s always; 5xx only for safe requests
    HttpClient = httpClientFromFactory,      // bring your own HttpClient
});

Concurrency

csharp
// Thread-safe — register one instance and share it (mind the 60 requests/minute limit)
var results = await Task.WhenAll(plans.Select(p => bp.Plans.GenerateAsync(p.Id, new GenerateParams { Count = 10 })));

Testing your code

You don't need a real account or network to unit-test code that uses the SDK — inject a fake transport. This is how the SDK's own test suite works.

csharp
sealed class StubHandler : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct) =>
        Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("""{"lines":["u:p@gw.buyproxy.org:6969"]}""", Encoding.UTF8, "application/json"),
        });
}

var bp = new BuyProxyClient(new BuyProxyOptions { ApiKey = "bp_key_test", HttpClient = new HttpClient(new StubHandler()) });
Assert.Equal("gw.buyproxy.org", (await bp.Plans.GenerateAsync("plan_1")).Proxies[0].Host);

API reference

Every method maps one-to-one onto a documented REST endpoint.

CapabilityCall
Catalog & pricesbp.Products.ListAsync()
Accountbp.Account.GetAsync()
Spendable GB per productbp.Balances.ListAsync()
Plansbp.Plans.ListAsync()
Generate proxiesbp.Plans.GenerateAsync(planId, params)
Card checkoutbp.Topup.CardAsync(params)
Crypto checkoutbp.Topup.CryptoAsync(product, gb)
Paymentsbp.Transactions.ListAsync/GetAsync/WaitAsync
Create an accountbp.Auth.SignupAsync/VerifyOtpAsync/ResendOtpAsync
Reseller summarybp.Reseller.MeAsync()
Customersbp.Reseller.Customers.ListAsync/CreateAsync/GetAsync/UpdateAsync/UsageAsync/AllocateAsync/GenerateAsync
Reseller poolbp.Reseller.Pool.GetAsync/TopupCardAsync/TopupCryptoAsync

Notes

  • Every exception derives from BuyProxyException (with Status and Body). Cancel any call with a CancellationToken.

  • Pass an HttpClient from IHttpClientFactory via BuyProxyOptions.HttpClient to get pooling, Polly policies and logging.

  • ProxyEndpoint.CreateHttpClient() returns an HttpClient already routed through the proxy.

Developing the SDK

bash
dotnet build -c Release
dotnet test

Was this page helpful?