SDKs

Go SDK

The official Go library for BuyProxy: generate residential, mobile, ISP and datacenter proxies, check bandwidth, buy it from your wallet (topped up by card or crypto), and run a reseller business. Go 1.21+, standard library only. Every call takes a context.Context; the client is safe for concurrent use.

  • Standard library only — no transitive dependencies

  • context.Context on every call; safe for concurrent use

  • errors.Is(err, buyproxy.ErrInsufficientBandwidth) and friends

  • Proxy.HTTPClient() returns an *http.Client already routed through the proxy

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

Installation

bash
go get github.com/DishantSinghDev2/buyproxy-go

Go 1.21+. Standard library only.

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.

go
// 1. Environment variable (recommended)
client := buyproxy.New()

// 2. Explicit key, e.g. from a secrets manager
client = buyproxy.New(buyproxy.WithAPIKey(secret))

// 3. Which kind of key is it?
fmt.Println(client.KeyKind()) // "personal" | "reseller" | ""
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

go
package main

import (
	"context"
	"fmt"
	"io"
	"log"

	buyproxy "github.com/DishantSinghDev2/buyproxy-go"
)

func main() {
	ctx := context.Background()
	client := buyproxy.New() // reads BUYPROXY_API_KEY — or buyproxy.WithAPIKey("bp_key_…")

	plans, err := client.Plans.List(ctx)
	if err != nil || len(plans) == 0 {
		log.Fatal("no plans yet, buy bandwidth from your wallet first: ", err)
	}

	res, err := client.Plans.Generate(ctx, plans[0].ID, &buyproxy.GenerateParams{Country: "US", Count: 5})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := res.Proxies[0].HTTPClient().Get("https://api.ipify.org")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	ip, _ := io.ReadAll(resp.Body)
	fmt.Println("exit IP:", string(ip))
}

Set StickyMinutes: 10 for a sticky session: on Premium Residential it sets the length (3 minutes to 24 hours), and on Core Residential it turns sticky on. For SOCKS5, set Protocol: buyproxy.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 (Premium Residential). Not together with city
citystringCity, where the product supports it (Premium Residential). Not together with state
stickyMinutesintegerSticky session: on Premium Residential it sets the length (3 minutes to 24 hours), and on Core Residential it turns sticky on. Omit for a fresh IP on every request. The maximum is plan.generate.maxStickyMinutes; 0 there means the product has no sticky sessions

Send a state or a city, not both: a city already implies its state, and a call with both gets a 400. The SDKs have no asn field yet, so target a network by ASN (Premium Residential) through the REST API; see Geo-targeting. No plan offers ISP-by-name targeting.

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

go
// Country on every plan. Premium Residential plans also take a city or a state, not both (see plan.Generate.Targeting)
client.Plans.Generate(ctx, plan.ID, &buyproxy.GenerateParams{Country: "US", City: "Los Angeles"})
client.Plans.Generate(ctx, plan.ID, &buyproxy.GenerateParams{Country: "US", State: "California"})

// Sticky session: 30 minutes on Premium Residential (max is plan.Generate.MaxStickyMinutes); on Core Residential it turns sticky on
client.Plans.Generate(ctx, plan.ID, &buyproxy.GenerateParams{Country: "DE", StickyMinutes: 30})

// SOCKS5 instead of HTTP
client.Plans.Generate(ctx, plan.ID, &buyproxy.GenerateParams{Protocol: buyproxy.SOCKS5, Count: 10})

// Bulk: up to 1000 lines per call
res, _ := client.Plans.Generate(ctx, plan.ID, &buyproxy.GenerateParams{Count: 1000})
os.WriteFile("proxies.txt", []byte(strings.Join(res.Lines, "\n")), 0o600)

Every bandwidth purchase 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 GBState, city and ASN targeting, and sticky sessions with a length you set
ispISP Rotating1 GBRotating ISP-registered IPs on datacenter infrastructure (currently US only)
mobileMobile Proxies1 GBReal carrier IPs for mobile-only targets
ipv4Datacenter IPv41 GBWorkloads compatible with datacenter IPv4 network addresses (currently US only)
ipv6IPv6 Proxies1 GBWorkloads that support IPv6 addressing and require an IPv6-compatible connection (currently US only)

