onchain-pay-open-api

binance/binance-skills-hub

Binance Onchain Pay: покупка крипты за фиат или отправка с Binance на внешний кошелёк в один поток.

Звёзды1 199
Форки278
Авторbinance
Обновлённоя 12 2026

Установка

SKILL.md

Binance Onchain-Pay Open API Skill

Call Binance Onchain-Pay Open API endpoints with automatic RSA SHA256 request signing.

Use Cases & Scenarios

This skill is designed for the following scenarios:

1. 💳 Fiat-to-Crypto Purchase & Send

When to use: User wants to buy crypto with fiat currency and send directly to an external on-chain wallet address

  • Buy USDT with USD/EUR/TWD using credit card → Send to MetaMask address on BSC
  • Purchase BTC with Google Pay → Transfer to hardware wallet
  • Buy USDC with P2P → Send to DeFi protocol contract address

Key APIs: trading-pairs → payment-method-list → estimated-quote → pre-order

2. 🔄 Direct Crypto Transfer (Send Primary)

When to use: User has crypto in Binance account and wants to send to external address

  • Send existing USDT from Binance Spot to friend's wallet address
  • Transfer ETH to Uniswap contract for trading
  • Move crypto from Binance to self-custodial wallet (Trust Wallet, Ledger, etc.)

Key APIs: pre-order with SEND_PRIMARY customization

3. 🔗 Cross-Chain Bridge Operations

When to use: User needs to buy crypto on one chain and transfer to another network

  • Buy USDC on Ethereum → Bridge to Polygon for lower fees
  • Purchase tokens on BSC → Transfer to Base network
  • Fiat to crypto on Solana → Send to Arbitrum for DeFi

Key APIs: crypto-network → pre-order with network selection

4. 🏪 Merchant Payment Integration

When to use: Integrate crypto payment gateway for e-commerce or services

  • Accept fiat payments and auto-convert to crypto
  • Enable "Pay with Crypto" checkout flow
  • Process subscription payments with crypto

Key APIs: pre-order with externalOrderId tracking

5. 🤖 Smart Contract Interaction (Onchain-Pay Easy)

When to use: Buy crypto and execute smart contract in one transaction

  • Buy USDT and deposit to lending protocol
  • Purchase tokens and stake in DeFi pool
  • Fiat on-ramp directly to GameFi or NFT marketplace

Key APIs: pre-order with ON_CHAIN_PROXY_MODE customization

6. 📊 Query & Monitoring

When to use: Check order status, available networks, or payment methods

  • Monitor order processing status (pending, completed, failed)
  • List supported fiat currencies and cryptocurrencies
  • Check available payment methods for specific country/amount
  • Verify network fees and limits

Key APIs: order, crypto-network, trading-pairs, payment-method-list


Quick Reference

EndpointAPI PathRequired ParamsOptional Params
Payment Method List (v1)papi/v1/ramp/connect/buy/payment-method-listfiatCurrency, cryptoCurrency, totalAmount, amountTypenetwork, contractAddress
Payment Method List (v2)papi/v2/ramp/connect/buy/payment-method-list(none)lang
Trading Pairspapi/v1/ramp/connect/buy/trading-pairs(none)(none)
Estimated Quotepapi/v1/ramp/connect/buy/estimated-quotefiatCurrency, requestedAmount, payMethodCode, amountTypecryptoCurrency, contractAddress, address, network
Pre-orderpapi/v1/ramp/connect/buy/pre-orderexternalOrderId, merchantCode, merchantName, tsfiatCurrency, fiatAmount, cryptoCurrency, requestedAmount, amountType, address, network, payMethodCode, payMethodSubCode, redirectUrl, failRedirectUrl, redirectDeepLink, failRedirectDeepLink, customization, destContractAddress, destContractABI, destContractParams, affiliateCode, gtrTemplateCode, contractAddress
Get Orderpapi/v1/ramp/connect/orderexternalOrderId(none)
Crypto Networkpapi/v1/ramp/connect/crypto-network(none)(none)
P2P Trading Pairspapi/v1/ramp/connect/buy/p2p/trading-pairs(none)fiatCurrency

