Oauth 2.0 for Server-side Web Apps

QuickBooks Online APIs uses the OAuth 2.0 protocol for authentication and authorization. Intuit supports use cases for server and client applications.

To begin, obtain OAuth 2.0 client credentials by creating a new QuickBooks Online application in your Intuit Developer Account. Then your application requests an access token from the Intuit’s Authorization Server, extracts a token from the response, and sends the token to the QuickBooks API that you want to access. For an interactive demonstration of using OAuth 2.0 with QuickBooks (including the option to use your own client credentials), experiment with the OAuth 2.0 Playground.

This page gives an overview of the OAuth 2.0 authorization scenarios that QuickBooks supports. For details about using OAuth 2.0 for authentication, see OpenID Connect

Note

Note

Given the security implications of getting the implementation correct, we strongly encourage you to use OAuth 2.0 libraries when interacting with QuickBooks’ Online endpoints. It is a best practice to use well-debugged code provided by others, and it will help you protect yourself and your users.

For more information, see the next section about Client libraries.

Download the OAuth Library

The language-specific examples on this page use QuickBooks Online API Client Libraries to implement OAuth 2.0 authorization. To run the code samples, you must first install the client library for your language.

When you use a QuickBooks Online API Client Library to handle your application’s OAuth 2.0 flow, the client library performs many actions that the application would otherwise need to handle on its own. The client library also generates correct redirect URLs and helps to implement redirect handlers that exchange authorization codes for access tokens.

The following client libraries integrate with popular frameworks, which makes implementing OAuth 2.0 simpler. More features will be added to the libraries over time.

.NET

Java

PHP

Node.js

Python

Ruby

1
Install-Package IntuitOAuth2PlaformClient

1
2
3
Download the latest version of oauth2-platform-api.jar and include it in your project.
Sample below shows how to add it to a gradle project:
compile (group: 'com.intuit.quickbooks-online', name: 'oauth2-platform-api', version: '4.0.3', classifier: 'jar-with-dependencies')

1
composer require quickbooks/v3-php-sdk

1
$ npm install intuit-oauth

1
$ pip install intuit-oauth

1
gem install 'intuit-oauth'
Obtain OAuth2 credentials for your app

Obtain OAuth 2.0 credentials such as a client id and client secret from the “keys” tab after creating a QuickBooks Online application in developer.intuit.com/myapps.

Define redirect URIs: Under the keys, you can define one or more redirect URIs. These URIs handle responses from the OAuth 2.0 server and are called after the user authorizes the connection. URIs in this list are the only ones to which the authorization response can be sent from the OAuth 2.0 server.

You must define at least one URI specifically for your application’s auth endpoint before you can use OAuth 2.0. For the sandbox environment, this list can include localhost. As a best practice, design your app’s auth endpoints in a way that doesn’t expose authorization codes to other resources on the page.

Obtain the access token

Before your application can access data using QuickBooks Online API, it must obtain an access token that grants access to the API. A single access token can grant varying degrees of access to multiple APIs. Scope parameter used while requesting the access token controls the set of resources and operations that an access token permits. During the access-token request, your application sends one or more values in the scope parameter.

Obtaining the token requires an authentication step where the user logs in with their QuickBooks Online account. After logging in, the user is asked whether they are willing to grant the permissions that your application is requesting. This process is called user consent.

If the user grants the permission, the Intuit Authorization Server sends your application an authorization code at the callback endpoint that you defined in the Redirect URL section of the Keys tab of your app. This authorization code can be exchanged to obtain the access token. If the user does not grant the permission, the server returns an error.

It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front.

View Screenshot

qbo/docs/develop/authentication-and-authorization/oauth2-flow-diagram.png
Step 1: Prepare authorization request

Your first step is to create the authorization request with the parameters that identify your application and permissions that the user will be asked to grant to your application.

If you use one of our client library for OAuth 2.0, you create and configure an object that defines these parameters. If you call the Intuit OAuth 2.0 endpoint directly, you’ll generate a URL and set the parameters on that URL.

.NET

Java

PHP

Node.js

Python

Ruby

1
2
3
4
5
6
7
8
9
// Instantiate object
public static OAuth2Client oauthClient = new OAuth2Client(“clientid”, “clientsecret”, “redirectUrl”, “environment”); // environment is “sandbox” or “production”

