0% found this document useful (0 votes)
18 views22 pages

On-chain Transfer Integration Guide v2

Uploaded by

Bump Bump
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views22 pages

On-chain Transfer Integration Guide v2

Uploaded by

Bump Bump
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

BINANCE PAY

API INTEGRATION GUIDE

On-chain Transfer
Table of Content
Get Started 3
How does it work 3
Generate Key Pairs 3
API Protocol Rules and Requests Header 3
Request Header 4
How to Generate API Signature 4
Query Network & Supported Currency 5
Pre-Create Transaction 7
API Integration (Universal Link) 9
How does it work 9
Payment Result 9
Android - UniversalUrl 11
iOS - UniversalUrl 14
SDK Integration 16
Android 16
Requirements 16
Installation 16
Usage 16
On-chain Transfer 17
iOS 18
Requirements 18
Installation 18
Usage 18
FAQ 20
Get Started
Binance Pay on-chain transfer integration is available in both SDK and API integration.

For a seamless experience, you can integrate with our SDK. Alternatively, you can also trigger
the Binance App with our universalUrl returned in our API.

How does it work


1. Users select the Binance Pay option on your app/website.
2. Call the API to obtain transactionId to trigger Binance App
3. Redirect the user to Binance App, the address will be auto populated
4. User will enter the amount and complete the transaction with Binance Pay
5. The transaction request will be processed within the estimated completion time.

Generate Key Pairs


Binance Pay On-chain Transfer uses the ECDSA key pairs to authenticate API requests. Please
generate a sets of ECDSA Keys and share the public key with Binance Pay Integration Team. Do
not share the private key and remember to handle it with care and keep it secure at all times.

Note:
To ensure that the public key you generate matches with the format required by Binance Pay,
we suggest you generating the ECDSA key pairs by the following instruction:

openssl ecparam -name prime256v1 -genkey -out private_key.pem


openssl ec -in private_key.pem -pubout -out public_key.pem

openssl ec -pubin -in public_key.pem -outform der -out public_key.der

API Protocol Rules and Requests Header


For security purposes, please follow the protocol rules and steps to create your API requests.

Rule Description

Protocol Use HTTPS for secure transactions

Content-Type application/json

Character Encoding UTF-8


Signature Algorithm ECDSA SHA256

Endpoint https://www.binance.com/bapi/pay

Request Header
Attributes Type Required Description

content-type string Y application/json

BinancePay-Timestamp long Y UnixTimestamp in milliseconds that the


requests send, guarantee the machine
time is sync with the network

BinancePay-Nonce string Y A random string generated by


merchants. Must be 32 characters.
e.g.
5RhaTrZPhknNv0kDSA2UQ67cPMVNS4s
A

BinancePay-Signature string Y API Signature. Please see the next step


for how to generate

How to Generate API Signature

Step 1. Build the content


String payload = timestamp + "\n" + nonce + "\n" + body + "\n";

Step 2. Sign the content


String signature = base64(ecdsa("sha256", payload, privateKey));
Query Network & Supported Currency
You can use the “Query Network & Supported Currency'' API to get the supported currencies
and networks that are available for the on-chain transfer.

End Point
POST /v1/friendly/binance-pay/withdraw/networks

Request Parameter
Attributes Type Required Description

source string Y Fixed Value - Provided by Binance Pay


Team once public key is submitted and
configured by Binance Pay Team

Request Example
{
"source": "test"
}

Response Parameter
Attributes Type Required Description

code string Y Request result code

data Object Y Response Body, Refer to Child Attribute

success Boolean Y True or False

Child Attribute

Attributes Type Required Description

networks List<String> Y List of available networks

coinDetail List<coinDetail> Y Refer to


coinDetail Attribute

Attributes Type Required Description

coin String Y Coin Name

coinDetail List<networkDetailList> Y Refer to Attribute List

networkDetailList Attribute

Attributes Type Required Description

network String Y Network Symbol

networkName String Y Network full name

withdrawEnable Boolean Y Is supported for on-chain transfer

contractAddress String Y Contract address for the coin

