Skip to main content

Integrate Binance Login with your App

Binance Open SDK#

中文文档

Binance Open SDK (hereinafter called SDK) provides two authorization ways, through Binance ap or web page, which is convenient to authorize the Binance account safely and quickly. SDK will adopt different ways according to the situations and users' choices.

To begin, your app should identify the needed permissions (scope) firstly. Setup and register your app with Binance Accounts, and get your client_id . For now, Binance Login(Oauth2.0), is only provided to close ecosystem partners now. Please reach to our business team for more details.

Process Introduction#

The Binance app will be called to authorize when the user clicks to login with the Binance account in the app. If the user does not install the Binance app supported the authorization,there would be a prompt for the user to authorize through the browser or download the Binance app. The result would be returned to the app after the authorization is finished.

img

Integrate SDK for Android#

1. Import SDK#
  1. Download binance_open_sdk_v0.5.0.aar

  2. Add binance_open_sdk_v0.5.0.aar into libs directory

  3. Add dependence for app module, just like this:

    dependencies {    implementation fileTree(include: ['*.jar'], dir: 'libs')    implementation (name: 'binance_open_sdk_v0.5.0.aar', ext: 'aar')}
  4. Sync project

  • Set clientID in the AndroidManifest.xml
<application>    <meta-data        android:name="BINANCE_CLIENT_ID"        android:resource="clientID"/></application>

2 Usage#

There are two flows of authorization.

  1. Authorization Code Flow, for apps with back-end.
  2. PKCE Flow, for apps without back-end services.

2.1 Authorization Code Flow#

// The context must be an activity.val binanceAPI = BinanceAPIFactory.createAPI(context)val oauthParams = OAuthParams(redirectUri, scope, state)binanceAPI.authorize(oauthParams, object : BinanceListener {    override fun onSuccess(code: String, state: String) {        Log.d(LOG_TAG, "code $code")    }
    override fun onError(errCode: Int) {        Log.d(LOG_TAG, "errCode $errCode")    }})
  • Aauthorize Parameter

    parameterdescription
    redirectUriThe URL in your application where users will be redirected after web authorization.
    scopeList of scopes enum your application requests access to, with comma (,) seperated.
    stateThe CSRF token to protect against CSRF (cross-site request forgery) attacks.

2.2 PKCE Flow#

The PKCE extension prevents an attack where the authorization code is intercepted and exchanged for an access token by a malicious client, by providing the authorization server with a way to verify the same client instance that exchanges the authorization code is the same one that initiated the flow. For more details, refer to https://tools.ietf.org/html/rfc7636

// The context must be an activity.val binanceAPI = BinanceAPIFactory.createAPI(context)val oauthParams = OAuthParams(redirectUri, scope, state)val codeVerifier = UUID.randomUUID().toString()val codeChallenge = generateCodeChallenge(codeVerifier)val challengeParams = ChallengeParams(codeChallenge, "S256")binanceAPI.authorize(oauthParams, challengeParams, object : BinanceListener {    override fun onSuccess(code: String, state: String) {        Log.d(LOG_TAG, "code $code")    }
    override fun onError(errCode: Int) {        Log.d(LOG_TAG, "errCode $errCode")    }})

generateCodeChallenge: The SDK provides a method, encrypting the codeVerifier, to make it quickly for developers to get codeChallenge. Java could be called through BinanceKit.generateCodeChallenge(codeVerifier).

Access to accessToken and user info: Exchange authorization code for refresh and access tokensCalling Binance APIs

parameterdescription
redirectUriThe URL in your application where users will be redirected after web authorization.
scopeList of scopes enum your application requests access to, with comma (,) seperated.
stateThe CSRF token to protect against CSRF (cross-site request forgery) attacks.
codeVerifierThe random secret code created
code_challengeThe URL in your web application where users will be redirected after authorization. This value needs to be URL encoded.

Receiving returned data#

  • BinanceListener

    • When it's successfully authorized, the onSuccess will be called.code is the authorization result and state is the parameter passed while calling the authorize .

    • The onError will be called if the authorization fails, and errCode is the error code.

      errCodedescription
      10000Binance App not installed
      10001Binance App version not supported
      10002client_id is null
      10003Parameter error
      10004App verification failed (app information is inconsistent with registration information)
  • DeepLink After the authorization is completed, the specified page (the page corresponding to the redirectUri during registration) will be opened through the method of DeepLink, and this needs to be in the onCreate method and onNewIntent method of the page processing the authorization result, the format of the successful authorization DeepLink is {redirectUri}?code=xxxxx&state=xxxxx&error=xxxxx. Sample:

class LoginActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        binanceAPI.handleResp(intent)    }
   override fun onNewIntent(intent: Intent?) {        super.onNewIntent(intent)        binanceAPI.handleResp(intent) // call `handleResp` func to proceed response. Nothing happens if this intent is not from binance.    }
    ......}

Integrate SDK for iOS#

Requirments#

  • Binance iOS App: 2.17.0+
  • iOS system version: iOS10+

Installation#

Cocoapods#
Manual#
  1. Add BinanceOpenSDK.framework to your xcode project.
  2. Open you xcode project, select to Build Phases tab.
  3. Add BinanceOpenSDK.framework to Embed Frameworks.

Usage#

BundleID & AppID#

You should use valid BundleID and AppID in your project.

Info.plist#
  1. Open Info.plist in xcode project.
  2. Add account.binance.oauth.suppor and com.binance.app.binance to LSApplicationQueriesSchemes.
  3. Add an new item(key is BinanceAppID, value is your AppID) to Info.plist.
APIs#
Authorize#

There are two flows of authorization.

  1. Authorization Code Flow, for apps with back-end.
  2. PKCE Flow, for apps without back-end services.

They all use same function(authorize(with:, baseAt:, onSuccess:, onFailure:)) to send an oauth request to Binance App.

public func authorize(with parameters: OAuthParameters, baseAt container: UIView, onSuccess:((String, String) -> Void)?, onFailure: ((OAuthError) -> Void)?)
OAuthParameters#

OAuthParameters is a struct that contains the neccessory parameters of OAuth Request.

codeChallenge is SHA256 and base64 hashed value. SDK provide a function(BinanceOpenUtils.generateCodeChallendge(codeVerifier)) to do this job for you.

if you use Code Flow, just send nil to OAuthParameters, If you use PKCE Flow, you need send .s256(code: BinanceOpenUtils.generateCodeChallendge(codeVerifier)!) to OAuthParameters

public struct OAuthParameters {    public var scope: String    public var state: String    public var redirectURI: String    public var codeChallenge: CodeChallenge?}
parameterdescription
redirectUriThe URL in your application where users will be redirected after web authorization.
scopeList of scopes enum your application requests access to, with comma (,) seperated.
stateThe CSRF token to protect against CSRF (cross-site request forgery) attacks.
codeChallengecodeVerifier encypted by sha256 & base64
Handle Open URL#

Don't forget to handle openURL in AppDelegate.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {    return BinanceOpenSDK.shared.handle(openURL: url)}
SelfTest#

If you has any problem in using BinanceOpenSDK, selfTest() helps you inspect the warnings/errors in BinanceOpenSDK. selfTest() returns an optional enum named BinanceOpenSDK.Warning. If it returns nil, that means BinanceOpenSDK works well.

public enum Warning {    case invalidAppID    case invalidBundleID    case noBinanceApp    case oauth(OAuthWarning)}
Localizations#

BinanceOpenSDK supports 2 language modes:

  1. automatic(default): The language of BinanceOpenSDK depends on iOS system.
  2. manual: You can assign a language to BinanceOpenSDK

// automaticBinanceOpenSDK.shared.languageMode = .automatic
// manualBinanceOpenSDK.shared.languageMode = .manual(language: .russia)

BinanceOpenSDK supports languages below:

  • english
  • chinese
  • traditionalChinese
  • korean
  • turkish
  • vietnamese
  • spanish
  • russia
  • portuguese
  • polish
  • ukrainian
  • french
Error Type#

There are 2 kinds of error in BinanceOpenSDK, one is internal error of SDK, the other is external error received from Binance App after Binance App authorizing failed.


public enum OAuthError: Error {    case invalidBundleID    case invalidAppID    case invalidParameters    case openAppFailed    case openSafariFailed    case fromBinanceApp(type: String, desc: String)}

The case fromBinanceApp is the error received from Binance:

  • cancelled: User has cancelled the authorization manually.
  • readClientInfoFailed: Binance App read your app's information failed.
  • invaildClientInfo: You app's information is invalid.