How to Execute a Request

Step 1: Gather credentials

Use the default account (prod) unless the user specifies otherwise. You need:

  • BASE_URL: API base URL
  • CLIENT_ID: Client identifier
  • API_KEY: The sign access token
  • PEM_PATH: Absolute path to the RSA private key PEM file

Use the account marked (default) in .local.md.

Step 2: Build the JSON body

Build a compact JSON body from user-specified parameters. Remove any parameters the user did not provide.

IMPORTANT: Address and Network Validation

  • address (destination wallet address) and network (blockchain network) are REQUIRED for all pre-order requests
  • If the user has configured Default Address and Default Network in .local.md, use them automatically
  • If not configured or not provided by user, ASK the user to provide both values before proceeding

Step 3: Sign and call using the bundled script

bash <skill_path>/scripts/sign_and_call.sh \
  "<BASE_URL>" \
  "<API_PATH>" \
  "<CLIENT_ID>" \
  "<API_KEY>" \
  "<PEM_PATH>" \
  '<JSON_BODY>'

Step 4: Return results

Display the JSON response to the user in a readable format.


Authentication

See references/authentication.md for full signing details.

Summary:

  1. Payload = JSON_BODY + TIMESTAMP (milliseconds)
  2. Sign payload with RSA SHA256 using PEM private key
  3. Base64 encode the signature (single line)
  4. Send as POST with headers: X-Tesla-ClientId, X-Tesla-SignAccessToken, X-Tesla-Signature, X-Tesla-Timestamp, Content-Type: application/json

Parameters Reference

Payment Method List v1 (buy/payment-method-list)

ParameterTypeRequiredDescription
fiatCurrencystringYesFiat currency code (e.g., USD, EUR, BRL, UGX)
cryptoCurrencystringYesCrypto currency code (e.g., BTC, USDT, USDC, SEI)
totalAmountnumberYesAmount value
amountTypenumberYes1 = fiat amount, 2 = crypto amount
networkstringNoBlockchain network (e.g., BSC, ETH, SOL, BASE, SEI)
contractAddressstringNoToken contract address (required for non-native tokens)

Payment Method List v2 (v2/buy/payment-method-list)

Get all available payment methods without specifying fiat/crypto parameters. Simplified version of v1.

ParameterTypeRequiredDescription
langstringNoLanguage code for localized payment method names (e.g., en, cn, es)

Differences from v1:

  • Simpler: No need to specify fiatCurrency, cryptoCurrency, or amount
  • Comprehensive: Returns all available payment methods for the merchant
  • Use case: Useful for displaying all options before user input

Response Format: Same as v1, returns list of payment methods with their limits and properties.

Estimated Quote (buy/estimated-quote)

ParameterTypeRequiredDescription
fiatCurrencystringYesFiat currency code
cryptoCurrencystringNoCrypto currency code (optional if contractAddress provided)
requestedAmountnumberYesAmount value
payMethodCodestringYesPayment method (e.g., BUY_CARD, BUY_GOOGLE_PAY, BUY_P2P, BUY_WALLET)
amountTypenumberYes1 = fiat amount, 2 = crypto amount
networkstringYes*Blockchain network (can use default from .local.md)
contractAddressstringNoToken contract address
addressstringYes*Destination wallet address for receiving crypto

* Recommended: These parameters should be provided. If not specified by user, check .local.md for defaults. If no defaults exist, ask user before proceeding.

Pre-order (buy/pre-order)

Create a buy pre-order and return the redirect link for payment.