//Prepare scopes
List<OidcScopes> scopes = new List<OidcScopes>();
scopes.Add(OidcScopes.Accounting);

//Get the authorization URL
string authorizeUrl = oauthClient.GetAuthorizationURL(scopes);

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
//Prepare the config
OAuth2Config oauth2Config = new OAuth2Config.OAuth2ConfigBuilder("clientId", "clientSecret")
        .callDiscoveryAPI(Environment.SANDBOX).buildConfig();

//Generate the CSRF token
String csrf = oauth2Config.generateCSRFToken();

//Prepare scopes
List<Scope> scopes = new ArrayList<Scope>();
scopes.add(Scope.Accounting); // add as needed

//Get the authorization URL
String url = oauth2Config.prepareUrl(scopes, redirectUri, csrf); //redirectUri - pass the callback url

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$dataService = DataService::Configure(array(
      'auth_mode' => 'oauth2',
      'ClientID' => "Client ID from the app's keys tab",
      'ClientSecret' => "Client Secret from the app's keys tab",
      'RedirectURI' => "The redirect URI provided on the Redirect URIs part under keys tab",
      'scope' => "com.intuit.quickbooks.accounting or com.intuit.quickbooks.payment",
      'baseUrl' => "Development/Production"
));
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$authorizationCodeUrl = $OAuth2LoginHelper->getAuthorizationCodeURL();

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Instance of client
var oauthClient = new OAuthClient({
    clientId: '<Enter your clientId>',
    clientSecret: '<Enter your clientSecret>',
    environment: 'sandbox',                                // ‘sandbox’ or ‘production’
    redirectUri: '<Enter your redirectUri>'
});

// AuthorizationUri
var authUri = oauthClient.authorizeUri({scope:[OAuthClient.scopes.Accounting,OAuthClient.scopes.OpenId],state:'testState'});  // can be an array of multiple scopes ex : {scope:[OAuthClient.scopes.Accounting,OAuthClient.scopes.OpenId]}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from intuitlib.client import AuthClient
from intuitlib.enums import Scopes

//Instantiate client
auth_client = AuthClient(
    “client_id”,
    “client_secret”,
    “redirect_uri”,
    “Environment”, # “sandbox” or “production”
)

// Prepare scopes
scopes = [
    Scopes.ACCOUNTING,
]

// Get authorization URL
auth_url = auth_client.get_authorization_url(scopes)

1
2
3
4
5
6
7
8
9
require 'intuit-oauth'

client = IntuitOAuth::Client.new('client_id', 'client_secret', 'redirectUrl', 'environment')
scopes = [
    IntuitOAuth::Scopes::ACCOUNTING
]

authorizationCodeUrl = oauth_client.code.get_auth_uri(scopes)
# => https://appcenter.intuit.com/connect/oauth2?client_id=clientId&redirect_uri=redirectUrl&response_type=code&scope=com.intuit.quickbooks.accounting&state=rMwcoDITc2N6FJsUGGO9
HTTP/REST

Retrieve the base URI from the Discovery Document using the key, authorization_endpoint. The discussion here assumes the base URI is https://appcenter.intuit.com/connect/oauth2 that includes the following parameters:

Field Description
client_id

Required. Identifies which app is making the request. Obtain this value from the Keys tab on the app profile via My Apps on the developer site. There are two versions of this key:

Development key—use only in the sandbox environment.

Production key—use only in the production environment.

scope

Required. A space-delimited list of scopes that identifies the QuickBooks Online API access that your application is requesting. The values passed in this parameter inform the consent screen that is shown to the user. Available scopes include: com.intuit.quickbooks.accounting—QuickBooks Online API


com.intuit.quickbooks.payment—QuickBooks Payments API


com.intuit.quickbooks.payroll—QuickBooks Payroll API (whitelisted beta apps only)


com.intuit.quickbooks.payroll.timetracking—QuickBooks Payroll API for for access to compensation (whitelisted beta apps only)


com.intuit.quickbooks.payroll.benefits—QuickBooks Payroll API for access to benefits/pension/deduction (whitelisted beta apps only)