Response Example
{
"code": "000000",
"data": {
"coinDetail": [{
"coin": "USDT",
"netWorkDetailList": [{
"network": "BSC",
"networkName": "BNB Smart Chain (BEP20)",
"withdrawEnable": true,
"contractAddress":
"0x55d398326f99059ff775485246999027b"
}, {
"network": "ETH",
"networkName": "Ethereum (ERC20)",
"withdrawEnable": true,
"contractAddress":
"0xdac17f958d2ee523a2206206994597c13d831e"
}]
}],
"networks": ["BSC", "XRP", "XTZ", "XVG", "XZC", "YOYO", "ZEC", "ZEN", "ZIL"]
},
"success": true
}
Pre-Create Transaction
You can use the “pre-create transaction'' API to get the transactionId that will be used in
SDK integration and universalLinkUrl that will be used for redirection.

End Point
POST /v1/friendly/binance-pay/withdraw/pre-create

Request Parameter
Attributes Type Required Description

source string Y Fixed Value - Provided by Binance Pay Team


once public key is submitted and configured

currency string Y Currency for the transaction

network string Y Network for the transaction

address string Y Receiving wallet address

Request Example
{
"source": "test",
"currency": "USDT",
"network": "ETH",
"address": "0xdac17f958d2ee523a2206206994597c13d831e"
}

Response Parameter
Attributes Type Required Description

code string Y Request result code

data Object Y Response Body, refer to here for data list

success Boolean Y True or False

Child Attribute

Attributes Type Required Description


transactionId String Y Transaction ID (used for SDK)

universalLinkUrl String Y Link to build on for redirection of user to


Binance App to complete transaction. Refer to
here for on integration for universalLink.

Response Example
{
"code": "000000",
"data": {
"transactionId": "a63cd022642649c49a6f94b9811cf442"
“universalLinkUrl”:” https://app.binance.com/payment”
},
"success": true
}

With the transactionId, you can redirect user to Binance App for complete payment by
integrating with Binance Pay SDK. Click here to refer to the SDK integration guide.

Alternatively, with the transactionId and universalLinkUrl, you can build the
universalLinkUrl and redirect user to Binance App with the link. Click here to refer to the guide
on how to build the universalLinkUrl.
API Integration (Universal Link)
Apart from SDK integration, you can integrate via API to trigger Binance App for user to
complete the transaction with the universal link returned.

How does it work


1. Users select the Binance Pay option on your app/website.
2. You will call the API to obtain transactionId and universalLinkUrl
3. Build the link by appending the base64url encoded deeplink to the universal link
4. Redirect the user to the universal link (Binance App) to complete the transaction.
5. With the redirectUrl, we will redirect user back to you
6. Handle the redirectUrl from Binance app to get the result

Parameters for the Universal Link


The universalLinkUrl return will be something like: https://app.binance.com?_dp=xxx

You will need to build the _dp to complete the link and redirect users to Binance for payment.

Key Name Type Required Description

_dp Deeplink String Y This value needs to be encoded with


Base64

Payment Result
Binance app will redirect users back to your app/website via the redirectUrl you indicated in
the _dp, after the payment is done or canceled. A query will be passed in your redirectUrl. You
can get the result by parsing the url from the Binance.

Binance will opens your app/website using the url with this format:
{REDIRECT_URL}?code=0&message=success

Code and message will be included in your redirectUrl as a query, you can parse them to get the
payment result.

Example
If you set redirectUrl as “https://www.test.com”
Once the user finishes or cancels the payment, we will redirect the user to
“{REDIRECT_URL}?code=0&message=success”, this will be the url shown on the user's
browser.

RedirectUrl Example
https://www.test.com?code=xxx&message=xxx

RedirectUrl Query Attribute

Attributes Type Required Limitation Note

code Int Y 0 for Success If no code is returned refer to user have


1 for Pending canceled the payment
others/”” for Failed

message String N information on why payment fails, this


field might be empty

● If the code is 0 or 1 = payment success, otherwise it means that the payment fails.
● The message is optional, you can get more information from it if your payment fails.
● The result returned is for display purpose only. Always double check the result.
Android - UniversalUrl
Please note for Android and iOS the redirection url might differ. Please refer to the guide below
for more information on Android.

