HHego Buyer API Español OpenAPI

Buy digital products from your own system

Query the live catalog, pay from your USDT balance and get the delivery in the same response. One REST API plus webhook events.

Base URLhttps://api.hegodigitaldev.com/api/v1/buyer
It is only used on this page to fill in the examples. It is never stored or sent to any server. Still, avoid pasting it on shared machines.
curl -X POST https://api.hegodigitaldev.com/api/v1/buyer/orders \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -H "Idempotency-Key: 7f9c2e0a-51d4-4c1b-9a67-3e0d2b8a11f4" \
  -H "Content-Type: application/json" \
  -d '{"productId": 102, "quantity": 2, "expectedPriceUsdt": 7}'
201 CreatedPurchase and delivery arrive together
{
  "success": true,
  "orderId": 45012,
  "status": "completed",
  "productId": 102,
  "quantity": 2,
  "totalPriceUsdt": 7,
  "createdAt": 1767225600000,
  "delivery": {
    "items": [
      "maria.lopez@example.com:Pass#8842",
      "juan.perez@example.com:Pass#1937"
    ]
  },
  "balanceAfterUsdt": 143.25,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}

Quickstart#

Five steps take you from zero to your first automated purchase.

  1. Generate your API key

    In the Telegram bot open Profile → Developer API → Generate and accept the terms. The key starts with hg_live_ and is shown only once: store it in a secret manager.

    You can have one active key. You can generate it even before topping up.

  2. Top up your wallet

    API purchases are charged to your USDT wallet, the same one you use in the bot. Top up from the wallet section of the bot and check the balance:

    curl https://api.hegodigitaldev.com/api/v1/buyer/balance \
      -H "X-API-Key: hg_live_YOUR_API_KEY"
    200 OKResponse
    {
      "success": true,
      "balanceUsdt": 143.25,
      "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
    }
  3. Read the catalog

    Pick an id and note its priceUsdt. If requiresRecipient is true, you will need the Telegram user who will receive the product.

    To test: buy the TEST ITEM product, made to verify your integration without spending on a real product. The prices you see already include the API client discount when one is active.

    curl https://api.hegodigitaldev.com/api/v1/buyer/products \
      -H "X-API-Key: hg_live_YOUR_API_KEY"
    200 OKResponse
    {
      "success": true,
      "products": [
        {
          "id": 102,
          "name": "Netflix 1 Screen (30 days)",
          "description": "Single profile with PIN. Renewable.",
          "instructions": "Sign in with the email and password delivered. Do not change the password.",
          "priceUsdt": 3.5,
          "quantityTiers": [
            {
              "quantity": 5,
              "totalPriceUsdt": 15
            }
          ],
          "availableStock": 18,
          "requiresRecipient": false
        },
        {
          "id": 215,
          "name": "Telegram Premium 3 months",
          "description": "Direct activation on the account you specify.",
          "instructions": "",
          "priceUsdt": 14.9,
          "quantityTiers": [],
          "availableStock": "unlimited",
          "requiresRecipient": true
        }
      ],
      "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
    }
  4. Make your first purchase

    Send productId, quantity and the total price you expect to pay. Generate a new Idempotency-Key (a UUID) for every purchase and store it before sending.

    curl -X POST https://api.hegodigitaldev.com/api/v1/buyer/orders \
      -H "X-API-Key: hg_live_YOUR_API_KEY" \
      -H "Idempotency-Key: 7f9c2e0a-51d4-4c1b-9a67-3e0d2b8a11f4" \
      -H "Content-Type: application/json" \
      -d '{"productId": 102, "quantity": 2, "expectedPriceUsdt": 7}'
    201 CreatedResponse
    {
      "success": true,
      "orderId": 45012,
      "status": "completed",
      "productId": 102,
      "quantity": 2,
      "totalPriceUsdt": 7,
      "createdAt": 1767225600000,
      "delivery": {
        "items": [
          "maria.lopez@example.com:Pass#8842",
          "juan.perez@example.com:Pass#1937"
        ]
      },
      "balanceAfterUsdt": 143.25,
      "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
    }
    You are done

    The delivery is in delivery.items. You also get a copy in your Telegram chat.

  5. Receive events (recommended)

    Set up a webhook to learn about price and stock changes, asynchronous deliveries and low balance without polling. See Webhooks.

There is no sandbox

Every purchase uses real balance. To practice without spending, use /health, /products and /balance, simulate webhooks with your own signature (see Verify the signature) and make your first purchase with the cheapest product.

Response format#

Every response is JSON in UTF-8, except file downloads. Every response includes:

FieldTypeDescription
successbooleantrue if the operation succeeded, false for an error.
requestIdstringUnique request identifier. Also sent in the X-Request-Id header. Log it and send it to support if something fails.
error, messagestringErrors only: a stable code (INSUFFICIENT_BALANCE) and a readable text. Build your logic on error, not message.

Conventions

  • Amounts: always USDT, as a JSON number (3.5, not "3.50"). Prices have up to 2 decimals.
  • Dates: createdAt is an integer in Unix milliseconds (UTC).
  • IDs: orderId and productId are integers.
  • No caching: responses carry Cache-Control: no-store.
  • Ignore fields you do not know: we may add new fields without notice (we will never remove or change existing ones within /v1).

Authentication & scopes#

Send your API key on every request (except /health) using either header:

Headers
X-API-Key: hg_live_YOUR_API_KEY

# or, equivalently
Authorization: Bearer hg_live_YOUR_API_KEY

Each key carries scopes. New keys include all of them:

ScopeAllows
catalog:readGET /products
balance:readGET /balance
orders:writePOST /orders (spend balance)
orders:readGET /orders/{id} and GET /orders/{id}/download
webhooks:readGET /webhook
webhooks:writePOST /webhook, DELETE /webhook
otp:readPOST /orders/{id}/otp (read codes of bought accounts)
  • 401UNAUTHORIZED — the key is missing, invalid, regenerated or disabled.
  • 403FORBIDDEN — the key is valid but lacks the required scope (Missing orders:write scope).
401Invalid key
{
  "success": false,
  "error": "UNAUTHORIZED",
  "message": "Invalid or missing API key",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
Your key spends your balance

Whoever holds the key can buy with your wallet. Keep it on your server only (environment variables or a secret manager), never in browser code, mobile apps, repositories or screenshots. If it leaks, regenerate it in the bot: the old one stops working immediately.

Products & delivery#

The catalog is live: prices, descriptions and stock change in real time. Each product is delivered in one of these ways:

Instant items

Credentials, links, codes or PINs. They arrive in delivery.items (a list of strings) in the purchase response itself.

File

The response carries delivery.downloadUrl. Download it with your key from GET /orders/{id}/download.

Asynchronous delivery

Some products are delivered by an external supplier with a delay. The purchase answers pending_delivery (already paid) and delivery arrives later: by webhook or by polling the order.

With recipient

Products like Telegram Premium activate on someone else's account. They require recipient.username. See the guide.

Price and stock

  • priceUsdt is the per-unit price. If the product has quantityTiers (pack prices), buying exactly that quantity costs the total shown: for example 5 units for 12 USDT. Any other quantity pays, for every unit, the per-unit price of the biggest pack it reaches: with the 5-pack at 12 USDT, 6 units cost 6 × 2.40 = 14.40 USDT. Below every pack it costs priceUsdt × quantity.
  • availableStock is a number, or "unlimited" for products with no cap. For external-supplier products it is an approximate figure refreshed periodically: if it runs out first, the purchase answers OUT_OF_STOCK or PURCHASE_FAILED.
  • Stock is reserved atomically per purchase: two simultaneous purchases never receive the same item.
  • Held balance: while a purchase from an external supplier is in progress (normally an instant), the amount is held and your available balance in GET /balance drops. It is charged for good when the purchase completes and released automatically if it fails.
  • Only active products are listed.

Order statuses#

StatusMeaningWhat to do
completedPaid and delivered. delivery is available.Hand the product to your customer.
pending_deliveryPaid; the supplier is still delivering.Wait for the order.completed webhook or poll GET /orders/{id} every 5–10 s.
failedThe supplier could not deliver. The amount is refunded to your balance.Tell your customer or retry with a new key. The order.failed webhook is sent.
processingOrder in progress (for example, a payment-pending order created from the bot).Check again later.

GET /orders/{id} returns any order on your account, including those you placed from the Telegram bot.

Idempotency & retries#

Networks fail: a request can arrive while its response is lost. So that retrying never buys twice, POST /orders requires the Idempotency-Key header.

One key per purchase

Generate one UUID per purchase you intend to make and store it before sending. Maximum 128 characters.

Same attempt, same key

After a timeout or network error, resend the identical request with the same key. You will get the order that was already created, or it will be bought exactly once.

New purchase, new key

Reusing a key with a different body returns 409 IDEMPOTENCY_CONFLICT. Keys belong to your account: they keep working even if you regenerate your API key.

What is replayed and what is not

OutcomeWith the same keyNext step
Successful purchase (201)Returns the same order and delivery, without charging again.Done.
INSUFFICIENT_BALANCE, PRICE_CHANGED, NOT_FOUNDReplays the same response.Fix it (top up, refresh the price) and use a new key.
OUT_OF_STOCKNot stored: it is attempted again.You can retry with the same key once stock is back.
502 PURCHASE_FAILEDYour balance was not debited. With own stock it is retried; with an external supplier it replays the error.Retry; if it persists, use a new key or contact support with the requestId.
504 PROVIDER_TIMEOUTYour balance was not debited. Replays the same result: the supplier may have processed the purchase without us knowing.Wait a few seconds and retry with a new key.
409 IDEMPOTENCY_UNRESOLVEDA previous attempt was interrupted before being charged.Nothing was debited. Retry with a new key.
Golden rule

If you do not know whether a purchase happened, repeat the same request with the same key. Never generate a new key to “try again” a purchase that may already have happened.

Limits & timeouts#

ItemValueDetail
Request rate120 per minute per API keyExceeding it returns 429 RATE_LIMITED with a Retry-After header (seconds). Contact support if you need more.
Failed authentications20 per 5 minutes per IPAfter that, attempts with an invalid key receive 429. Requests with a valid key are not affected.
Body size64 KBLarger returns 400.
Idempotency-Keyup to 128 charactersUse a UUID.
Supplier waitup to 15 sSuppliers usually answer instantly. If one does not answer in time, the purchase fails with 504 PROVIDER_TIMEOUT and is not charged.
Recommended client timeout30 s for POST /orders, 15 s elsewhereIf it expires, retry with the same Idempotency-Key.
Webhook10 s to respondSee retries.

On a 429 or 5xx, wait with exponential backoff (1 s, 2 s, 4 s…) and honor Retry-After when present.

Telegram copy#

Even when you buy through the API, the delivery also reaches your chat with the bot, identical to a regular purchase: order summary, a backup .txt file, copy-ready items and buttons for support, problem reports and “My purchases”.

It is a courtesy copy: your integration must always rely on the API response. If you blocked the bot or have no open chat, the purchase works just the same.

Endpoint reference#

Base URL: https://api.hegodigitaldev.com/api/v1/buyer. Every endpoint except /health requires your API key.

GET/healthno auth

Check that the API is up

Status check for monitoring. It needs no authentication and does not use your rate limit.

curl https://api.hegodigitaldev.com/api/v1/buyer/health
200 OKResponse
{
  "success": true,
  "service": "buyer-api",
  "status": "ok",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
GET/productscatalog:read

List the catalog

Returns all active products with their price, stock and delivery details at the time of the call.

Fields of each product

FieldTypeDescription
idintegerIdentifier you use as productId.
namestringCommercial name.
descriptionstringWhat the product includes.
instructionsstringUsage notes delivered with the purchase. May be empty.
priceUsdtnumberPer-unit price in USDT, already including the API client discount when one is active.
quantityTiersarrayPack prices: {quantity, totalPriceUsdt}. Buying exactly quantity units costs totalPriceUsdt in total. Empty ([]) when the price is flat.
availableStockinteger | "unlimited"Units available.
requiresRecipientbooleanIf true, POST /orders requires recipient.username.
  • 401UNAUTHORIZED — invalid key.
  • 403FORBIDDEN — missing catalog:read.

Fetch it on start-up, then keep your copy fresh with webhooks instead of polling constantly.

curl https://api.hegodigitaldev.com/api/v1/buyer/products \
  -H "X-API-Key: hg_live_YOUR_API_KEY"
200 OKResponse
{
  "success": true,
  "products": [
    {
      "id": 102,
      "name": "Netflix 1 Screen (30 days)",
      "description": "Single profile with PIN. Renewable.",
      "instructions": "Sign in with the email and password delivered. Do not change the password.",
      "priceUsdt": 3.5,
      "quantityTiers": [
        {
          "quantity": 5,
          "totalPriceUsdt": 15
        }
      ],
      "availableStock": 18,
      "requiresRecipient": false
    },
    {
      "id": 215,
      "name": "Telegram Premium 3 months",
      "description": "Direct activation on the account you specify.",
      "instructions": "",
      "priceUsdt": 14.9,
      "quantityTiers": [],
      "availableStock": "unlimited",
      "requiresRecipient": true
    }
  ],
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
GET/balancebalance:read

Get your balance

Available USDT balance of your wallet. It is the same balance you see in the bot.

  • 401UNAUTHORIZED — invalid key.
  • 403FORBIDDEN — missing balance:read.

Every successful purchase also returns balanceAfterUsdt, so you do not need to query it after buying.

curl https://api.hegodigitaldev.com/api/v1/buyer/balance \
  -H "X-API-Key: hg_live_YOUR_API_KEY"
200 OKResponse
{
  "success": true,
  "balanceUsdt": 143.25,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
POST/ordersorders:write

Create a purchase

Buys a product with your balance. In one step it validates the price, reserves stock, debits your wallet and delivers. It is idempotent: retrying with the same Idempotency-Key never buys twice.

Headers

HeaderValue
X-API-Key requiredYour API key.
Idempotency-Key requiredUnique UUID per purchase (max 128 characters).
Content-Type requiredapplication/json

Body

FieldTypeDescription
productId requiredintegerProduct ID (from GET /products).
quantity optionalintegerUnits, minimum 1. Default 1.
expectedPriceUsdt requirednumberThe total price you expect to pay for the whole quantity, not per unit. If the current price differs, nothing is charged and you get PRICE_CHANGED. It protects your customer from price changes.
recipient.username optionalstringTelegram user who receives the product, with @ (5–32 characters: letters, digits and _). Required when requiresRecipient is true.

Successful response

FieldDescription
orderIdOrder ID. Store it: you need it to query the order.
statuscompleted or pending_delivery. See statuses.
productId, quantityWhat you bought.
totalPriceUsdtAmount charged.
createdAtUnix milliseconds.
delivery.itemsList of delivered strings (only if completed and not a file).
delivery.downloadUrlRelative path to download the file (file products).
balanceAfterUsdtRemaining balance after the purchase.

Errors

  • 400BAD_REQUEST — missing Idempotency-Key, invalid JSON or not an object, invalid fields, missing recipient.username or body over 64 KB.
  • 402INSUFFICIENT_BALANCE — your balance is not enough. Nothing was charged.
  • 404NOT_FOUND — the product does not exist or is unavailable.
  • 409PRICE_CHANGED — the price changed; the response carries currentPriceUsdt.
  • 409OUT_OF_STOCK — not enough stock.
  • 409IDEMPOTENCY_CONFLICT — that key was already used with a different body.
  • 409IDEMPOTENCY_UNRESOLVED — a previous attempt was interrupted; use a new key.
  • 502PURCHASE_FAILED — could not be completed; your balance was not debited.
  • 504PROVIDER_TIMEOUT — the supplier did not answer within 15 s; your balance was not debited. Retry with a new key.
What if the price changes?

Treat it as a feature, not an error: show the new price (currentPriceUsdt) to your customer or apply your tolerance rule and call again with a new Idempotency-Key and the new expectedPriceUsdt.

curl -X POST https://api.hegodigitaldev.com/api/v1/buyer/orders \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -H "Idempotency-Key: 7f9c2e0a-51d4-4c1b-9a67-3e0d2b8a11f4" \
  -H "Content-Type: application/json" \
  -d '{"productId": 102, "quantity": 2, "expectedPriceUsdt": 7}'
201 CreatedCompleted purchase
{
  "success": true,
  "orderId": 45012,
  "status": "completed",
  "productId": 102,
  "quantity": 2,
  "totalPriceUsdt": 7,
  "createdAt": 1767225600000,
  "delivery": {
    "items": [
      "maria.lopez@example.com:Pass#8842",
      "juan.perez@example.com:Pass#1937"
    ]
  },
  "balanceAfterUsdt": 143.25,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
201 CreatedAsynchronous product: paid, delivery pending
{
  "success": true,
  "orderId": 45013,
  "status": "pending_delivery",
  "productId": 215,
  "quantity": 1,
  "totalPriceUsdt": 14.9,
  "createdAt": 1767225600000,
  "balanceAfterUsdt": 128.35,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
201 CreatedFile product
{
  "success": true,
  "orderId": 45014,
  "status": "completed",
  "productId": 320,
  "quantity": 1,
  "totalPriceUsdt": 9,
  "createdAt": 1767225600000,
  "delivery": {
    "downloadUrl": "/api/v1/buyer/orders/45014/download"
  },
  "balanceAfterUsdt": 119.35,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
409 ConflictThe price changed
{
  "success": false,
  "error": "PRICE_CHANGED",
  "message": "Price changed",
  "currentPriceUsdt": 7.2,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
402 Payment RequiredInsufficient balance
{
  "success": false,
  "error": "INSUFFICIENT_BALANCE",
  "message": "Insufficient wallet balance",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
504 Gateway TimeoutThe supplier did not answer
{
  "success": false,
  "error": "PROVIDER_TIMEOUT",
  "message": "The supplier did not answer in time. Your balance was not debited.",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
GET/orders/{id}orders:read

Get an order

Current state of an order on your account and, when completed, its delivery. Use it to resolve pending_delivery or to reconcile your records.

  • 404NOT_FOUND — the order does not exist or is not yours.
  • 403FORBIDDEN — missing orders:read.

The body has the same fields as the purchase, except balanceAfterUsdt. There is no endpoint to list orders: store the orderId of every purchase.

curl https://api.hegodigitaldev.com/api/v1/buyer/orders/45012 \
  -H "X-API-Key: hg_live_YOUR_API_KEY"
200 OKResponse
{
  "success": true,
  "orderId": 45012,
  "status": "completed",
  "productId": 102,
  "quantity": 2,
  "totalPriceUsdt": 7,
  "createdAt": 1767225600000,
  "delivery": {
    "items": [
      "maria.lopez@example.com:Pass#8842",
      "juan.perez@example.com:Pass#1937"
    ]
  },
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
404 Not FoundUnknown order
{
  "success": false,
  "error": "NOT_FOUND",
  "message": "Order not found",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
GET/orders/{id}/downloadorders:read

Download an order file

For file products. Returns the original file (not JSON) with its Content-Type and Content-Disposition: attachment. The name has no extension: use the Content-Type to decide how to store it.

  • 404NOT_FOUND — the order does not exist, is not yours or its product is not a file.
  • 409DELIVERY_NOT_READY — the order is not completed yet.
  • 502 / 503DELIVERY_UNAVAILABLE — the file could not be retrieved right now; retry in a few seconds.
curl -L https://api.hegodigitaldev.com/api/v1/buyer/orders/45014/download \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -o pedido-45014
POST/orders/{id}/otpotp:read

Read the OTP code of a bought account

For streaming accounts that get codes by email (Disney+, Max, Prime Video, Paramount+, Canva, Apple TV, DAZN). First request the code from the service's app or website, then call this endpoint: it reads the latest email sent to that account and returns only the code or the link.

FieldTypeDescription
email requiredstringEmail of an account delivered in that order.
action requiredstringlogin (Disney+), change (Disney+ email change), max, max_change (Max recovery), prime, paramount, canva, canva_change, apple_tv, apple_tv_change, dazn.

The response carries code or link (whatever the service sent) and receivedAt when known. Each product allows only some actions; the others answer OTP_NOT_ALLOWED.

  • 404NOT_FOUND — the order does not exist, is not yours or is not completed.
  • 403EMAIL_NOT_IN_ORDER — that email was not delivered in that order.
  • 403OTP_NOT_ALLOWED — the product does not allow that action.
  • 400OTP_ACTION_NOT_SUPPORTED — unknown action.
  • 404OTP_NOT_FOUND_YET — no code has arrived yet: request it again from the service and retry in a few seconds.
  • 410OTP_WINDOW_EXPIRED — the order is more than 30 days old.
  • 429RATE_LIMITED — at most 10 per hour and 30 per day per order (and per email), and 20 per minute overall. Honour retryAfterSec.
  • 503OTP_UNAVAILABLE — codes cannot be read right now; retry in a few seconds.
No automatic retries

Every call that reaches the mailbox counts against the limit, even when there is no code yet. Wait 5–10 s between attempts; a request can take up to ~30 s.

curl -X POST https://api.hegodigitaldev.com/api/v1/buyer/orders/45012/otp \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email": "maria.lopez@example.com", "action": "login"}'
200 OKCode
{
  "success": true,
  "code": "482913",
  "receivedAt": "2026-11-30T14:05:12.000Z",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
200 OKLink
{
  "success": true,
  "link": "https://auth.max.com/reset?token=…",
  "receivedAt": "2026-11-30T14:05:12.000Z",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
404 Not FoundNot here yet
{
  "success": false,
  "error": "OTP_NOT_FOUND_YET",
  "message": "No code or link found yet. Ask the service to send it again and retry in a few seconds",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
429 Too Many RequestsLimit reached
{
  "success": false,
  "error": "RATE_LIMITED",
  "message": "Too many OTP requests. Retry later",
  "retryAfterSec": 1740,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
GET/webhookwebhooks:read

Get your webhook

Returns the current configuration. The secret is never shown in full again: you only see its last 4 characters in secretMasked.

  • 404NOT_FOUND — no webhook is configured.
  • 409WEBHOOK_SECRET_UNREADABLE — the stored secret cannot be read; register the webhook again.
cURL
curl https://api.hegodigitaldev.com/api/v1/buyer/webhook \
  -H "X-API-Key: hg_live_YOUR_API_KEY"
200 OKResponse
{
  "success": true,
  "webhook": {
    "url": "https://tienda.example.com/hooks/hego",
    "events": [
      "order.completed",
      "order.failed",
      "stock.changed",
      "balance.low"
    ],
    "balanceThresholdUsdt": 20,
    "secretMasked": "***5f80"
  },
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
POST/webhookwebhooks:write

Set your webhook

Registers the URL that receives events and which ones you subscribe to. There is one webhook per account: calling again replaces the configuration and generates a new secret (the old one stops working immediately).

FieldTypeDescription
url requiredstringPublic https URL. No credentials, port 443 or 8443, and a domain that resolves to a public IP (no localhost or private networks). Redirects are not followed.
events requiredstring[]One or more of: order.completed, order.failed, catalog.updated, stock.changed, balance.low.
balanceThresholdUsdt optionalnumberThreshold (≥ 0) for balance.low.
  • 400BAD_REQUEST — invalid URL or event (HTTPS URL is required, Invalid URL destination, Port not allowed, Host does not resolve, Invalid event: …).
The secret is shown only once

Store it in your secret manager: you need it to verify the signature of every event.

curl -X POST https://api.hegodigitaldev.com/api/v1/buyer/webhook \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://tienda.example.com/hooks/hego",
    "events": ["order.completed", "order.failed", "stock.changed", "balance.low"],
    "balanceThresholdUsdt": 20
  }'
200 OKResponse
{
  "success": true,
  "webhook": {
    "url": "https://tienda.example.com/hooks/hego",
    "events": [
      "order.completed",
      "order.failed",
      "stock.changed",
      "balance.low"
    ],
    "balanceThresholdUsdt": 20,
    "secret": "whsec_live_5b1e0c7a94d3f28a6e1b0d47c93f5a82e6d1074b3c9a5f80"
  },
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
DELETE/webhookwebhooks:write

Delete your webhook

Disables the webhook. Because it is destructive, it requires explicit confirmation in the body: {"confirm": true}. Pending events are cancelled.

  • 400BAD_REQUEST — missing confirm: true.
  • 404NOT_FOUND — no webhook is configured.
cURL
curl -X DELETE https://api.hegodigitaldev.com/api/v1/buyer/webhook \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"confirm": true}'
200 OKResponse
{
  "success": true,
  "message": "Webhook deleted",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}

Webhooks#

Instead of polling the API, let Hego tell you: we send a POST with JSON to your URL when an event you subscribed to happens. Configure it with POST /webhook.

What your server receives

HeaderContent
X-Hego-EventEvent type, for example order.completed.
X-Hego-DeliveryUnique event ID (evt_…). Use it to deduplicate.
X-Hego-SignatureSignature: t=<timestamp>,v1=<hmac>. See verification.
X-Request-IdIdentifier of this delivery attempt, for support.
User-AgentHegoMarket-BuyerAPI/1.0

The body is JSON with the event data plus eventId and type. Both are covered by the signature, so you can trust them.

Answer with any 2xx within 10 seconds. Anything else (or a timeout) counts as a failure and is retried.

Events & payloads#

EventWhenWhat to do
order.completedAn order was delivered: after an instant purchase or when a supplier finishes an asynchronous delivery.If it was pending_delivery, call GET /orders/{id} to read the delivery.
order.failedA supplier could not deliver. The amount was already refunded to your balance.Tell your customer or retry with a new key.
catalog.updatedA product changed: price, name, description or status. May group several products.Re-read those products with GET /products.
stock.changedA product's inventory changed (restock, sale, withdrawal). May group several.Update your local stock.
balance.lowYour balance dropped below your threshold because of a purchase (emitted once when crossed).Top up your wallet.
POSTorder.completed
{
  "orderId": 45013,
  "eventId": "evt_9f2b7c1d4a6e08355b2c9d1e7f30a4b6",
  "type": "order.completed"
}
POSTorder.failed
{
  "orderId": 45013,
  "eventId": "evt_9f2b7c1d4a6e08355b2c9d1e7f30a4b6",
  "type": "order.failed"
}
POSTcatalog.updated
{
  "productId": 102,
  "productIds": [
    98,
    102
  ],
  "eventId": "evt_9f2b7c1d4a6e08355b2c9d1e7f30a4b6",
  "type": "catalog.updated"
}
POSTstock.changed
{
  "productId": 102,
  "productIds": [
    98,
    102
  ],
  "eventId": "evt_9f2b7c1d4a6e08355b2c9d1e7f30a4b6",
  "type": "stock.changed"
}
POSTbalance.low
{
  "balanceUsdt": 18.4,
  "thresholdUsdt": 20,
  "eventId": "evt_9f2b7c1d4a6e08355b2c9d1e7f30a4b6",
  "type": "balance.low"
}
Grouped events

When many products change in a row (a bulk restock, for example), catalog.updated and stock.changed are grouped into a single delivery: productIds lists all products and productId is the latest. If the API client discount changes, a catalog.updated arrives with allProducts: true and no productId: re-read the whole catalog.

Verify the signature#

Anyone can send a POST to your URL. The signature proves Hego sent it and that nobody altered the body. Always verify it before acting.

  1. Read t and v1 from the X-Hego-Signature header.
  2. Build the signed text: t + . + X-Hego-Delivery + . + the exact raw body.
  3. Compute HMAC-SHA256 with your secret (whsec_live_…) and compare it in hex with v1, in constant time.
  4. Reject if t (milliseconds) is more than 5 minutes away from your clock: it prevents replays of old deliveries.
import crypto from 'node:crypto';
import express from 'express';

const app = express();
const TOLERANCE_MS = 5 * 60 * 1000;

// IMPORTANT: use the RAW body (Buffer), not the already-parsed JSON
app.post('/hooks/hego', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('X-Hego-Signature') || '';
  const eventId = req.get('X-Hego-Delivery') || '';
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));

  const fresh = Math.abs(Date.now() - Number(parts.t)) <= TOLERANCE_MS;
  const expected = crypto
    .createHmac('sha256', process.env.HEGO_WEBHOOK_SECRET)
    .update(`${parts.t}.${eventId}.${req.body.toString('utf8')}`)
    .digest('hex');
  const given = Buffer.from(parts.v1 || '');
  const valid = given.length === expected.length &&
    crypto.timingSafeEqual(given, Buffer.from(expected));

  if (!fresh || !valid) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString('utf8'));
  res.sendStatus(200); // answer fast, process afterwards
  queueForProcessing(event); // deduplicate by event.eventId
});
Use the raw body

If your framework parses the JSON and serializes it again, the bytes change and the signature will not match. Read the body as bytes/text before parsing it.

Test your verification

With your secret you can sign a test delivery and send it to your own endpoint:

Bash
# Simulate a signed delivery against your endpoint (handy to test your verification)
SECRET="whsec_live_..."
BODY='{"orderId":45013,"eventId":"evt_test_1","type":"order.completed"}'
TS=$(date +%s%3N)
SIG=$(printf '%s' "$TS.evt_test_1.$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //')

curl -X POST https://tienda.example.com/hooks/hego \
  -H "Content-Type: application/json" \
  -H "X-Hego-Event: order.completed" \
  -H "X-Hego-Delivery: evt_test_1" \
  -H "X-Hego-Signature: t=$TS,v1=$SIG" \
  -d "$BODY"

Retries & ordering#

Up to 5 attempts

Immediate, then at 1 min, 5 min, 30 min and 6 h. After the fifth failure the event is dropped and support is alerted.

At least once

The same event can arrive more than once. Deduplicate by eventId (or the X-Hego-Delivery header) and make your handling idempotent.

No strict ordering

Your account's events are sent in order, but a retry can arrive after a newer one. When in doubt, query the current state through the API.

  • Answer fast (2xx) and process in the background.
  • We do not follow redirects: a 3xx response counts as a failure. Register the final URL.
  • Before every delivery we check again that your domain resolves to a public IP.
  • If your endpoint was down for more than a few hours, reconcile with GET /products and GET /orders/{id}.

Error codes#

Every error shares the same format and a stable error code you can build on.

CodeHTTPWhen it happensWhat to do
BAD_REQUEST400Malformed request or invalid fields.Fix the request; do not retry as is.
UNAUTHORIZED401API key missing, invalid or revoked.Check the key; regenerate it if it leaked.
INSUFFICIENT_BALANCE402Insufficient balance.Top up and retry with a new key.
FORBIDDEN403The key lacks the required scope.Use a key with that scope.
NOT_FOUND404Unknown product, order, webhook or route.Check the ID.
PRICE_CHANGED409The current total price does not match expectedPriceUsdt.Use currentPriceUsdt with a new key.
OUT_OF_STOCK409Insufficient stock.Retry later (same key) or reduce the quantity.
IDEMPOTENCY_CONFLICT409The key was already used with a different body.Use a new key for a different purchase.
IDEMPOTENCY_UNRESOLVED409A previous attempt was interrupted before being charged.Retry with a new key.
DELIVERY_NOT_READY409Download of an order that is not completed yet.Wait for completed.
WEBHOOK_SECRET_UNREADABLE409The stored secret cannot be read.Register the webhook again.
RATE_LIMITED429Too many requests.Wait Retry-After seconds.
INTERNAL_ERROR500Unexpected error on our side.Retry with backoff; report the requestId if it persists.
PURCHASE_FAILED502The purchase could not be completed (for example, the supplier failed). Your balance was not debited.Retry; if it persists, contact support with the requestId.
PROVIDER_TIMEOUT504The external supplier did not answer within 15 s. Your balance was not debited.Wait a few seconds and retry with a new key.
DELIVERY_UNAVAILABLE502 / 503The file could not be retrieved.Retry in a few seconds.
OTP_ACTION_NOT_SUPPORTED400Unknown OTP action.Use one of the documented actions.
EMAIL_NOT_IN_ORDER403The email was not delivered in that order.Check the email and the orderId.
OTP_NOT_ALLOWED403The product does not allow that OTP action.Do not retry; contact support if you think it is a mistake.
OTP_NOT_FOUND_YET404No code or link has arrived yet.Request it again from the service and retry in 5–10 s.
OTP_WINDOW_EXPIRED410The order is more than 30 days old.Contact support.
OTP_UNAVAILABLE503Codes cannot be read right now.Retry in a few seconds.
402Example: insufficient balance
{
  "success": false,
  "error": "INSUFFICIENT_BALANCE",
  "message": "Insufficient wallet balance",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
409Example: out of stock
{
  "success": false,
  "error": "OUT_OF_STOCK",
  "message": "Insufficient stock",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
429Example: rate limited
{
  "success": false,
  "error": "RATE_LIMITED",
  "message": "Rate limit exceeded",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
400Example: invalid request
{
  "success": false,
  "error": "BAD_REQUEST",
  "message": "Invalid order payload",
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}

Robust purchase flow#

A complete Node.js example combining the essentials: one Idempotency-Key per purchase, safe retries with the same key, 429/5xx handling and waiting for asynchronous deliveries.

JavaScript
import { randomUUID } from 'node:crypto';

const BASE = 'https://api.hegodigitaldev.com/api/v1/buyer';
const headers = (extra = {}) => ({ 'X-API-Key': process.env.HEGO_API_KEY, ...extra });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// 1) Purchase with safe retries: SAME key while it is the same attempt
async function buy({ productId, quantity, expectedPriceUsdt, recipient }) {
  const idempotencyKey = randomUUID(); // persist it in your database before calling
  const body = JSON.stringify({ productId, quantity, expectedPriceUsdt, recipient });

  for (let attempt = 1; attempt <= 4; attempt++) {
    try {
      const res = await fetch(`${BASE}/orders`, {
        method: 'POST',
        headers: headers({ 'Idempotency-Key': idempotencyKey, 'Content-Type': 'application/json' }),
        body,
        signal: AbortSignal.timeout(30_000), // the server waits up to 15 s for the supplier
      });
      const data = await res.json();

      if (res.status === 201) return data;
      if (res.status === 504) throw Object.assign(new Error(data.message), { code: data.error, data }); // slow supplier: nothing charged; retry later with a NEW key
      if (res.status === 429) { await sleep(Number(res.headers.get('retry-after') || 1) * 1000); continue; }
      if (res.status >= 500 || res.status === 409 && data.error === 'OUT_OF_STOCK') { await sleep(2 ** attempt * 500); continue; }
      throw Object.assign(new Error(data.message), { code: data.error, data }); // 402, 400, 404, price 409: do not retry
    } catch (err) {
      if (err.code) throw err;              // business error: bubble up
      await sleep(2 ** attempt * 500);       // timeout/network: retry with the SAME key
    }
  }
  throw new Error('Could not confirm the purchase');
}

// 2) If it is pending_delivery, wait for the webhook or poll the order
async function waitForDelivery(orderId, { every = 5000, timeout = 600_000 } = {}) {
  const deadline = Date.now() + timeout;
  while (Date.now() < deadline) {
    const res = await fetch(`${BASE}/orders/${orderId}`, { headers: headers() });
    const order = await res.json();
    if (order.status === 'completed' || order.status === 'failed') return order;
    await sleep(every);
  }
  throw new Error('Delivery still pending');
}

// 3) Usage
const order = await buy({ productId: 215, quantity: 1, expectedPriceUsdt: 14.9, recipient: { username: '@cliente_final' } });
const final = order.status === 'pending_delivery' ? await waitForDelivery(order.orderId) : order;
console.log(final.status, final.delivery);

Why it works this way

  • The key is created once per purchase and reused across retries: if the response was lost, you get the same order.
  • Business errors (402, 400, 404, price) are not retried: repeating them does not fix them.
  • Store the orderId and outcome in your database as part of the same operation that hands the product to your customer.

Keeping your catalog in sync#

Prices and stock change all the time. The recommended pattern:

  1. On start-up, load everything with GET /products and store it.
  2. Subscribe to catalog.updated and stock.changed.
  3. When an event arrives, re-read the catalog (or only the listed productIds) and update your copy.
  4. As a safety net, refresh the whole catalog every 10–15 minutes.
  5. Always send expectedPriceUsdt: if your copy went stale, the API protects you with PRICE_CHANGED.

Recipient products#

Products with requiresRecipient: true (for example Telegram Premium or Stars) are activated directly on a Telegram account. Say who receives it in recipient.username:

cURL
curl -X POST https://api.hegodigitaldev.com/api/v1/buyer/orders \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -H "Idempotency-Key: 0c5d7a2e-93b1-4f68-8e0a-6d41b7c9e2f5" \
  -H "Content-Type: application/json" \
  -d '{"productId": 215, "quantity": 1, "expectedPriceUsdt": 14.9,
       "recipient": {"username": "@cliente_final"}}'
201 CreatedUsually pending until the supplier activates
{
  "success": true,
  "orderId": 45013,
  "status": "pending_delivery",
  "productId": 215,
  "quantity": 1,
  "totalPriceUsdt": 14.9,
  "createdAt": 1767225600000,
  "balanceAfterUsdt": 128.35,
  "requestId": "3f0c6a52-8d1b-4a0e-9c47-2b5e7d9a1c30"
}
  • The username must start with @ and be 5–32 characters (letters, digits or _).
  • Verify the username before buying: an activation on the wrong account cannot be undone.
  • If you forget the recipient you get 400 BAD_REQUEST and nothing is charged.

File products#

When the product is a file, the purchase returns delivery.downloadUrl (a relative path). Download it with your API key:

curl -L https://api.hegodigitaldev.com/api/v1/buyer/orders/45014/download \
  -H "X-API-Key: hg_live_YOUR_API_KEY" \
  -o pedido-45014

You can download it again whenever you like while the order exists. Save the file in your own storage: your customer should never use your API key to download it.

Production checklist#

Security

Key in a secret manager · never in frontend · always HTTPS · regenerate if leaked · webhook secret stored separately.

Purchases

UUID stored before sending · same key on retries · always expectedPriceUsdt · 30 s timeout · store orderId.

Webhooks

Signature and timestamp verified · raw body · fast 2xx · dedupe by eventId · asynchronous processing.

Operations

Log the requestId · exponential backoff on 429/5xx · alert on balance.low · periodic reconciliation.

Frequently asked questions#

Is there a sandbox?

There is no separate environment: purchases use real balance. To test your integration end to end, buy the TEST ITEM product from the catalog: it is a test product made for that. You can also try /health, /products and /balance and simulate signed webhooks with your secret.

Can I buy more than 10 units in one order?

It depends on the product. Some (those delivered instantly from an external supplier) accept at most 10 units per order: with more, the API answers 400 BAD_REQUEST without charging. Split the purchase into several orders, each with its own Idempotency-Key.

Is there a discount for API clients?

There may be. When it is active, GET /products already returns the prices with the discount applied (priceUsdt and quantityTiers) and that is what is charged: use those values in expectedPriceUsdt. Some supplier products may keep their normal price when a discount would leave no margin. When the discount changes you receive a catalog.updated with allProducts: true.

My request timed out. Was I charged?

Repeat the same request with the same Idempotency-Key. If the purchase happened you get that order; if not, it happens exactly once. Never change the key.

I got 502 PURCHASE_FAILED.

Your balance was not debited. Retry; if it stays the same with the same key, use a new key. If it persists, contact support with the requestId.

I got 504 PROVIDER_TIMEOUT.

The supplier did not answer in time and your balance was not debited (the held amount is released automatically). It is rare: wait a few seconds and retry with a new key. If it happens often with a product, let us know with the requestId.

Why did my balance drop and then come back?

While a purchase with an external supplier is being processed the amount is held so nobody else can spend it. If the purchase fails it is released; if it completes it is charged for good.

Why do I get PRICE_CHANGED if the price looks the same?

expectedPriceUsdt is the total price for the quantity, not the unit price. With quantity: 3 at 3.5 each send 10.5. If the product has quantityTiers, the exact quantity of a pack costs its own total (not unit × quantity). When in doubt, use currentPriceUsdt from the response.

How do I list my orders?

Today orders are queried by ID with GET /orders/{id}. Store each purchase's orderId in your database.

How do I rotate my API key?

In the bot: Profile → Developer API → Regenerate. The old key stops working immediately and your previous Idempotency-Keys remain valid. You can also disable the API from there.

Can I call the API from a browser?

Do not: you would expose a key that spends your balance. Always call from your server.

How many keys can I have?

One active key per account. Regenerating revokes the previous one.

Which currency does it use?

USDT, for both prices and balance.

Where do I get help?

From the bot's support button. Always include the response's requestId (or the X-Request-Id header) and the orderId if applicable.

Changelog#

VersionDateChanges
v12026-11New POST /orders/{id}/otp and otp:read scope (added to existing keys): read the code or link of a bought account without opening the bot.
v12026-10Optional discount for API clients: the prices in GET /products and what is charged already include it. When it changes, catalog.updated is sent with allProducts: true (no productId).
v12026-10GET /products now includes quantityTiers: the pack prices of each product (buying exactly that quantity costs that total).
v12026-09Purchases with external suppliers: 15 s maximum wait (504 PROVIDER_TIMEOUT, no charge) and the balance is held while the purchase is in progress so it cannot be spent twice.
v12026-09Hardening: rate limits, strict webhook validation (public destinations, no redirects), type and eventId inside the signature, grouped events with productIds, OUT_OF_STOCK (409), IDEMPOTENCY_UNRESOLVED, recovery of interrupted purchases and a failed status consistent with the webhook.
v12026-09Launch: catalog, balance, idempotent purchases, order lookup and download, and signed webhooks.

Compatible changes (new fields, new events) are added within /v1. A breaking change would ship as /v2 with prior notice.