redirect_uri Required. Determines where the API server redirects the user after the user completes the authorization flow. The value of this parameter must exactly match one of the values listed for this app in the app settings. This includes the https scheme, the same case, and the trailing ‘/’. For the sandbox environment, this list can include localhost (no HTTPS with localhost). IP addresses are not allowed for redirect URIs.
response_type Required. Determines whether the Intuit OAuth 2.0 endpoint returns an authorization code. Always set this to code
state Required. Specifies any string value that your application uses to maintain state between your authorization request and the authorization server’s response. The server returns the exact value that you send as a name=value pair in the request. To mitigate against cross-site request forgery (CSRF), it is strongly recommended to include an anti-forgery token in the state, and confirm it in the response.
Step 2: Redirect to Intuit’s OAuth 2.0 server

Redirect the user to Intuit’s OAuth 2.0 server using the URL prepared above to initiate the authentication and authorization process. This step is required when your application first needs to access user’s data. In the case of incremental authorization, this step also occurs when your application first needs to access additional resources that it does not yet have permission to access.

.NET

Java

PHP

Node.js

Python

Ruby

1
2
// Redirect the authorization URL
return Redirect(authorizeUrl);

1
2
//Use standard url redirect-
resp.sendRedirect(url);

1
2
//redirect users to authorization screen url
header('Location: '. $authorizationCodeUrl);

1
2
// Redirect the authUri
res.redirect(authUri);

1
2
//Using standard redirect
return redirect(auth_url)

1
redirect_to(authorizationCodeUrl)
HTTP/REST

Here is an example of a complete authorization request URI specifying the com.intuit.quickbooks.accounting scope, with line breaks and spaces for readability

1
2
POST https://appcenter.intuit.com/connect/oauth2?
client_id=Q3ylJatCvnkYqVKLmkH1zWlNzNWB5CkYB36b5mws7HkKUEv9aI&response_type=code&scope=com.intuit.quickbooks.accounting&redirect_uri=https://www.mydemoapp.com/oauth-redirect&state=security_token%3D138r5719ru3e1%26url%3Dhttps://www.mydemoapp.com/oauth-redirect&

In this step, the user decides whether to grant your application the requested access. At this stage, Intuit displays a consent window to the user showing the name of your application and the QuickBooks Online Company name that it is requesting permission to access with the user’s authorization credentials. The user can then consent or refuse to grant access to your application.

Your application doesn’t need to do anything at this stage as it waits for the response from Intuit’s OAuth 2.0 server indicating whether the access was granted.

Step 4: Handle the OAuth 2.0 server response

The OAuth 2.0 server responds to your application’s access request by using the redirect_uri specified in the request.

If the user approves the access request, then the response contains an authorization code. An example callback looks like this:

1
2
https://www.mydemoapp.com/oauth-redirect?state=security_token%3D138r5719ru3e1%26url
%3Dhttps://www.mydemoapp.com/oauth-redirect&code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&realmId=1231434565226279
URL parameter Description
code Authorization code returned by the server, to be used in the next step
realmid RealmID for the company that your app was granted access to. You use it in subsequent API endpoint URLs when retrieving data from the QuickBooks Online company.
state Confirm that the state received from Intuit matches the state token you sent in the authentication request. This round-trip verification helps to ensure that the user, not a malicious script, is making the request.

If the user does not approve the request, the response contains an error message as shown below:

Error Response Description
access_denied The user did not authorize the request.
invalid_scope An invalid scope string was sent in the request.

Note

Note

If your response endpoint renders an HTML page, any resources on that page will be able to see the authorization code in the URL. Scripts can read the URL directly, and all resources may be sent the URL in the Referer HTTP header. Carefully consider if you want to send authorization credentials to all resources on that page (especially third-party scripts such as social plugins and analytics). To avoid this issue, we recommend that the server first handle the request, then redirect to another URL that doesn’t include the response parameters.

Step 5: Exchange authorization code for refresh and access tokens

After the app receives the authorization code, it should exchange the authorization code for refresh and access tokens

.NET

Java

PHP

Node.js

Python

Ruby

1
2
3
4
5
// Get OAuth2 Bearer token
var tokenResponse = await auth2Client.GetBearerTokenAsync(code);
//retrieve access_token and refresh_token
tokenResponse.AccessToken
tokenResponse.RefreshToken

1
2
3
4
5
6
7
8
9
//Prepare OAuth2PlatformClient
OAuth2PlatformClient client  = new OAuth2PlatformClient(oauth2Config);

//Get the bearer token (OAuth2 tokens)
BearerTokenResponse bearerTokenResponse = client.retrieveBearerTokens(authCode, redirectUri);

