### Authenticated API Call Example Source: https://developers.binance.com/docs/zh-CN Example of how to make an authenticated API call to Binance using a valid access token. ```APIDOC ## Authenticated API Call Example ### Description After obtaining a valid `access_token`, you can make authenticated API calls to Binance endpoints by including the token in the `Authorization` header. ### Method GET (example for user-info endpoint) ### Endpoint https://www.binanceapis.com/oauth-api/v1/user-info ### Headers - **Authorization**: `Bearer {access_token}` (Replace `{access_token}` with your actual access token) ### Request Example ```bash curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ### Response #### Success Response (200) - **code** (string) - Response code. - **message** (string) - Response message, if any. - **data** (object) - Contains user-specific data. - **userId** (string) - The user's unique identifier. - **email** (string) - The user's email address. - **success** (boolean) - Indicates if the request was successful. #### Response Example ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90", "email": "xx@xx.com" }, "success": true } ``` ``` -------------------------------- ### Example Binance OAuth Authorization URL Source: https://developers.binance.com/docs/zh-CN An example of a complete authorization URL with actual client ID, redirect URI, and code challenge values. This URL is used to initiate the OAuth 2.0 flow. ```HTTP GET https://accounts.binance.com/en/oauth/authorize? response_type=code& client_id=a28f296f2cbe6c64b4d5dec24735d39b1b6fffcf& redirect_uri=https%3A%2F%2Fdomain.com%2Foauth%2Fcallback& state=377f36a4557ab5935b36& scope=user:openId,create:apikey& code_challenge=ARU184muFVaDi3LObH5YTZSxqA5ZdYPLspCl7wFwV0U code_challenge_method=S256 ``` -------------------------------- ### Start Binance OAuth Activity (Android) Source: https://developers.binance.com/docs/login/app-integration Creates an Android Intent with the constructed Binance OAuth URL and starts the activity to initiate the authorization process. Handles cases where the URL is pre-formatted. ```java Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); ``` ```java Uri uri = Uri.parse("https://accounts.binance.com/oauth/authorize?response_type=code&scope=user:openId,create:apikey&client_id=xxxxxxxxx&redirect_uri=https%3A%2F%2Faccounts.pexpay.com%2Fen%2Foauth-handle&state=76ea8434ceca47ada566308030ef5f5c&bundleID=com.xxx.www"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); ``` -------------------------------- ### Binance OAuth Callback Redirection Example Source: https://developers.binance.com/docs/zh-CN This is an example of the redirection from Binance back to your application's redirect URI after the user grants authorization. It contains the temporary authorization code and the state parameter if provided. ```HTTP GET https://domain.com/oauth/callback? code=cf6941ae8918b6a008f1377f36a4557ab5935b36& state=377f36a4557ab5935b36 ``` -------------------------------- ### GET /oauth-api/v1/user-info - Get User Information Source: https://developers.binance.com/docs/zh-CN Retrieve information about the authenticated user using a valid access token. ```APIDOC ## GET /oauth-api/v1/user-info ### Description Retrieve information about the currently authenticated user. ### Method GET ### Endpoint https://www.binanceapis.com/oauth-api/v1/user-info ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token. Format: `Bearer {access_token}` ### Request Example ```curl curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ### Response #### Success Response (200) - **code** (string) - Response code. - **message** (string) - Response message. - **data** (object) - User information. - **userId** (string) - The unique identifier for the user. - **email** (string) - The user's email address. - **success** (boolean) - Indicates if the request was successful. #### Response Example ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90", "email": "xx@xx.com" }, "success": true } ``` ``` -------------------------------- ### GET /oauth-api/v1/user-info Source: https://developers.binance.com/docs/index Retrieve user information using a valid access token. ```APIDOC ## GET /oauth-api/v1/user-info ### Description Retrieves the authenticated user's information. Requires a valid access token in the Authorization header. ### Method GET ### Endpoint `https://www.binanceapis.com/oauth-api/v1/user-info` ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token, e.g., `Bearer {access_token}`. ### Request Example ```bash curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ### Response #### Success Response (200) - **code** (string) - Response code. - **message** (string) - Response message (null if successful). - **data** (object) - User information object. - **userId** (string) - The unique identifier for the user. - **email** (string) - The user's email address. - **success** (boolean) - Indicates if the request was successful. #### Response Example ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90", "email": "xx@xx.com" }, "success": true } ``` ``` -------------------------------- ### Get User Info API Source: https://developers.binance.com/docs/binance-open-api/apis Retrieves information about the authenticated user using an access token. ```APIDOC ## GET /oauth-api/v1/user-info ### Description Retrieves information about the authenticated user. ### Method GET ### Endpoint `/oauth-api/v1/user-info` ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer {access_token} ### Request Example ```bash curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ### Response #### Success Response (200) - **code** (string) - Response code. - **message** (string) - Response message. - **data** (object) - User data. - **userId** (string) - The user's unique identifier. - **success** (boolean) - Indicates if the request was successful. #### Response Example ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90" }, "success": true } ``` ``` -------------------------------- ### Call Binance API with Access Token (curl) Source: https://developers.binance.com/docs/index This example demonstrates how to make an authenticated API call to Binance using a valid access token. The access token is included in the 'Authorization' header as a Bearer token. ```curl curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90", "email": "xx@xx.com" }, "success": true } ``` -------------------------------- ### Call Binance APIs with Access Token (curl) Source: https://developers.binance.com/docs/index Make authenticated API calls to Binance services using a valid access token. The access token should be included in the 'Authorization' header as a Bearer token. This example demonstrates fetching user information. ```shell curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` -------------------------------- ### GET /oauth-api/v1/user-info Source: https://developers.binance.com/docs/index Retrieve user information using a valid Bearer access token. ```APIDOC ## GET /oauth-api/v1/user-info ### Description Retrieves basic information about the authenticated user using a valid access token. ### Method GET ### Endpoint https://www.binanceapis.com/oauth-api/v1/user-info ### Parameters #### Header Parameters - **Authorization** (string) - Required - The access token in the format `Bearer {access_token}`. ### Request Example (cURL) ```bash curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ### Response #### Success Response (200) - **code** (string) - Response code, '000000' for success. - **message** (string or null) - Any message associated with the response. - **data** (object) - Contains user information. - **userId** (string) - The unique identifier for the user. - **email** (string) - The user's email address. - **success** (boolean) - Indicates if the request was successful. #### Response Example ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90", "email": "xx@xx.com" }, "success": true } ``` ``` -------------------------------- ### Request Binance Access (Authorization Code Flow) Source: https://developers.binance.com/docs/index This GET request redirects users to Binance to initiate the OAuth 2.0 authorization process. It includes necessary parameters like client ID, redirect URI, and requested scopes. Ensure carriage returns are removed in production. ```http GET https://accounts.binance.com/en/oauth/authorize? response_type=code& client_id=YOUR_CLIENT_ID& redirect_uri=YOUR_REDIRECT_URI& state=CSRF_TOKEN& scope=SCOPES ``` ```http GET https://accounts.binance.com/en/oauth/authorize? response_type=code& client_id=a28f296f2cbe6c64b4d5dec24735d39b1b6fffcf& redirect_uri=https%3A%2F%2Fdomain.com%2Foauth%2Fcallback& state=377f36a4557ab5935b36& scope=user:openId,create:apikey ``` -------------------------------- ### Call Binance API with Access Token (curl) Source: https://developers.binance.com/docs/zh-CN Makes an authenticated API call to Binance services using a valid access token. The access token is included in the 'Authorization' header as a Bearer token. The example demonstrates fetching user information. ```shell curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90", "email": "xx@xx.com" }, "success": true } ``` -------------------------------- ### Get Binance User Info via OAuth 2.0 (cURL) Source: https://developers.binance.com/docs/binance-open-api/apis Retrieves user information from Binance using the OAuth 2.0 user-info endpoint. Requires an access token in the Authorization header. Returns user ID and other details in a JSON object. ```cURL curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` -------------------------------- ### Authorization Code Flow - Step 1: Redirect users to request Binance access Source: https://developers.binance.com/docs/index This step involves redirecting users to Binance's OAuth 2.0 server to request access and set authorization parameters. Your application constructs a GET request with necessary parameters like client ID, redirect URI, and requested scopes. ```APIDOC ## GET /en/oauth/authorize ### Description Redirect users to Binance to request access and set authorization parameters. ### Method GET ### Endpoint `https://accounts.binance.com/en/oauth/authorize` ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be `code`. - **client_id** (string) - Required - The client ID of your application. - **redirect_uri** (string) - Required - The URL in your web application where users will be redirected after authorization. This value needs to be URL encoded. - **state** (string) - Optional - A CSRF token to protect against CSRF attacks. - **scope** (string) - Required - A comma-separated list of scopes your application requests access to. ### Request Example ``` GET https://accounts.binance.com/en/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&state=CSRF_TOKEN&scope=SCOPES ``` ### Response Example This endpoint does not return a response body directly. It redirects the user's browser. #### Success Response (Redirection) Upon successful authorization, Binance redirects the user's browser to the `redirect_uri` with a `code` and potentially the `state` parameter. Example redirection: `GET https://domain.com/oauth/callback?code=AUTHORIZATION_CODE&state=CSRF_TOKEN` ``` -------------------------------- ### Make Authenticated Binance API Call (curl) Source: https://developers.binance.com/docs/zh-CN This snippet demonstrates how to make a request to a Binance API endpoint after obtaining a valid access token. The access token is included in the 'Authorization' header as a Bearer token. The example shows a call to the user-info endpoint and its typical JSON response structure. ```shell curl 'https://www.binanceapis.com/oauth-api/v1/user-info' \ --header 'Authorization: Bearer {access_token}' ``` ```json { "code": "000000", "message": null, "data": { "userId": "e10e20b7f20947e7bd206b15ce3dae90", "email": "xx@xx.com" }, "success": true } ``` -------------------------------- ### Step 1: Request Binance Access Source: https://developers.binance.com/docs/zh-CN Initiates the OAuth 2.0 flow by redirecting the user to Binance's authorization server. This step requires specifying your application's client ID, redirect URI, and requested scopes. It also includes parameters for PKCE (Proof Key for Code Exchange) to enhance security. ```APIDOC ## GET /en/oauth/authorize ### Description Redirect users to request Binance access and set authorization parameters. ### Method GET ### Endpoint `https://accounts.binance.com/en/oauth/authorize` ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be `code`. - **client_id** (string) - Required - The client ID of your application. - **redirect_uri** (string) - Required - The URL in your web application where users will be redirected after authorization. This value needs to be URL encoded. - **state** (string) - Optional - A CSRF token to protect against CSRF (cross-site request forgery) attacks. - **scope** (string) - Required - A comma-separated list of scopes your application requests access to. - **code_challenge** (string) - Required - Hash and base64-urlencode of `code_verifier`. - **code_challenge_method** (string) - Required - The method used for `code_challenge`, typically `S256`. ### Request Example ``` GET https://accounts.binance.com/en/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&state=CSRF_TOKEN&scope=SCOPES&code_challenge=CODE_CHALLENGE&code_challenge_method=S256 ``` ### Response This endpoint initiates a redirect to the user's browser. The actual response is handled in Step 3. ``` -------------------------------- ### Android Integration: Handling OAuth Callback Source: https://developers.binance.com/docs/login/app-integration Instructions for handling the redirect URI callback on Android after a user completes the Binance OAuth 2.0 authorization process. ```APIDOC ## Android Callback Handling ### Description This section describes how your Android application should handle the callback intent after the user completes or denies the Binance OAuth 2.0 authorization. ### Process 1. **Declare Intent Filter**: Configure your `AndroidManifest.xml` to handle the specific `VIEW` action and `BROWSABLE` category with your app's custom URI scheme and host. ```xml ``` 2. **Receive Redirect URI**: Retrieve the incoming intent's data (`Uri`) in your activity's `onCreate` or `onNewIntent` method. ```kotlin class YourActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... your other onCreate logic ... handleIntentUri(intent) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) handleIntentUri(intent) } private fun handleIntentUri(intent: Intent?) { val uri = intent?.data if (uri != null) { // Handle the URI here val success = uri.getQueryParameter("code") != null val code = uri.getQueryParameter("code") val state = uri.getQueryParameter("state") val error = uri.getQueryParameter("error") val errorDescription = uri.getQueryParameter("error_description") if (success) { // Send 'code' and 'state' to your server for token exchange Log.d("OAuthCallback", "Success: Code=$code, State=$state") } else { // Handle error Log.e("OAuthCallback", "Error: $error, Description=$errorDescription") } } } } ``` 3. **Server-Side Token Exchange**: After receiving the authorization `code`, send it along with your `client_id` and `redirect_uri` to your backend server. Your server should then exchange this `code` for an access token and user information by making a request to Binance's token endpoint (details not provided in this snippet but standard OAuth 2.0 procedure). ``` -------------------------------- ### Initiate Binance OAuth Flow (Swift) Source: https://developers.binance.com/docs/zh-CN/login/app-integration This code snippet demonstrates how to construct and open the Binance OAuth authorization URL using Swift. It requires a properly formatted URL string and uses UIApplication.shared.open to launch the Binance app. Ensure the URLString is correctly encoded with all required parameters. ```swift let urlString = "https://accounts.binance.com/oauth/authorize?response_type=code&scope=user:openId,create:apikey&client_id=m1smLsRw0q&redirect_uri=oauthdemo%3A%2F%2Flogin&state=76ea8434ceca47ada566308030ef5f5c" guard let url = URL(string: urlString) else { return } UIApplication.shared.open(url) ``` -------------------------------- ### Create OAuth Authorization URL Source: https://developers.binance.com/docs/login/app-integration Constructs the URL for initiating the Binance OAuth authorization flow. This involves combining the base URL with required query parameters. ```APIDOC ## POST /oauth/authorize ### Description Creates a URL to initiate the Binance OAuth authorization flow. This URL includes parameters like `response_type`, `scope`, `client_id`, `redirect_uri`, and `state`. ### Method GET ### Endpoint `https://accounts.binance.com/oauth/authorize` ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be set to `code`. - **scope** (string) - Required - A comma-separated list of scopes your application requests access to (e.g., `user:openId,create:apikey`). - **client_id** (string) - Required - Your Binance application's client ID. - **redirect_uri** (string) - Required - The URL in your application where users will be redirected after authorization. Ensure this matches your registered redirect URI. - **state** (string) - Required - A CSRF token to protect against cross-site request forgery attacks. - **bundleID** (string) - Optional - The Bundle ID of your app. ### Request Example ```json { "example": "https://accounts.binance.com/oauth/authorize?response_type=code&scope=user:openId,create:apikey&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&state=YOUR_STATE&bundleID=YOUR_BUNDLE_ID" } ``` ### Response #### Success Response (302 Redirect) - The server redirects the user's browser to the specified `redirect_uri` with an authorization `code` or an `error`. #### Response Example (Redirect to `redirect_uri`) - **Success:** `YOUR_REDIRECT_URI?state=YOUR_STATE&code=AUTHORIZATION_CODE` - **Error:** `YOUR_REDIRECT_URI?state=YOUR_STATE&error=ERROR_CODE&error_description=ERROR_DESCRIPTION` ``` -------------------------------- ### Handle OAuth Callback Source: https://developers.binance.com/docs/login/app-integration Processes the callback from Binance after the user completes or cancels the OAuth process. The result is returned via the `redirect_uri` provided during the authorization request. ```APIDOC ## Handle OAuth Result ### Description This section describes how to handle the callback URL that Binance redirects to after the user completes or cancels the OAuth process. The callback contains either an authorization `code` or an `error`. ### Method GET (handled by your application's redirect URI) ### Endpoint Your registered `redirect_uri` ### Parameters (as query parameters in the callback URL) #### Query Parameters - **state** (string) - The CSRF token provided during the authorization request. - **code** (string) - Required (on success) - The authorization code to exchange for user tokens. - **error** (string) - Required (on error) - The error code indicating the reason for failure (e.g., `cancelled`, `readClientInfoFailed`). - **error_description** (string) - Optional (on error) - A human-readable description of the error. ### Request Example (Simulated callback) ```json { "example": "YOUR_REDIRECT_URI?state=YOUR_STATE&code=AUTHORIZATION_CODE" } ``` ### Error Handling Example ```json { "example": "YOUR_REDIRECT_URI?state=YOUR_STATE&error=cancelled&error_description=cancelled%20by%20user" } ``` ### Error Types #### Error and Error Description Table | Error | Description | |---|---| | `cancelled` | User has cancelled the authorization manually. | | `readClientInfoFailed` | Binance App failed to read your app's information. | | `invaildClientInfo` | Your app's information is invalid. | ### Next Steps After receiving the `code`, your server should exchange it with the Binance OAuth server to obtain user access tokens and complete the authorization process. ``` -------------------------------- ### Step 3: Handle Callback Redirect Source: https://developers.binance.com/docs/index After the user grants or denies access, Binance's OAuth server redirects the user back to your specified `redirect_uri`. This callback contains an authorization `code` if access was granted, or an error. You should validate the `state` parameter to ensure security. ```APIDOC ## GET /oauth/callback ### Description This is the endpoint configured as `redirect_uri` in the authorization request. Binance redirects the user to this URL after they have authorized or denied your application access. ### Method GET ### Endpoint `YOUR_REDIRECT_URI` (e.g., `https://domain.com/oauth/callback`) ### Parameters #### Query Parameters - **code** (string) - Required (if authorized) - A temporary authorization code. This code is used in Step 4 to obtain an access token. - **state** (string) - Optional (if provided in the request) - The CSRF token that was sent in the initial authorization request. This value must be validated against the one stored by your application to prevent CSRF attacks. - **error** (string) - Required (if an error occurred) - Describes the error that occurred during the authorization process. - **error_description** (string) - Optional - Provides a more detailed description of the error. ### Request Example ``` GET https://domain.com/oauth/callback?code=cf6941ae8918b6a008f1377f36a4557ab5935b36&state=377f36a4557ab5935b36 ``` ### Response Example This endpoint does not return a response body directly. It is a redirect handled by the user's browser. Your application's server-side code will process the query parameters from this redirect. ``` -------------------------------- ### Handle Binance OAuth Callback (Android Manifest) Source: https://developers.binance.com/docs/login/app-integration Configures the AndroidManifest.xml to declare an activity that can handle the VIEW intent with a specific data scheme and host, allowing the app to receive the OAuth callback from Binance. ```xml ``` -------------------------------- ### JavaScript: Generate PKCE Code Challenge Source: https://developers.binance.com/docs/zh-CN Provides functions to generate the PKCE code challenge from a code verifier. It includes SHA256 hashing and Base64 URL encoding. The `generateCodeChallenge` function orchestrates these steps. ```javascript // Calculate the SHA256 hash of the input text. function sha256(code_verifier) { const encoder = new TextEncoder(); const data = encoder.encode(code_verifier); return window.crypto.subtle.digest("SHA-256", data); } // Base64-urlencodes the input string function base64urlencode(hashed) { return btoa(String.fromCharCode.apply(null, new Uint8Array(hashed))) .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); } // Return the base64-urlencoded sha256 hash for the PKCE challenge async function generateCodeChallenge(code_verifier) { hashed = await sha256(code_verifier); return base64urlencode(hashed); } ``` -------------------------------- ### Binance OAuth Authorization Request URL Source: https://developers.binance.com/docs/zh-CN This is the initial URL to redirect users to Binance to request authorization for your application. It includes parameters like client ID, redirect URI, and PKCE challenge. Ensure carriage returns are removed in production. ```HTTP GET https://accounts.binance.com/en/oauth/authorize? response_type=code& client_id=YOUR_CLIENT_ID& redirect_uri=YOUR_REDIRECT_URI& state=CSRF_TOKEN& scope=SCOPES& code_challenge=CODE_CHALLENGE& code_challenge_method=S256 ``` -------------------------------- ### Handle Binance OAuth Callback (Swift) Source: https://developers.binance.com/docs/login/app-integration This Swift code snippet shows how to handle the callback from the Binance app after a user completes or cancels the OAuth process. It extracts the URL context to retrieve the authorization code or error information. ```swift func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { guard let urlContext = URLContexts.first else { return } let url = urlContext.url print("*****(String(describing: url))*****") // Process the URL to extract code or error if url.path == "/login" { if let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let queryItems = components.queryItems { var code: String? = nil var state: String? = nil var error: String? = nil var errorDescription: String? = nil for item in queryItems { if item.name == "code" { code = item.value } if item.name == "state" { state = item.value } if item.name == "error" { error = item.value } if item.name == "error_description" { errorDescription = item.value } } if let authCode = code, let authState = state { print("Authorization Code: \(authCode)") print("State: \(authState)") // Send code to your server } else if let err = error, let errDesc = errorDescription { print("Error: \(err)\nError Description: \(errDesc)") // Handle error } } } } ``` -------------------------------- ### Handle Binance OAuth Redirect in Android Source: https://developers.binance.com/docs/zh-CN/login/app-integration This code demonstrates how to handle the redirect URI returned after a successful or failed Binance OAuth 2.0 authorization. It shows how to register an activity to receive the intent with a specific scheme and host, and how to extract the code or error information from the intent's data. ```xml ``` ```kotlin class YourActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val uri = intent.data //handle the uri here } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val uri = intent.data //handle the uri here } ...... } ``` -------------------------------- ### Binance Oauth 2.0 (iOS Integration) Source: https://developers.binance.com/docs/zh-CN/login/app-integration Documentation for integrating Binance Login via OAuth 2.0 for iOS applications. This section is currently a placeholder and requires further details on the specific implementation steps for iOS. ```APIDOC ## Binance Oauth 2.0 (iOS Integration) ### Description This section outlines the process for integrating Binance Login using OAuth 2.0 for iOS applications. Specific implementation details and code examples for iOS are to be provided. ### Method GET ### Endpoint `https://accounts.binance.com/oauth/authorize` ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be set to `code`. - **scope** (string) - Required - The scope of permissions requested (e.g., `user:openId,create:apikey`). - **client_id** (string) - Required - Your application's client ID obtained after registering with Binance. - **redirect_uri** (string) - Required - The URI to which the user will be redirected after authorization. Must be URL-encoded. - **state** (string) - Recommended - An opaque value used to maintain state between the request and callback, and to prevent CSRF attacks. - **bundleID** (string) - Required for iOS - The unique identifier of your iOS application (e.g., `com.yourcompany.yourapp`). ### Request Example ``` https://accounts.binance.com/oauth/authorize?response_type=code&scope=user:openId,create:apikey&client_id=xxxxxxxxx&redirect_uri=https%3A%2F%2Fyourapp.com%2Fcallback&state=76ea8434ceca47ada566308030ef5f5c&bundleID=com.xxx.www ``` ### Handling the Response Upon successful authorization, Binance will redirect the user to the specified `redirect_uri`. **Success Response:** The redirect URI will include `code` and `state` query parameters. `[redirect_uri]?code=xxxxx&state=xxxxx` **Failure Response:** The redirect URI will include `error` and `error_description` query parameters. `[redirect_uri]?error=xxxxx&error_description=xxxxx` Similar to Android, the received `code` should be transmitted to your backend server to complete the authorization process by exchanging it for user data with the Binance OAuth server. ``` -------------------------------- ### Handle Binance OAuth Redirect (Swift) Source: https://developers.binance.com/docs/zh-CN/login/app-integration This Swift code snippet shows how to handle the redirect URL after a user completes the Binance OAuth process. It is typically implemented within a UISceneDelegate method to capture the URL context. The received URL contains the authorization code or error information, which can then be processed. ```swift func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { print("*****\(String(describing: URLContexts.first))*****") } ``` -------------------------------- ### Step 1: Request Binance Access Source: https://developers.binance.com/docs/index Redirect users to Binance to request authorization for your application. This step involves creating and sending an authorization request with various parameters, including client ID, redirect URI, and PKCE challenge. ```APIDOC ## GET /en/oauth/authorize ### Description Initiates the OAuth 2.0 authorization flow by redirecting the user to Binance to grant your application access to their account. ### Method GET ### Endpoint `https://accounts.binance.com/en/oauth/authorize` ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be set to `code`. - **client_id** (string) - Required - The client ID of your application. - **redirect_uri** (string) - Required - The URL in your web application where users will be redirected after authorization. This value must be URL encoded. - **state** (string) - Optional - A CSRF token to protect against cross-site request forgery attacks. This value should be generated by your application and passed in the request. - **scope** (string) - Required - A comma-separated list of scopes your application requests access to. - **code_challenge** (string) - Required - The base64-urlencoded SHA256 hash of the `code_verifier`. Used for PKCE (Proof Key for Code Exchange). - **code_challenge_method** (string) - Required - Must be set to `S256` when using PKCE. ### Request Example ``` GET https://accounts.binance.com/en/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&state=CSRF_TOKEN&scope=SCOPES&code_challenge=CODE_CHALLENGE&code_challenge_method=S256 ``` ### Response Example This endpoint does not return a response body. It redirects the user's browser to the specified `redirect_uri`. ``` -------------------------------- ### Step 3: Binance Redirects Back to Your Application Source: https://developers.binance.com/docs/zh-CN After the user approves or denies the authorization request, Binance's OAuth server redirects the user back to your specified `redirect_uri`. The response includes an authorization `code` and the `state` parameter if it was provided in the initial request. ```APIDOC ## GET [Your Redirect URI] ### Description Binance redirects back to your application with an authorization code after user consent. ### Method GET ### Endpoint `[YOUR_REDIRECT_URI]` (as specified in Step 1) ### Parameters #### Query Parameters - **code** (string) - Required - A temporary authorization code. - **state** (string) - Required - The state parameter provided in the initial authorization request. Should be validated against the initial state to prevent CSRF attacks. ### Response Example ``` GET https://domain.com/oauth/callback?code=cf6941ae8918b6a008f1377f36a4557ab5935b36&state=377f36a4557ab5935b36 ``` ### Note Your application should validate the `state` parameter to ensure the request originated from the same browser and is not a CSRF attack. ``` -------------------------------- ### POST /oauth/authorize (Android Integration) Source: https://developers.binance.com/docs/zh-CN/login/app-integration This section details how to integrate Binance Login for Android applications using OAuth 2.0. It covers creating the authorization URL, initiating the OAuth activity, and handling the redirect URI callback. ```APIDOC ## POST /oauth/authorize (Android Integration) ### Description This endpoint is used to initiate the Binance OAuth 2.0 authorization flow for Android applications. It constructs a URL that, when opened, prompts the user to authorize access to their Binance account via the Binance app or a web page. ### Method GET ### Endpoint `https://accounts.binance.com/oauth/authorize` ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be set to `code`. - **scope** (string) - Required - The scope of permissions requested (e.g., `user:openId,create:apikey`). - **client_id** (string) - Required - Your application's client ID obtained after registering with Binance. - **redirect_uri** (string) - Required - The URI to which the user will be redirected after authorization. Must be URL-encoded. - **state** (string) - Recommended - An opaque value used to maintain state between the request and callback, and to prevent CSRF attacks. - **bundleID** (string) - Required for Android - The unique identifier of your Android application. ### Request Example ``` https://accounts.binance.com/oauth/authorize?response_type=code&scope=user:openId,create:apikey&client_id=xxxxxxxxx&redirect_uri=https%3A%2F%2Faccounts.pexpay.com%2Fen%2Foauth-handle&state=76ea8434ceca47ada566308030ef5f5c&bundleID=com.xxx.www ``` ### Handling the Response Once the user completes the OAuth process, Binance will redirect the user to the `redirect_uri` you provided. **Success Response:** The redirect URI will include `code` and `state` query parameters. `[redirect_uri]?code=xxxxx&state=xxxxx` **Failure Response:** The redirect URI will include `error` and `error_description` query parameters. `[redirect_uri]?error=xxxxx&error_description=xxxxx` The `code` received should be sent to your server, which will then exchange it with the Binance OAuth server to obtain user data and complete the authorization. ### Android Integration Snippet ```kotlin val uri = Uri.Builder() .scheme("https") .authority("accounts.binance.com") .appendPath("oauth") .appendPath("authorize") .appendQueryParameter("response_type", "code") .appendQueryParameter("scope", scope) .appendQueryParameter("redirect_uri", redirectUri) .appendQueryParameter("state", state) .appendQueryParameter("client_id", clientID) .appendQueryParameter("bundleID", bundleId) // Add bundleID for Android .build() val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) ``` ### AndroidManifest Configuration Ensure your `AndroidManifest.xml` includes an intent filter to handle the redirect URI: ```xml ``` ### Handling Redirect in Activity Handle the incoming URI in your activity's `onCreate` or `onNewIntent` methods: ```kotlin class YourActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val uri = intent.data // Handle the uri here } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val uri = intent.data // Handle the uri here } } ``` **Note:** This functionality relies on Android App Links. If App Links verification is incomplete, users might be redirected to the website for OAuth. ``` -------------------------------- ### POST /oauth/token (Authorization Code Grant) Source: https://developers.binance.com/docs/index Exchange an authorization code for access and refresh tokens. This is the first step after user authorization. ```APIDOC ## POST /oauth/token (Authorization Code Grant) ### Description Exchanges an authorization code received after user consent for an access token and a refresh token. ### Method POST ### Endpoint https://accounts.binance.com/oauth/token ### Parameters #### Query Parameters - **grant_type** (string) - Required - Value must be `authorization_code`. - **code** (string) - Required - The authorization code obtained from the previous step. - **client_id** (string) - Required - The client ID of your application. - **code_verifier** (string) - Required - The secret code generated in STEP1. - **redirect_uri** (string) - Required - The URL to redirect users to after authorization. Must be URL encoded. ### Request Example ```json { "grant_type": "authorization_code", "code": "STEP3_CODE", "client_id": "YOUR_CLIENT_ID", "code_verifier": "STEP1_CODE_VERIFIER", "redirect_uri": "YOUR_REDIRECT_URI" } ``` ### Request Example (cURL) ```bash curl https://accounts.binance.com/oauth/token \ -X POST \ -d 'client_id=je-client&code_verifier=65a4ecce1fe857067bec7a6887529531831ebe38e32da95fe0f322a2&grant_type=authorization_code&code=95OfIm&redirect_uri=https%3A%2F%2Fdomain.com%2Foauth%2Fcallback' ``` ### Response #### Success Response (200) - **access_token** (string) - The obtained access token. - **refresh_token** (string) - The token used to obtain new access tokens when the current one expires. - **scope** (string) - The scope granted to the access token. - **token_type** (string) - The type of the token, usually 'bearer'. - **expires_in** (integer) - The lifespan of the access token in seconds. #### Response Example ```json { "access_token": "83f2bf51-a2c4-4c2e-b7c4-46cef6a8dba5", "refresh_token": "fb5587ee-d9cf-4cb5-a586-4aed72cc9bea", "scope": "read", "token_type": "bearer", "expires_in": 30714 } ``` ```