The _dp value before encoded with Base64 will be like

bnc://app.binance.com/payment/secpay?
extra_key_api_type=xxx&transactionId=xxx&nonce=xxx&sign=xxx&timeStamp=xxx&redire
ctUrl=xxx

Key Name Type Required Description

extra_key_ TradeType string Y This value should always be on-chain-transfer


api_type

transaction TransactionId string Y Order’s transaction ID from pre-create


Id transaction API.

nonce BinancePay- string Y A random string generated by you. Must be 32


Nonce characters (32 bytes).
e.g. 5RhaTrZPhknNv0kDSA2UQ67cPMVNS4sA

sign BinancePay-S string Y Use ECDSA SHA256, refer here for more
ignature information.

timeStamp BinancePay-T string Y UnixTimestamp in milliseconds that the


imestamp requests send, guarantee the machine time is
sync with the network. Binance Pay only
process request within 1s

redirectUrl redirectUrl string Y url we will redirect to when the user


finishes/cancels the payment.

How to generate Signature


Call the pre-create API to get the transactionId.
Use this transactionId to generate the signature along with the nonce and timestamp. Please
sort by field name's ascii code ascending and then concat them by delimiter "&".

Example:
nonce=oDlQrz6Vlo9RQHBbgn0j&timestamp=1663731699460&transactionId=2c55ed01caef4
3a18fa81d010f7b96cb

Use private key to do signature; ECDSA SHA256; base64 encode*.


Usage

If you are calling from JS


To trigger the Binance App's pay action:
<a href="https://app.binance.com?_dp=xxx">XXXX</a>
<iframe src="https://app.binance.com?_dp=xxx"></iframe>
window.location.href= "https://app.binance.com?_dp=xxx";
Please do remember to set the redirectUrl as your return page.

Payment Result
If you have set the redirectUrl as “https://www.test.com” Once the user finishes or cancels the
payment, we will redirect the user to the redirectUrl. The below url will display the user's
browser, along with the queries.
https://www.test.com?code=xxx&message=xxx

Handle Payment Result


To handle the payment results after payment is completed.