ParameterTypeRequiredDescription
externalOrderIdstringYesPartner's unique order ID (must be unique)
merchantCodestringYesMerchant code assigned to you by Binance (provided by user)
merchantNamestringYesMerchant display name (provided by user)
tsnumberYesCurrent timestamp in milliseconds
fiatCurrencystringNo*Fiat currency code (e.g., TWD, USD, EUR)
fiatAmountnumberNo*Fiat amount to spend
cryptoCurrencystringNo*Crypto currency to buy (e.g., USDT, BTC, ETH)
requestedAmountnumberNo*Amount value (fiat or crypto based on amountType)
amountTypenumberNo*1 = fiat amount, 2 = crypto amount
addressstringNoDestination wallet address for receiving crypto
networkstringNoBlockchain network (e.g., BSC, ETH, SOL)
payMethodCodestringNoPayment method code (e.g., BUY_CARD, BUY_P2P, BUY_GOOGLE_PAY, BUY_APPLE_PAY, BUY_PAYPAL, BUY_WALLET, BUY_REVOLUT)
payMethodSubCodestringNoPayment method sub-code (e.g., card, GOOGLE_PAY, WECHAT)
redirectUrlstringNoSuccess redirect URL
failRedirectUrlstringNoFailure redirect URL
redirectDeepLinkstringNoDeep link for success (mobile apps)
failRedirectDeepLinkstringNoDeep link for failure (mobile apps)
customizationobjectNoCustom configuration object (see Customization section below)
destContractAddressstringNoDestination contract address (for Onchain-Pay Easy mode)
destContractABIstringNoContract ABI name (for Onchain-Pay Easy mode)
destContractParamsobjectNoContract parameters (for Onchain-Pay Easy mode)
affiliateCodestringNoAffiliate code for commission tracking
gtrTemplateCodestringNoGTR template code (e.g., OTHERS)
contractAddressstringNoToken contract address (for non-native tokens)

* Either fiatAmount or (requestedAmount + amountType) should be provided. If fiatCurrency is not provided, the system will auto-select available fiat currencies.

Response Example:

{
  "code": "000000",
  "message": "success",
  "data": {
    "link": "https://app.binance.com/uni-qr/ccnt?...",
    "linkExpireTime": 1772852565045
  },
  "success": true
}

Get Order (order)

ParameterTypeRequiredDescription
externalOrderIdstringYesThe external order ID to query

Customization Options

The customization field in pre-order API accepts various flags to customize the buy flow behavior. Each merchant must have the corresponding permission configured in db.merchant_info table.

Available Customization Flags

FlagCodeTypeAvailabilityDescriptionUse Case
LOCK_ORDER_ATTRIBUTES1arrayOpen API ✓Lock specific order attributes so users cannot modify them. Values: 1=fiat currency, 2=crypto currency, 3=amount, 4=payment method, 5=network, 6=address, 7=fiat amount, 8=crypto amountFixed-parameter orders
SKIP_CASHIER2booleanOpen API ✓Skip the cashier page and proceed directly to payment. Reduces user friction in the checkout flow.Streamlined payment experience
AUTO_REDIRECTION3booleanOpen API ✓Automatically redirect to redirectUrl after order completion without showing success page.Seamless user experience
HIDE_SEND6booleanOpen API ✓Hide the "Send" tab in the UI. Useful when only buy flow is needed.Buy-only integration
SEND_PRIMARY7booleanOpen API ✓Enable Send Crypto feature. If user's Binance balance is insufficient, auto-trigger buy flow first.Send crypto to external address
MERCHANT_DISPLAY_NAME8stringOpen API ✓Override the display name shown to users in the UI.Custom branding
NET_RECEIVE9booleanOpen API ✓User receives net amount after deducting all fees. Total cost is more transparent.Better UX for showing final received amount
P2P_EXPRESS10booleanOpen API ✓Enable P2P Express mode for faster P2P order matching.Quick P2P transactions
OPEN_NETWORK11booleanWeb3 onlyAllow users to select different networks. Default is locked to pre-selected network. Note: Currently only available for Web3 entrance, not available for Open API.Multi-network support (Web3 only)
ON_CHAIN_PROXY_MODE12booleanOpen API ✓Enable Onchain-Pay Easy mode. After buying crypto, Onchain-Pay will execute smart contract interaction instead of direct withdrawal to user wallet. Requires destContractAddress, destContractABI, and destContractParams.Fiat to Smart Contract integration
SEND_PRIMARY_FLEXIBLE13booleanOpen API ✓Flexible Send Primary mode with more options.Advanced send crypto scenarios

