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), it is only provided to close ecosystem partner now, please reach to our business team for more detail oauth-apply@binance.com.

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#
  • Make sure that your project already contains(project > build.gradle).
repositories {    jcenter()}
  • Add the dependencies in the build.gradle file(project > module > build.gradle).
dependencies {    implementation 'com.binance.android:binance-opensdk:0.3.1'}
  • 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 onCancel() {        Log.d(LOG_TAG, "onCancel")    }
    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 onCancel() {        Log.d(LOG_TAG, "onCancel")    }
    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 tokens、Calling 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#

If the user authorize through the Binance App, the result is received in the BinanceListener. If through Web login, the specified page would be opened by DeepLink and the result is returned.To receive the authorization result properly, you need to add the following code to the onActivityResult method of the Activity class that calls the authorization interface

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {    super.onActivityResult(requestCode, resultCode, data)    binanceAPI?.handleResp(requestCode, resultCode, 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 onCancel will be called when the user cancels the authorization.

    • 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 If the user log in through the Web, 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. Sample:

class LoginActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        val code = intent?.data?.getQueryParameter("code")        val state = intent?.data?.getQueryParameter("state")        Log.d(LOG_TAG, "code $code")    }
   override fun onNewIntent(intent: Intent?) {        super.onNewIntent(intent)        val code = intent?.data?.getQueryParameter("code")        val state = intent?.data?.getQueryParameter("state")        Log.d(LOG_TAG, "code $code")    }
    ......}

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.