Money goes into your wallet by deposit: $5 minimum (minTopupCents in the catalog), $2,000 maximum per deposit. Bandwidth is then bought from the wallet in whole GB, from the product's min order (minGb). Orders 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.

net/http

go
proxy := res.Proxies[0]

client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxy.URL())}}
// or simply: client := proxy.HTTPClient()

Colly

go
c := colly.NewCollector()
c.SetProxyFunc(http.ProxyURL(res.Proxies[0].URL()))

chromedp / Rod

go
opts := append(chromedp.DefaultExecAllocatorOptions[:],
	chromedp.ProxyServer(res.Proxies[0].URL().Host)) // add auth via a fetch.AuthRequired handler

curl & shell

go
fmt.Println(res.Proxies[0].Curl())  // ready-to-run curl command
fmt.Println(res.Proxies[0].Env())   // HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, …

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 that's still being added (pending). The wallet call returns your wallet balance in cents and its recent activity.

go
catalog, _ := client.Products.List(ctx)       // product keys & live prices — no API key needed
account, _ := client.Account.Get(ctx)         // email, plan, lifetime GB
balances, _ := client.Balances.List(ctx)      // spendable GB per product (+ GB still arriving)
plans, _ := client.Plans.List(ctx)            // plan ids and what each can generate
history, _ := client.Transactions.List(ctx, 20)

Buying bandwidth