//retrieve the token using the variables below
bearerTokenResponse.getAccessToken()
bearerTokenResponse.getRefreshToken()

1
2
3
$accessTokenObj = $OAuth2LoginHelper->exchangeAuthorizationCodeForToken("authorizationCode", "RealmID");
$accessTokenValue = $accessTokenObj->getAccessToken();
$refreshTokenValue = $accessTokenObj->getRefreshToken();

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Parse the redirect URL for authCode and exchange them for tokens
var parseRedirect = req.url;

// Exchange the auth code retrieved from the **req.url** on the redirectUri
oauthClient.createToken(parseRedirect)
    .then(function(authResponse) {
        console.log('The Token is  '+ JSON.stringify(authResponse.getJson()));
    })
    .catch(function(e) {
        console.error("The error message is :"+e.originalMessage);
        console.error(e.intuit_tid);
    });

1
2
3
4
5
6
// Get OAuth2 Bearer token
auth_client.get_bearer_token(auth_code, realm_id=realm_id)

//retrieve access_token and refresh_token
auth_client.access_token
auth_client.refresh_token

1
2
oauth2Token = oauth_client.token.get_bearer_token('the authorization code returned from authorizationCodeUrl')
# => #<IntuitOAuth::ClientResponse:0x00007f9152b5c418 @access_token="the access token", @expires_in=3600, @refresh_token="the refresh token", @x_refresh_token_expires_in=8726400>
HTTP/REST

Retrieve the base URI from the Discovery Document using the key, token_endpoint. The discussion here assumes the base URI (https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer) sends an HTTPS POST request to the URL above that includes the following parameters:

Field Description
code Required. The authorization code returned from the initial request.
redirect_uri Required. One of the redirect URIs listed for this project in the developer dashboard.
grant_type Required. As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code.

The following snippet shows a sample request:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
POST https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer HTTP/1.1
Accept: application/json
Authorization: Basic UTM0dVBvRDIwanp2OUdxNXE1dmlMemppcTlwM1d2
    NzRUdDNReGkwZVNTTDhFRWwxb0g6VEh0WEJlR3dheEtZSlVNaFhzeGxma1l
    XaFg3ZlFlRzFtN2szTFRwbw==
Content-Type: application/x-www-form-urlencoded
Host: oauth.platform.intuit.com
Body: grant_type=authorization_code&
code=L3114709614564VSU8JSEiPkXx1xhV8D9mv4xbv6sZJycibMUI&
redirect_uri=https://www.mydemoapp.com/oauth-redirect

Authorization header can be generated using the value below-

1
"Basic " + base64encode(client_id + ":" + client_secret)

The token server returns a JSON object that contains a new access token. The following snippet shows a sample response:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
"token_type": "bearer",
"expires_in": 3600,
"refresh_token":"Q311488394272qbajGfLBwGmVsbF6VoNpUKaIO5oL49aXLVJUB",
"x_refresh_token_expires_in":15551893,
"access_token":"eJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGGlyIn0..KM1_Fezsm6BUSaqqfTedaA.
dBUCZWiVmjH8CdpXeh_pmaM3kJlJkLEqJlfmavwGQDThcf94fbj9nBZkjEPLvBcQznJnEmltCIvsTGX0ue_w45h7_
yn1zBoOb-1QIYVE0E5TI9z4tMUgQNeUkD1w-X8ECVraeOEecKaqSW32Oae0yfKhDFbwQZnptbPzIDaqiduiM_q
EFcbAzT-7-znVd09lE3BTpdMF9MYqWdI5wPqbP8okMI0l8aa-UVFDH9wtli80zhHb7GgI1eudqRQc0sS9zWWb
I-eRcIhjcIndNUowSFCrVcYG6_kIj3uRUmIV-KjJUeXdSV9kcTAWL9UGYoMnTPQemStBd2thevPUuvKrPdz3ED
ft-RVRLQYUJSJ1oA2Q213Uv4kFQJgNinYuG9co_qAE6A2YzVn6A8jCap6qGR6vWHFoLjM2TutVd6eOeYoL2bb7jl
QALEpYGj4E1h3y2xZITWvnmI0CEL_dYQX6B3QTO36TDaVl9WnTaCCgAcP6bt70rFlPYbCjOxLoI6qFm5pUwGLLp
67JZ36grc58k7NIyKJ8dLJUL_Q9r1WoUvw.ZS298t_u7dSlkfajxLfO9Q"
}