1. Android - Kotlin
fun test(
context: Context,
transactionId: String,
nonce: String,
sign: String,
timestamp: String,
redirectUrl: String
){
val params =
"transactionId=${transactionId}&nonce=${nonce}&sign=${sign}&timeStamp=${timestamp}&redirec
tUrl=${redirectUrl}"
val uri =
Uri.parse("bnc://app.binance.com/payment/secpay?extra_key_api_type=on-chain-transfer&$param
s")
val encodedDp = Base64.encodeToString(uri.toString().toByteArray(), Base64.NO_WRAP)
val intent = Intent(Intent.ACTION_VIEW, "https://app.binance.com?_dp=$encodedDp".toUri())
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}

2. Android - Webpage
If you want to go back to a web page once finished, you may refer to the JS step.
3. Android - Native Page
If you want to go back to an android native page once the transaction is completed.
You should register your activity in your mainfest.xml file like below.
<activity
android:name=".TestActivity"
android:exported="true">
<intent-filter
android:autoVerify="true"
android:exported="true">
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />


<category android:name="android.intent.category.BROWSABLE" />

<data
android:host="app.test.com"
android:scheme="test" />
</intent-filter>
</activity>

You can then set your redirectUrl as “test://app.test.com”. You will get an intent at your Activity
once the user finishes the payment.

You can get code and message on Kotlin as below:


val data = intent?.data
val code = data.getQueryParameter("code")?.toIntOrNull()
val message = data.getQueryParameter("message").orEmpty()

RedirectUrl Query Attribute

Attributes Type Required Limitation Note

code Int Y 0 for Success If no code is returned refer to user have


1 for Pending canceled the payment
others/”” for Failed

message String N information on why payment fails, this


field might be empty

Note: If there is no code within, which means the user has canceled the payment. The result we
return is for display purposes, always check the final result.
iOS - UniversalUrl
Please note for iOS and Android the redirection url might differ. Please refer to below guide for
more information on iOS.

Usage
Please use this universal link to trigger the Binance App
https://app.binance.com?_dp={BASE64URL_ENCODED_DEEPLINK}
We add the ended deeplink as a query parameter in the universal link.

You should provide the BASE64URL_ENCODED_DEEPLINK in the following format:


bnc://app.binance.com/payment/onchainpay?transactionId=
{TRANSACTION_ID}&nonce={NONCE}&timeStamp={TIMESTAMP}&sign=
{SIGN}&redirectUrl={REDIRECT_URL}

Parameter Description

Key Name Type Required Description

transaction TradeType string Y The order’s transaction id received from


Id pre-create transaction API.

nonce BinancePay- string Y A random string generated by you. Must be 32


Nonce characters (32 bytes).
e.g. 5RhaTrZPhknNv0kDSA2UQ67cPMVNS4sA

sign BinancePay-S string Y Use ECDSA SHA256, please refer to below on


ignature how to generate signature.

timeStamp BinancePay-T string Y UnixTimestamp in milliseconds that the


imestamp requests send, guarantee the machine time is
sync with the network. Binance Pay only
process request within 1s

redirectUrl redirectUrl string Y url we will redirect to when the user


finishes/cancels the payment.

How to generate Signature


Call the pre-create API to get the transactionId.
Use this transactionId to generate the signature along with the nonce and timestamp. Please
sort by field name's ascii code ascending and then concat them by delimiter "&".
Example:
nonce=oDlQrz6Vlo9RQHBbgn0j&timestamp=1663731699460&transactionId=2c55ed01caef4
3a18fa81d010f7b96cb

Use private key to do signature; ECDSA SHA256; base64 encode*.

How to use base64 url to encode your deeplink:


extension Data {
func base64URLEncodedString() -> String {
let result = base64EncodedString()
return result.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}}
deeplink.data(using: .utf8)?.base64URLEncodedString()

Example
Deeplink:
bnc://app.binance.com/payment/onchainpay?
transactionId=2730aefde812497795b8318b1cf810f3&nonce=enG1XBQDJCXOlAEdZM
vS&timeStamp=1663941125810&sign=TUVVQ0lEUGd5VkI3ekxJK3RnODhqb0diQ09B
d3JlVzZFTURBdHZaNFQ3byt3N1FWQWlFQTdwdjE5TG56eU1aSlVqTGJGQVJuYmFK
ZGV1TDZZRU9SMG5iOFlJcFBjbE0&redirectUrl=testapp://result/onchain/result

Universal Link:
https://app.binance.com?_dp=Ym5jOi8vYXBwLmJpbmFuY2UuY29tL3
BheW1lbnQvb25jaGFpbnBheT90cmFuc2FjdGlvbklkPTI3MzBhZWZkZTgxMjQ5Nzc5N
WI4MzE4YjFjZjgxMGYzJm5vbmNlPWVuRzFYQlFESkNYT2xBRWRaTXZTJnRpbWVTd
GFtcD0xNjYzOTQxMTI1ODEwJnNpZ249VFVWVlEwbEVVR2Q1VmtJM2VreEpLM1JuT0RocWI
wZGlRMDlCZDNKbFZ6WkZUVVJCZEhaYU5GUTNieXQzTjFGV1FXbEZRVGR3Z
GpFNVRHNTZlVTFhU2xWcVRHSkdRVkp1WW1GS1pHVjFURFpaUlU5U01HNWlPRmx
KY0ZCamJFMCZyZWRpcmVjdFVybD10ZXN0YXBwOi8vcmVzdWx0L29uY2hhaW4vcm
VzdWx0

Payment Result
Binance App will redirect customers back to the redirectUrl you specify, after the payment is
done or canceled. You can get the result by parsing the url from the Binance app.

Binance app opens your app/website by using the url with this format:
{REDIRECT_URL}?code=0&message=success

Binance app adds the code and message as the query into the redirectUrl , you can parse them
to get the payment result.
If the code is 0 or 1 , it means your payment success, otherwise it means your payment failed.

The message is optional, you can get more information from it if your payment fails.
SDK Integration
For more information, you can refer to our documentation on standard B2C SDK integration.

Android
Requirements
● Android 4.1+ Support
● AndroidX

Installation
1. Get the SDK zip file from Binance Pay Integration Team
2. Add binance_pay_sdk_v1.0.0.aar into libs directory
3. Add dependence for app module:
android{
repositories {
flatDir {
dirs 'libs'
}}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation (name: 'binance_pay_sdk_v1.2.0', ext: 'aar')
}

4. Sync project

Usage
1. Create BinancePayListener
class PayListener : BinancePayListener {
override fun onSuccess() {
// When the payment is successful, this will be called.
}

override fun onCancel() {


// When the payment is canceled, this will be called.
}

override fun onFailure(code: Int, message: String) {


// When there is an error in the payment process,this will be called.
}
}
val listener = PayListener()

On-chain Transfer
1. Create an activity to get the transfer result for the old version of Binance App.
//sample code
class TransferResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
BinancePayFactory.getBinancePay(context).handleResult(intent)
finish()
}
}