Every account has one USD wallet. You add money to it, then buy from it.

  1. Add money with the wallet top-up call (POST /v1/wallet/topup with method card or crypto and amountCents, $5 minimum, $2,000 maximum per deposit). It returns a hosted payment URL (payUrl for card, processed by Stripe Checkout; url for a crypto invoice) and a transaction id.
  2. Pay at that URL, or send your user there.
  3. Poll the transaction (or use the SDK's wait helper) until status is succeeded. The money is in your wallet from that point. Crypto payments are checked live on every poll, so they settle even if a webhook is delayed.
  4. Buy with the wallet purchase call (POST /v1/wallet/purchase): kind: "gb" with productKey and gb for bandwidth, "scraper" for Scraper API credit, or "dedicated" for dedicated and ISP Unlimited rentals (check the price in the dashboard first). It is charged to the wallet and delivered at once, so the GB is on balances straight away. Attach an idempotency key so a repeated purchase is charged once.

If the wallet is short, the purchase fails with 402 and the body carries shortfallCents; add at least that much (and at least $5; one deposit can be at most $2,000) and buy again.

Plans are subscriptions billed monthly or yearly by card; crypto can only add money to the wallet. If the account already has a subscription, the plan 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.

The per-product top-up calls of the 1.0.x SDKs (card or crypto top-ups for a product, and pool top-ups) were retired on 9 November 2026. In 1.1.0 and later they fail straight away with a 410 error that names the wallet call to use. On 1.0.x they reach the API, which answers 410 and names the wallet call too.

go
// 1. Add $15 to your wallet by card (buyproxy.PayByCrypto for a crypto invoice)
topup, _ := client.Wallet.Topup(ctx, buyproxy.PayByCard, 1500)
fmt.Println(topup.CheckoutURL())                                // open it in a browser
client.Transactions.Wait(ctx, topup.TransactionID, 3*time.Second) // the money is in the wallet once it says "succeeded"

// 2. Buy 10 GB of Core Residential from the wallet: charged and delivered at once
order, _ := client.Wallet.Purchase(ctx, buyproxy.BuyGB(buyproxy.ProductResidential, 10).WithIdempotencyKey("order-1042"))
fmt.Println(order.Summary, order.BalanceCents) // 10 GB Core Residential 510

// Scraper API credit and dedicated rentals come out of the same wallet
client.Wallet.Purchase(ctx, buyproxy.BuyScraperCredit(500))
client.Wallet.Purchase(ctx, buyproxy.RentDedicated(buyproxy.DedicatedIPv4, "USA", 30, 5))

wallet, _ := client.Wallet.Get(ctx)
fmt.Println(wallet.BalanceCents)

// Plans are card subscriptions, monthly or yearly
client.Topup.Card(ctx, buyproxy.PlanCardParams(buyproxy.PlanPro, buyproxy.Yearly))

Wallet methods need v1.1.0 or later. From v1.1.0 the retired v1.0.x top-ups fail before any request with an error matching errors.Is(err, buyproxy.ErrRetired).

Card payments are processed by Stripe and crypto payments by an invoice page; both add money to your wallet ($5 minimum, $2,000 maximum per deposit). Subscriptions are billed by card and can be managed or cancelled from Dashboard → Subscriptions → Manage subscription.

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 from your wallet (POST /v1/pool/purchase). Add money to the wallet first, by card or crypto. Pool GB is priced like any bandwidth purchase (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.

go
reseller := buyproxy.New(buyproxy.WithAPIKey("bp_live_…"))

reseller.Reseller.Pool.Purchase(ctx, buyproxy.PoolPurchaseParams{ProductKey: buyproxy.ProductResidential, GB: 500}) // from your wallet
customer, _ := reseller.Reseller.Customers.Create(ctx, "Acme Inc") // isolated sub-account

reseller.Reseller.Customers.Allocate(ctx, customer.Username, buyproxy.AllocateParams{
	ProductKey: buyproxy.ProductResidential, GB: 20, IdempotencyKey: "order-1042", // safe to retry
})

detail, _ := reseller.Reseller.Customers.Get(ctx, customer.Username)
res, _ := reseller.Reseller.Customers.Generate(ctx, customer.Username, buyproxy.CustomerGenerateParams{
	PlanID: detail.Plans[0].ID, GenerateParams: buyproxy.GenerateParams{Country: "DE"},
})

reseller.Reseller.Customers.Update(ctx, customer.Username, buyproxy.CustomerUpdate{Status: buyproxy.CustomerSuspended})

Calls that move money or GB accept an idempotency key, sent as the Idempotency-Key header:

  • Wallet purchases and pool purchases (POST /v1/wallet/purchase, POST /v1/pool/purchase). If a purchase times out, send it again with the same key and you are charged once. Keys may be up to 128 characters.
  • Allocating bandwidth to a customer. Send the same key twice and the second call moves nothing and returns alreadyApplied: true with the same result. Keys may be up to 200 characters.

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.

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.

HTTPCheck withMeaning
400errors.Is(err, buyproxy.ErrValidation)A parameter was missing or invalid
401errors.Is(err, buyproxy.ErrAuthentication)Missing or invalid API key (also returned locally when no key is set)
402errors.Is(err, buyproxy.ErrInsufficientBandwidth)Empty reseller pool, a plan with no GB left, or a wallet that can't cover a purchase (the body carries shortfallCents)
403errors.Is(err, buyproxy.ErrForbidden)Suspended account/customer, or the plan doesn't include this endpoint
404errors.Is(err, buyproxy.ErrNotFound)Plan, customer or transaction not found on this account
409apiErr.Status == 409 (read it with errors.As)The purchase's idempotency key is in use: the first request with it is still running (repeat later with the same key), or it ended without a purchase (send a new key)
410errors.Is(err, buyproxy.ErrRetired) from v1.1.0; apiErr.Status == 410 on v1.0.0A retired call, such as a 1.0.x bandwidth top-up. v1.1.0 raises it locally without a request; on v1.0.0 the API returns it. The message names the wallet call to use
422apiErr.Status == 422The idempotency key was already used for a different purchase. Send a new key for a new order
429errors.Is(err, buyproxy.ErrRateLimited)Over 60 requests/minute, or a sign-up or code limit. APIError.RetryAfter is the wait the API asked for, capped at 30 s, or zero if it gave none
5xxerrors.Is(err, buyproxy.ErrServer)BuyProxy is temporarily unavailable
—*buyproxy.ConnectionErrorNo response (DNS, reset, offline); context errors are returned as-is
go
_, err := client.Plans.Generate(ctx, planID, nil)

switch {
case errors.Is(err, buyproxy.ErrInsufficientBandwidth):
	log.Println("Out of GB: buy more from your wallet")
case errors.Is(err, buyproxy.ErrRateLimited):
	wait := 5 * time.Second // used when the API sends no Retry-After
	var apiErr *buyproxy.APIError
	if errors.As(err, &apiErr) && apiErr.RetryAfter > 0 {
		wait = apiErr.RetryAfter
	}
	log.Printf("Slow down; retry in %s", wait)
case errors.Is(err, buyproxy.ErrAuthentication):
	log.Println("Check your API key")
}

Non-2xx responses are *buyproxy.APIError (with Status, Message, Body); network failures are *buyproxy.ConnectionError.

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 when there is none.
  • Reads (GET) are also retried on 502/503/504 and on network failures.
  • Writes are not retried on server errors, because a repeated write could move money or GB twice. An allocation is retried only when you attach an idempotency key (see below).
  • Wallet and pool purchases are never retried after a server error or a dropped connection (a 429 is still retried, which is safe because nothing was processed). Attach an idempotency key and repeat the call yourself, and you are charged once.
  • A 502 on a purchase, with an error message, is final: delivery failed and the money went back to your wallet (the message says if the refund needs checking), so use a new key if you still want to buy.
  • A 503 on a purchase means nothing was delivered. Usually your wallet wasn't charged either, so repeat the purchase with the same key. If the message says the money is back in your wallet, that key is used up, so use a new one. If it says the purchase couldn't be confirmed, wait about 10 minutes, then repeat it with the same key.
  • 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, counted in a fixed 60-second window that starts with your first request. Batch with count (up to 1000 lines per call) rather than looping over single-proxy calls.

Configuration

go
client := buyproxy.New(
	buyproxy.WithAPIKey("bp_key_…"),            // default: $BUYPROXY_API_KEY
	buyproxy.WithBaseURL("https://www.buyproxy.org"),
	buyproxy.WithHTTPClient(&http.Client{Timeout: 10 * time.Second}),
	buyproxy.WithMaxRetries(2),                  // 429s always; 5xx only for safe requests
)

Concurrency

go
// The client is safe for concurrent use (mind the 60 requests/minute limit)
g, ctx := errgroup.WithContext(ctx)
for _, p := range plans {
	p := p
	g.Go(func() error {
		_, err := client.Plans.Generate(ctx, p.ID, &buyproxy.GenerateParams{Count: 10})
		return err
	})
}
err := g.Wait()

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.

go
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprint(w, `{"lines":["u:p@gw.buyproxy.org:6969"]}`)
}))
defer srv.Close()