Note

Note

Other fields may be included in the response, and your application should not treat this as an error. The set shown above is the minimum set.

Field Description
code Required. The authorization code returned from the initial request.
redirect_uri Required. One of the redirect URIs listed for this project in the developer dashboard.
grant_type Required. As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code.

Note

Note

Your application should store both tokens in a secure, long-lived location that is accessible between different invocations of your application. The refresh token enables your application to obtain a new access token if the one that you have expires. As such, if your application loses the refresh token, the user will need to repeat the OAuth 2.0 consent flow so that your application can obtain a new refresh token.

Understand token expiration

Access tokens are valid for 60 minutes (one hour), after which you need to get a new one using the latest refresh_token returned to you from the previous request. You must write your code to anticipate the possibility that a granted access token might no longer work.

  • As a reminder, you pass the 1-hour access token in the Authorization header with every API request, such as when you query CompanyInfo.
  • You only use the refresh token to mint a new 1-hour access token when the prior access token expires. The refresh token itself can last up to 100 days before it expires, and then the user needs to sign in and grant consent again or you can get a new one programmatically using the Refresh Token API before the 100-day refresh token expires. Keep in mind that a refresh token is only for getting new (i.e., “refreshing”) access tokens; you can’t pass a refresh token for requests like querying CompanyInfo.
qbo/docs/develop/authentication-and-authorization/TokenExpiration.png
An access token might stop working for one of these reasons:
  • The user has revoked your app’s access: If a user revokes connection to the QuickBooks Online company, the access token and refresh token are invalidated. When this happens, your app must ask the user to reauthorize the connection as in Step 1.
  • The access token has been expired: If the access token is past one hour you will receive a 401 error while making a QuickBooks Online API call. When this happens, you must request for new token using the refresh token that you received last.
  • The refresh token has not been used for 100 days: The lifetime of refresh token is 100 days. When this happens, your app must ask the user to reauthorize the connection as in Step 1.

Note

Note

Even though the refresh token is valid for 100 days, the value of refresh token can change every 24-26 hour period. Hence, you might encounter a situation where the request token that you received first is different than the latest one. As a best practice, always store the latest refresh token received from the API response and use that to make subsequent calls to obtain a new pair of tokens.

Refresh the token

Access tokens periodically expire. You can refresh an access token without prompting the user for permission.

.NET

Java

PHP

Node.js

Python

Ruby

1
2
3
4
5
// Instantiate object
public static OAuth2Client oauthClient = new OAuth2Client(“clientid”, “clientsecret”, “redirectUrl”, “environment”); // environment is “sandbox” or “production”

//Refresh token endpoint
var tokenResp = await oauthClient.RefreshTokenAsync(“refreshToken”);

1
2
3
4
5
6
7
8
//Prepare the config
OAuth2Config oauth2Config = new OAuth2Config.OAuth2ConfigBuilder("OAuth2AppClientId", "OAuth2AppClientSecret").callDiscoveryAPI(Environment.SANDBOX).buildConfig();

//Prepare OAuth2PlatformClient
OAuth2PlatformClient client  = new OAuth2PlatformClient(oauth2Config);

//Call refresh endpoint
BearerTokenResponse bearerTokenResponse = client.refreshToken("refreshToken"); //set refresh token

1
2
3
4
5
$oauth2LoginHelper = new OAuth2LoginHelper($ClientID,$ClientSecret);
$accessTokenObj = $oauth2LoginHelper->
                    refreshAccessTokenWithRefreshToken($theRefreshTokenValue);
$accessTokenValue = $accessTokenObj->getAccessToken();
$refreshTokenValue = $accessTokenObj->getRefreshToken();

1
2
3
4
5
6
7
8
   oauthClient.refresh()
        .then(function(authResponse) {
            console.log('Tokens refreshed : ' + JSON.stringify(authResponse.json()));
        })
        .catch(function(e) {
            console.error("The error message is :"+e.originalMessage);
            console.error(e.intuit_tid);
        });

1
2
3
4
5
6
7
8
9
//Instantiate client
auth_client = AuthClient(
    “client_id”,
    “client_secret”,
    “redirect_uri”,
    “Environment”, # “sandbox” or “production”
)
// Refresh token endpoint
auth_client.refresh(refresh_token=”refresh_token”)