2. Configuration in the AndroidManifest.xml.


//sample code
<queries>
<package android:name="com.binance.dev" />
</queries>
<application>
<activity android:name=".TransferResultActivity">
<intent-filter
android:autoVerify="true"
android:exported="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="on-chain.transfer.binance"//just sample
android:scheme="wc"//just sample />
</intent-filter>
</activity>
</application>

3. Pay
val binancePay = BinancePayFactory.getBinancePay(context)
val redirectUrl = "wc://on-chain.transfer.binance" //same with the configuration in the
AndroidManifest.xm
binancePay.pay(transactionId, nonce, sign, timeStamp, redirectUrl, listener)redirectURL

Note:
De-fi Wallet backend calls pre-create API and gets transactionId, and generates the
signature using this transactionId, nonce and timestamp. Please sort by field
name's ascii code ascending and then concat them by delimiter "&".

Example
nonce=oDlQrz6Vlo9RQHBbgn0j&timestamp=1663731699460&transactionId=2c55ed0
1caef43a18fa81d010f7b96cb

Use private key to do signature; ECDSA SHA256; base64 encode*.


iOS
Requirements
● iOS 10+
● Swift 5.1+

Installation
1. Get BinancePaySDK.xcframework
2. Add BinancePaySDK.xcframework into Frameworks, Libraries and Embeded Content of
your target
3. Embed Type should be Embed & Sign

Usage
1. CreateRequestParameters:
// On Chain Payment
public struct OnChainInitParameters {
public let transactionId: String
public let timestamp: Int64
public let sign: String
public let nonce: String
public let redirectScheme: String
}

Note:

De-fi Wallet backend calls pre-create API and gets transactionId, and generates the
signature using this transactionId, nonce and timestamp. Please sort by field name's
ascii code ascending and then concat them by delimiter "&".

Example:
nonce=oDlQrz6Vlo9RQHBbgn0j&timestamp=1663731699460&transactionId=2c55ed0
1caef43a18fa81d010f7b96cb

Use private key to do signature; ECDSA SHA256; base64 encode*.


*If you’re facing a signature error, please try encoding with base64url instead.

2. Call API:
BinancePaySDK will show an alert if the user does not have the Binance app installed on
his/her device. The alert will be shown on the containerView.
BinancePay.shared.pay(with: parameters, containerView: self.view) { (result) in
switch result {
case .success:
print("success")
case .failure(let error):
print("failure \(error)")
}
}

3. ErrorTypes. Here are the errors you may get from BinancePaySDK :
public enum PayError: Error {
case invalidParameters(OrderInitParametersError)
case binanceAppNotInstalled
case binanceAppNotSupported
case openAppFailed
case fromBinanceApp(code: Int, message: String)
}

public enum OrderInitParametersError: Error {


case invalidTimestamp
case invalidNonceStr
case invalidCertSn
case invalidSign
case invalidRedirectScheme
}

4. Language
public enum languageMode {
case automatic // SDK automatically use the same language as iOS
system
case manual(Language: Language) // You can specify the language
}
BinancePay.shared.languageMode = .automatic
FAQ
SDK Integration FAQ
If you have any issues on the integration, please refer to our FAQ.

If it's a redirection issue with iOs even if the scheme is updated, please add all the queried URL
Schemes as shown:

You might also like