client := buyproxy.New(buyproxy.WithAPIKey("bp_key_test"), buyproxy.WithBaseURL(srv.URL))
res, _ := client.Plans.Generate(ctx, "plan_1", nil)
// res.Proxies[0].Host == "gw.buyproxy.org"

API reference

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

CapabilityCall
Catalog & pricesclient.Products.List(ctx)
Accountclient.Account.Get(ctx)
Spendable GB per productclient.Balances.List(ctx)
Plansclient.Plans.List(ctx)
Generate proxiesclient.Plans.Generate(ctx, planID, params)
Walletclient.Wallet.Get(ctx) · .Topup(ctx, method, amountCents) · .Purchase(ctx, params)
Plan subscription (card)client.Topup.Card(ctx, buyproxy.PlanCardParams(...))
Paymentsclient.Transactions.List/Get/Wait
Create an accountclient.Auth.Signup/VerifyOTP/ResendOTP
Reseller summaryclient.Reseller.Me(ctx)
Customersclient.Reseller.Customers.List/Create/Get/Update/Usage/Allocate/Generate
Reseller poolclient.Reseller.Pool.Get(ctx) · .Purchase(ctx, params)

Notes

  • Non-2xx responses are *buyproxy.APIError with Status, Message and Body; use errors.As to read them.

  • Proxy.HTTPClient() returns an *http.Client already routed through the proxy — HTTP and SOCKS5.

  • Zero third-party dependencies, so there is nothing to audit but this module.

Developing the SDK

bash
go vet ./... && go test -race ./...

Something wrong or missing on this page?

Suggest edits