1
newToken = oauth_client.token.refresh_tokens('Your_refresh_token')
HTTP/REST

To refresh an access token, your application sends an HTTPS POST request to Intuit’s authorization server (https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer) that includes the following parameters:

Field Description
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of refresh_token
refresh_token The refresh token returned from the authorization code exchange

The following snippet shows a sample request:

1
2
3
4
5
6
7
8
POST /oauth2/v1/tokens/bearer HTTP/1.1
Accept: application/json
Authorization: Basic UTM0dVBvRDIwanp2OUdxNXE1dmlMemppcTlwM1d2
    NzRUdDNReGkwZVNTTDhFRWwxb0g6VEh0WEJlR3dheEtZSlVNaFhzeGxma1l
    XaFg3ZlFlRzFtN2szTFRwbw==
Content-Type: application/x-www-form-urlencoded
Body: grant_type=refresh_token&
refresh_token=Q311488394272qbajGfLBwGmVsbF6VoNpUKaIO5oL49aXLVJUB

Authorization header can be generated using the value below-

1
"Basic " + base64encode(client_id + ":" + client_secret)

As long as the user has not revoked the access granted to the application, the token server returns a JSON object that contains a new access token. The following snippet shows a sample response:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
"token_type": "bearer",
"expires_in": 3600,
"refresh_token":"Q311488394272qbajGfLBwGmVsbF6VoNpUKaIO5oL49aXLVJUB",
"x_refresh_token_expires_in":15551893,
"access_token":"eJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGGlyIn0..KM1_Fezsm6BUSaqqfTedaA.
dBUCZWiVmjH8CdpXeh_pmaM3kJlJkLEqJlfmavwGQDThcf94fbj9nBZkjEPLvBcQznJnEmltCIvsTGX0ue_w45h7_
yn1zBoOb-1QIYVE0E5TI9z4tMUgQNeUkD1w-X8ECVraeOEecKaqSW32Oae0yfKhDFbwQZnptbPzIDaqiduiM_q
EFcbAzT-7-znVd09lE3BTpdMF9MYqWdI5wPqbP8okMI0l8aa-UVFDH9wtli80zhHb7GgI1eudqRQc0sS9zWWb
I-eRcIhjcIndNUowSFCrVcYG6_kIj3uRUmIV-KjJUeXdSV9kcTAWL9UGYoMnTPQemStBd2thevPUuvKrPdz3ED
ft-RVRLQYUJSJ1oA2Q213Uv4kFQJgNinYuG9co_qAE6A2YzVn6A8jCap6qGR6vWHFoLjM2TutVd6eOeYoL2bb7jl
QALEpYGj4E1h3y2xZITWvnmI0CEL_dYQX6B3QTO36TDaVl9WnTaCCgAcP6bt70rFlPYbCjOxLoI6qFm5pUwGLLp
67JZ36grc58k7NIyKJ8dLJUL_Q9r1WoUvw.ZS298t_u7dSlkfajxLfO9Q"
}
Revoke token/Disconnect

Your app can programmatically revoke access given to it by a specific user when they click the Disconnect link in your app. Use the revoke endpoint to request permissions granted to the application to be removed.

.NET

Java

PHP

Node.js

Python

Ruby

Curl

1
2
3
4
5
// Instantiate object
public static OAuth2Client oauthClient = new OAuth2Client(“clientid”, “clientsecret”, “redirectUrl”, “environment”); // environment is “sandbox” or “production”