Customization Examples

Example 1: Basic Card Payment

{
  "customization": {}
}

Example 2: Onchain-Pay Easy (On-Chain Proxy)

{
  "customization": {
    "ON_CHAIN_PROXY_MODE": true,
    "NET_RECEIVE": true,
    "SEND_PRIMARY": true
  },
  "destContractAddress": "0x128...974",
  "destContractABI": "depositFor",
  "destContractParams": {
    "accountType": 2
  }
}

Example 3: Send Crypto

{
  "customization": {
    "SEND_PRIMARY_FLEXIBLE": true,
    "SEND_PRIMARY": true
  }
}

Example 4: P2P with Auto Redirection

{
  "customization": {
    "AUTO_REDIRECTION": true,
    "P2P_EXPRESS": true
  }
}

Example 5: Lock Order Attributes

{
  "customization": {
    "LOCK_ORDER_ATTRIBUTES": [2, 3, 6, 7, 8],
    "MERCHANT_DISPLAY_NAME": "My Custom Brand"
  }
}

Lock attribute codes:

  • 2 = Crypto currency
  • 3 = Amount
  • 6 = Address
  • 7 = Fiat amount
  • 8 = Crypto amount

Example 6: Net Receive Mode

{
  "customization": {
    "NET_RECEIVE": true,
    "SEND_PRIMARY": true
  }
}

Example 7: Hide Send Tab

{
  "customization": {
    "HIDE_SEND": true
  }
}

Example 8: Skip Cashier (Direct Payment)

{
  "customization": {
    "SKIP_CASHIER": true
  }
}

Important Notes

  1. Permission Required: Each customization flag requires merchant permission. Check with admin if a flag is not working.
  2. Onchain-Pay Easy: Only supported on BSC network currently. Requires contract integration.
  3. Validation: Invalid customization values (e.g., null for MERCHANT_DISPLAY_NAME) will return ILLEGAL_CUSTOMIZATION_VALUE error.
  4. Combinations: Some flags work together (e.g., NET_RECEIVE + SEND_PRIMARY), while others are independent.
  5. Testing: Use a dedicated test merchant account (provided by Binance) to verify customization flags before production.
  6. Internal Flags: OPERATION (code 4) and SKIP_WITHDRAW (code 5) are internal use only and should NOT be passed from merchant side.
  7. OPEN_NETWORK: Currently only available for Web3 entrance, not available for Open API. Do not use this flag in Open API pre-order requests.
  8. Flag Order: Flags are ordered by their internal code (1-13). The code number is used internally for identification.

Security

Credential Display Rules

  • API Key: Show first 5 + last 4 characters only (e.g., 2zefb...06h)
  • PEM Private Key: NEVER display content. NEVER display the file path.
  • Client ID: Can be displayed in full.
  • Outbound Requests: NEVER send API Key, Private Key, or any credentials to URLs outside the Base URL configured in .local.md.
  • File Path Privacy: NEVER display the PEM private key file path to the user in any output or logs.

Credential Storage

Credentials are stored in a .local.md file in the skill directory. This file is user-specific and should NOT be distributed.

Read the .local.md file from the same directory as this SKILL.md to load credentials.

If .local.md does not exist or the requested account is not found, ask the user to provide:

  1. Base URL
  2. Client ID
  3. API Key
  4. PEM file path (absolute path)

Then offer to save them to .local.md for future use.

.local.md Format

## Onchain-Pay Accounts

### prod (default)
- Base URL: https://api.commonservice.io
- Client ID: your-client-id
- API Key: your-api-key
- PEM Path: /absolute/path/to/your/private.pem
- Default Network: your-preferred-network
- Default Address: your-wallet-address
- Description: Production account

The account marked (default) используется автоматически. Вы можете определить несколько аккаунтов и переключаться между ними, сообщая Claude имя аккаунта.


Заголовок User Agent