//Revoke token endpoint
var tokenResp = await oauthClient.RevokeTokenAsync(“refreshToken");

1
2
3
4
5
6
7
8
//Prepare the config
OAuth2Config oauth2Config = new OAuth2Config.OAuth2ConfigBuilder("OAuth2AppClientId", "OAuth2AppClientSecret").callDiscoveryAPI(Environment.SANDBOX).buildConfig();

//Prepare OAuth2PlatformClient
OAuth2PlatformClient client  = new OAuth2PlatformClient(oauth2Config);

//Call revoke endpoint
PlatformResponse response  = client.revokeToken("refreshToken"); //set refresh token

1
2
$oauth2LoginHelper = new OAuth2LoginHelper($clientID,$clientSecret);
$revokeResult = $oauth2LoginHelper->revokeToken($yourToken);

1
2
3
4
5
6
7
8
oauthClient.revoke(params)
        .then(function(authResponse) {
            console.log('Tokens revoked : ' + JSON.stringify(authResponse.json()));
        })
        .catch(function(e) {
            console.error("The error message is :"+e.originalMessage);
            console.error(e.intuit_tid);
        });

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//Instantiate client
auth_client = AuthClient(
    “client_id”,
    “client_secret”,
    “redirect_uri”,
    “Environment”, # “sandbox” or “production”
)

// Refresh token endpoint
auth_client.revoke(token=”refresh_token”)

1
trueOrFalse = oauth_client.token.revoke_tokens('the_token_you_want_to_revoke')

1
2
$ ls -lsa .
$ make file
HTTP/REST

To revoke an token, your application sends an HTTPS POST request to revoke endpoint (https://developer.api.intuit.com/v2/oauth2/tokens/revoke) and includes the token as a parameter

The following snippet shows a sample request:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
POST https://developer.api.intuit.com/v2/oauth2/tokens/revoke HTTP/1.1
Accept: application/json
Authorization: Basic UTM0dVBvRDIwanp2OUdxNXE1dmlMemppcTlwM1d2
    NzRUdDNReGkwZVNTTDhFRWwxb0g6VEh0WEJlR3dheEtZSlVNaFhzeGxma1l
    XaFg3ZlFlRzFtN2szTFRwbw==
Content-Type: application/json

{
    "token": "{bearerToken or refreshToken}"
}

Authorization header can be generated using the value below:

1
"Basic " + base64encode(client_id + ":" + client_secret)

If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.

OAuth 2.0 Playground

The OAuth 2.0 playground is a tool to walk through each step of both the OAuth 2.0 and OpenID Connect workflows. The playground demonstrates the following steps:

  • Get the access token
  • Make API calls
  • Refresh the access token

Looking for the OAuth 1 playground? Click here

Note

Note

The playground requires that you to have a QuickBooks Online app. Create a QuickBooks Online App if you haven’t already done so before proceeding.

Get the access token

Invoke the OAuth 2.0 playground directly, or from your app’s dashboard. Authorize the connection between your app and the QuickBooks Online company or Sandbox Company.

  1. Select app: If you have multiple apps under your Intuit Developer Account, start by selecting the app and the environment (sandbox or production) using that you want to connect your QuickBooks Online company with. This auto populates the client id and client secret corresponding to the app.
  2. Select scopes: In the next step, select the scope that you would like to pass while requesting for access.
  3. Get the authorization code: Click the Get Authorization Code button and then the Authorize button on the connection dialog to initiate the company authorization workflow. The next playground section, Get Tokens from Authorization Code, is populated with the authorization code and company ID.
  4. Exchange code for access token: In the Get Tokens from Authorization Code section, click the Get Tokens button to finish the authorization process. The response payload contains the access token for use in subsequent API calls and the refresh token to use when refreshing the access token.
qbo/docs/develop/authentication-and-authorization/oauth2_playground.gif

Note

Note

The playground uses its own OAuth redirect URI to field the authorization request.

Make API calls

The Make API Calls panel is populated with the realm Id (labeled Company ID) and the current access token, ready for you to test out some API calls. The Call API dropdown list contains the three available API calls you can make from the playground. Availability of each is based on the scopes you choose when getting your access token.

API Call Required Scope Description
Get Company Info com.intuit.quickbooks.accounting Calls the QuickBooks Online API CompanyInfo resource to get information about the company corresponding to the realm Id.
Submit Charge com.intuit.quickbooks.payments Calls the QuickBooks Payments API Charges resource to create a charge to the test Visa card account.
Get User Info OpenID and at least one of Profile, Email, Phone, `` Address``. Calls the UserInfo resource to get additional information about the logged in user.
Refresh the access token

The Refresh Access Token panel is populated with the current access and refresh tokens. Click Refresh Access Token to refresh the token. As a general rule, access tokens need to be refreshed every 60 minutes. Click here for further information about refreshing access tokens.

Sample Code
Language Client Library Sample
GoLang No Yes
Ruby No
.Net Yes
Java Yes
PHP Yes
Node.js Yes
Python Yes

Connect to QuickBooks Button

qbo/docs/develop/authentication-and-authorization/C2QB_auth.png

Add a Connect to QuickBooks Button for your users to connect your application to their QuickBooks Online Company via the Oauth Authorization flow.