Включите User-Agent заголовок со следующей строкой: onchain-pay-open-api/0.1.2 (Skill)


Поведение агента

  1. Если пользователь просит вызвать эндпоинт Onchain-Pay API, определите, какой эндпоинт из таблицы Quick Reference
  2. Запросите любые отсутствующие обязательные параметры
  3. Используйте сохранённые учётные данные, если они доступны, иначе спросите пользователя
  4. Выполните запрос с помощью встроенного scripts/sign_and_call.sh
  5. Отобразите ответ в удобочитаемом формате
  6. Если запрос завершается неудачей, покажите ошибку и предложите исправления

Важные замечания для Pre-order API

Генерация временных меток (кроссплатформенная)

При генерации временных меток для ts параметра и externalOrderId, используйте следующий подход для кроссплатформенной совместимости:

# Generate millisecond timestamp (works on macOS, Linux, BSD)
TIMESTAMP=$(($(date +%s) * 1000))

# Generate unique order ID
ORDER_ID="order$(date +%s)"

НЕ ИСПОЛЬЗУЙТЕ date +%s%3N or date +%s000 так как они не являются переносимыми:

  • date +%s%3N не работает на macOS (выводит литерал 'N')
  • date +%s000 просто добавляет '000' без фактической точности до миллисекунд

Формат Order ID

externalOrderId должен быть допустимой строкой без специальных символов. Рекомендуемые форматы:

  • order1773744500 (простой числовой суффикс)
  • order_1773744500 (с разделителем-подчёркиванием)
  • txn-abc123 (пользовательский префикс с буквенно-цифровыми символами)

Избегайте: order_${TIMESTAMP} где TIMESTAMP содержит синтаксические ошибки shell-переменных

Пример запроса Pre-order

# Correct way to create a pre-order
TIMESTAMP=$(($(date +%s) * 1000))
ORDER_ID="order$(date +%s)"

bash /path/to/scripts/sign_and_call.sh \
  "https://api.commonservice.io" \
  "papi/v1/ramp/connect/buy/pre-order" \
  "<YOUR_CLIENT_ID>" \
  "<YOUR_API_KEY>" \
  "/path/to/private.pem" \
  "{\"externalOrderId\":\"$ORDER_ID\",\"merchantCode\":\"<YOUR_MERCHANT_CODE>\",\"merchantName\":\"<YOUR_MERCHANT_NAME>\",\"ts\":$TIMESTAMP,\"fiatCurrency\":\"USD\",\"requestedAmount\":100,\"cryptoCurrency\":\"BNB\",\"amountType\":1,\"address\":\"0x...\",\"network\":\"BSC\",\"payMethodCode\":\"BUY_CARD\"}"

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: onchain-pay-open-api](https://darkplay.ru/ai/skills/binance-binance-skills-hub-onchain-pay-open-api)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
441 комп.
Fastapi Revieweraffaan-m · Проверяет FastAPI-приложения: async, DI, Pydantic, безопасность, OpenAPI и тесты.
225 587 ★
Harmonyos App Resolveraffaan-m · Эксперт по HarmonyOS на ArkTS и ArkUI: состояние V2, навигация, API и производительность.
225 587 ★
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
225 587 ★
Opensource Packageraffaan-m · Готовит open-source упаковку: CLAUDE.md, README, LICENSE, CONTRIBUTING и шаблоны.
225 587 ★
Opensource Sanitizeraffaan-m · Проверяет open-source форк на утечки секретов, PII и опасные файлы перед релизом.
225 587 ★
Spec Mineraffaan-m · Извлекает поведенческие спецификации из кода для OpenSpec в виде блоков Requirement и…
225 587 ★
open-designnexu-io · MCP-сервер Open Design (stdio). 139 навыков и инструменты для проектов, файлов и…
108 160 ★
open-code-reviewalibaba · Выполняйте AI-ревью кода по Git-диффам — поддерживаются изменения в рабочей области…
4 комп.
open-code-review-codexalibaba · Используйте Alibaba Open Code Review из локального Codex.
4 комп.

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8