If you just want to jump right in and test an API call, you have a few options:
Make a generic API call
Simply set up your developer account. Then use the sample GET request to call the companyInfo entity.
Call a specific API using your sandbox company
Want to build something more robust that mimics the early stages of app development? Use this guide to build a “Demo app” in .NET, Java, or PHP. The demo can send requests and get live data from QuickBooks Online.
.NET
Java
PHP
Before you start, you should have a basic understanding of ASP.NET MVC Framework.
Start by installing the following on your machine:
Use the commands below to clone the “Hello World” repo:
1 2 | git clone https://github.com/IntuitDeveloper/HelloWorldApp-MVC5-Dotnet cd HelloWorldApp-MVC5-Dotnet |
This repo gives you basic code to build the demo app. It sets up your development environment so you can use an SDK, handles authorization set up (OAuth 2.0 protocol), and simplifies logging.
Now you have sample code. Create an app on the developer portal:
This generates credentials and lets you set the demo’s URIs. You can use these credentials on a QuickBooks Online Sandbox company. Click here to create one.
When users connect to your app, it needs to redirect them to start the authorization flow. This “user consent” step is where they give your app permission to access their QuickBooks Online company data.
Let’s redirect users who connect to your “Demo app” to the callback page. Use the provided http://localhost address for the URI:
For this demo app, we’ll assume a user found your app on the QuickBooks App Store and selected the Connect to QuickBooks link. This is just one of several ways to initiate the authorization flow.
Let’s make a few edits in the cloned “Hello World” repo:
1 2 3 4 5 | <appSettings> <add key="clientid" value="Enter value here" /> <add key="clientsecret" value="Enter value here" /> <add key="redirectUrl" value="http://localhost:27353/callback" /> </appSettings> |
View Screenshot
View Screenshot
After you select Authorize, you’ll redirect to the URI you added in Step 4.
If users authorize your app, our server sends an authorization code to your app. You’ll exchange the authorization code for access tokens. For this demo, the Intuit OAuth 2.0 server will automatically handle the backend exchange of temporary authorization codes for tokens.
Let’s assume the “Demo app” has access tokens and simulate your first API call. You’ll redirect to a new webpage via the URI (i.e. http://localhost:27353/callback).
View Screenshot
This automatically makes an API call to the CompanyInfo
entity for the sandbox company you just connected.
Now you have a good understanding of the basic development and authorization process. Download one of our SDKs to get a jumpstart on development.
Here’s more info about:
The Client Id and Client Secret are used by your app to uniquely establish its identity with the QuickBook Online platform.
The value of Redirect URI defines where your app’s users get redirected in your app after they authorize the app.
Specify which environment your application is running in with appEnvironment value. This ensures the OAuth2Client uses the correct discovery document (this is part of the OAuth2Client initialization). Discovery documents contain the AuthorizationEndpoint, TokenEndpoint, and other values required for the authorization flow.
1 2 3 4 5 6 | <appSettings> <add key="clientid" value="EnterClientIdHere" /> <add key="clientsecret" value="EnterClientSecretHere" /> <add key="appEnvironment" value="sandbox" /> <add key="redirectUrl" value="http://localhost:27353/callback" /> </appSettings> |
There are a few key components:
Initialize the OAuth2Client object with clientid, clientecret, redirectUrl and appEnvironment
1
public static OAuth2Client auth2Client = new OAuth2Client(clientid, clientsecret, redirectUrl, environment);
To start the authorization flow, specify the Accounting scope Use GetAuthorizationURL method of OAuth2Client object to get the Authorization URL. It’s redirected to show the QuickBooks user the Connect screen. Here’s a code sample:
1 2 3 4 5 6 7 public ActionResult InitiateAuth(string submitButton) { List<OidcScopes> scopes = new List<OidcScopes>(); scopes.Add(OidcScopes.Accounting); string authorizeUrl = auth2Client.GetAuthorizationURL(scopes); return Redirect(authorizeUrl); }
Once the tokens are received, apps can make calls to the QuickBooks Online Accounting API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public ActionResult ApiCallService() { string realmId = Session["realmId"].ToString(); var principal = User as ClaimsPrincipal; OAuth2RequestValidator oauthValidator = new OAuth2RequestValidator(principal.FindFirst("access_token").Value); // Create a ServiceContext with Auth tokens and realmId ServiceContext serviceContext = new ServiceContext(realmId, IntuitServicesType.QBO, oauthValidator); serviceContext.IppConfiguration.MinorVersion.Qbo = "23"; // Create a QuickBooks QueryService using ServiceContext QueryService<CompanyInfo> querySvc = new QueryService<CompanyInfo>(serviceContext); CompanyInfo companyInfo = querySvc.ExecuteIdsQuery("SELECT * FROM CompanyInfo").FirstOrDefault(); string output = JsonConvert.SerializeObject(companyInfo, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return View("ApiCallService", (object)("QBO API call Successful!! Response: " + output)); } |
The CallbackController has two key methods:
After user clicks on Connect button in authorization flow, the request is sent to Intuit servers. When successful, Intuit responds with an authorization code and the QuickBooks Company ID (i.e. the Realm ID) on the Redirect URL as callback URL query parameters.
1 2 3 4 5 6 public async Task<ActionResult> Index() { string code = Request.QueryString["code"] ?? "none"; string realmId = Request.QueryString["realmId"] ?? "none"; await GetAuthTokensAsync(code, realmId); }
This authorization code is exchanged for Access and Refresh Tokens using the TokenEndpoint. Access tokens are used in an API request and Refresh tokens are used to get fresh short-lived Access tokens after they expire.
1 2 3 4 5 6 7 private async Task GetAuthTokensAsync(string code, string realmId) { var tokenResponse = await auth2Client.GetBearerTokenAsync(code); var accessToken = tokenResponse.AccessToken; var refreshToken = tokenResponse.RefreshToken; }
Before you start, you should have a basic understanding of Spring Boot.
Start by installing the following on your machine:
Use the commands below to clone the “Hello World” repo:
1 2 | git clone https://github.com/IntuitDeveloper/HelloWorld-Java.git cd HelloWorld-Java |
This repo gives you basic code to build the demo app. It sets up your development environment so you can use an SDK, handles authorization set up (OAuth 2.0 protocol), and simplifies logging.
Now you have sample code. Create an app on our portal:
This generates credentials and lets you set the demo’s URIs. You can use these credentials on a QuickBooks Online Sandbox company. Click here to create one.
When users connect to your app, it needs to redirect them to start the authorization flow. This “user consent” step is where they give your app permission to access their QuickBooks Online company data.
Let’s redirect users who connect to your “Demo app” to the callback page. Use the provided http://localhost address for the URI:
For this demo, we’ll assume a user found your app on the QuickBooks App Store and selected the Connect to QuickBooks link. This is just one of several ways to initiate the authorization flow.
Let’s make a few edits in the cloned “Hello World” repo:
1 2 3 | #OAuth2 App Configuration OAuth2AppClientId=add your clientId OAuth2AppClientSecret=add your clientSecret |
View Screenshot
View Screenshot
After you select Connect, you’ll redirect to the URI you added in Step 4.
If users authorize your app, our server sends an authorization code to your app. You’ll exchange the authorization code for access tokens. For this demo, the Intuit OAuth 2.0 server will automatically handle the backend exchange of temporary authorization codes for tokens.
Let’s assume the “Demo app” has access tokens and simulate your first API call. You’ll redirect to a new webpage via the URI (i.e. http://localhost:8080/oauth2redirect).
View Screenshot
Select the QuickBooks CompanyInfoAPI Call button. This makes an API call to the CompanyInfo
entity for the sandbox company you just connected.
Now you have a good understanding of the basic development and authorization process. Download one of our SDKs to get a jumpstart on development.
This file holds all the configurations to run your app. Client Id and Client Secret should be entered for OAuth2AppClientId and OAuth2AppClientSecret fields. These values are used by your app to uniquely establish its identity with the QuickBooks Online platform.
The value of Redirect URI should match the value configured in application.properties. This url defines where your app’s customer will be redirected in your app after they authorize the app.
The HomeController has three request mappings:
Here’s an example code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @RequestMapping("/connectToQuickBooks") public View connectToQuickBooks(HttpSession session) { //prepare OAuth2Config OAuth2Config oauth2Config = factory.getOAuth2Config(); //generate csrf token String csrf = oauth2Config.generateCSRFToken(); //retrieve redirectUri from application.properties String redirectUri = factory.getPropertyValue("OAuth2AppRedirectUri"); //prepare scopes List<Scope> scopes = new ArrayList<Scope>(); scopes.add(Scope.Accounting); //prepare authorization url to intiate the oauth handshake return new RedirectView(oauth2Config.prepareUrl(scopes, redirectUri, csrf), true, true, false); }
In the code above, we initialize the OAuth2Config object by providing the client id and secret and specifying the environment (sandbox or production) to make the API calls.
The SDK internally calls the discovery document (this is part of the OAuth2Client initialization). Discovery documents contain API-level properties such as an API description, resource schemas, authentication scopes, and methods) to populate the url’s needed for the oauth handshake and returns the initialized object back.
We then prepare the essential parameters needed for the request such as scope, redirect uri, state (a unique identifier or any other information that might be useful to your application) and prepare the authorization url to initiate the OAuth handshake.
This method receives the callback from Intuit’s OAuth service after the authorization flow. The server sends a temporary authorization code and the QuickBooks company id (also called as realmId) to the callback endpoint.
This authorization code is exchanged for Access and Refresh Tokens using the TokenEndpoint. Access tokens are used in an API request and Refresh tokens are used to get fresh short-lived Access tokens after they expire.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @RequestMapping("/oauth2redirect") public String callBackFromOAuth(@RequestParam("code") String authCode, @RequestParam(value = "realmId") String realmId) { //prepare OAuth2Platform client OAuth2PlatformClient client = factory.getOAuth2PlatformClient(); //retrieve redirectUri from application.properties String redirectUri = factory.getPropertyValue("OAuth2AppRedirectUri"); //retrieve access token by calling the token endpoint BearerTokenResponse bearerTokenResponse = client.retrieveBearerTokens(authCode, redirectUri); return "connected"; } |
Once you have the access token, you can use it to make API calls. The method below illustrates how to make a CompanyInfo API call.
callQBOCompanyInfo: We first initialize DataService object by passing the realm Id and accessToken. We then call the executeQuery method of the service class to get company information. The data query can be modified to execute any QuickBooks Online API supported query as a String in the parameter as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @ResponseBody @RequestMapping("/getCompanyInfo") public String callQBOCompanyInfo(HttpSession session) { //get DataService DataService service = helper.getDataService(realmId, accessToken); // get all companyinfo String sql = "select * from companyinfo"; QueryResult queryResult = service.executeQuery(sql); CompanyInfo companyInfo = (CompanyInfo) queryResult.getEntities().get(0); // process response ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(companyInfo); } |
To start, install the following on your machine:
Use the commands below to clone the “Hello World” repo:
1 2 3 4 | git clone https://github.com/IntuitDeveloper/HelloWorld-PHP.git cd HelloWorld-PHP curl -sS https://getcomposer.org/installer | php composer install |
This repo gives you basic code to build the demo app. It sets up your development environment so you can use an SDK, handles authorization set up (OAuth 2.0 protocol), and simplifies logging.
Now you have sample code. Create an app on our portal:
This generates credentials and lets you set the demo’s URIs. You can use these credentials on a QuickBooks Online Sandbox company. Click here to create one.
When users connect to your app, it needs to redirect them to start the authorization flow. This “user consent” step is where they give your app permission to access their QuickBooks Online company data.
Let’s redirect users who connect to your “Demo app” to the callback page. Use the provided http://localhost address for the URI:
For this demo, we’ll assume a user found your app on the QuickBooks App Store and selected the Connect to QuickBooks link. This is just one of several ways to initiate the authorization flow.
Let’s make a few edits in the cloned “Hello World” repo:
1 2 | 'client_id' => 'Enter the clietID from Developer Portal', 'client_secret' => 'Enter the clientSecret from Developer Portal', |
View Screenshot
View Screenshot
After you select Authorize, you’ll redirect to the URI you added in Step 4.
If users authorize your app, our server sends an authorization code to your app. You’ll exchange the authorization code for access tokens. For this demo, the Intuit OAuth 2.0 server will automatically handle the backend exchange of temporary authorization codes for tokens.
Let’s assume the “Demo app” has access tokens and simulate your first API call. You’ll redirect to a new webpage via the URI (i.e. http://localhost:3000/callback).
View Screenshot
Select the Get Company Info button. This makes an API call to the CompanyInfo
entity for the sandbox company you just connected.
Now you have a good understanding of the basic development and authorization process. Download one of our SDKs to get a jumpstart on development.
Learn more about downloaded docs and parameters
To connect to QuickBooks, developers will need to provide following necessary parameters to the DataService object:
The DataService object will be used to construct OAuth2LoginHelper object.
The OAuth2LoginHelper will help developers to complete all the necessary steps for retrieving access tokens required to connect your app to the user’s QuickBooks Online company.
We use the OAuth2LoginHelper object to generate Authorization Code URL in the index.php file, we then render the Authorization Code URL on the browser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <?php require_once(__DIR__ . '/vendor/autoload.php'); use QuickBooksOnline\API\DataService\DataService; $config = include('config.php'); session_start(); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $config['client_id'], 'ClientSecret' => $config['client_secret'], 'RedirectURI' => $config['oauth_redirect_uri'], 'scope' => $config['oauth_scope'], 'baseUrl' => "development" )); $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper(); $authUrl = $OAuth2LoginHelper->getAuthorizationCodeURL(); // Store the url in PHP Session Object; $_SESSION['authUrl'] = $authUrl; //set the access token using the auth object if (isset($_SESSION['sessionAccessToken'])) { $accessToken = $_SESSION['sessionAccessToken']; $accessTokenJson = array('token_type' => 'bearer', 'access_token' => $accessToken->getAccessToken(), 'refresh_token' => $accessToken->getRefreshToken(), 'x_refresh_token_expires_in' => $accessToken->getRefreshTokenExpiresAt(), 'expires_in' => $accessToken->getAccessTokenExpiresAt() ); $dataService->updateOAuth2Token($accessToken); $oauthLoginHelper = $dataService -> getOAuth2LoginHelper(); $CompanyInfo = $dataService->getCompanyInfo(); } ?> |
Once the Authorization Code URL is displayed to the users, they will start authorizing the app, an authorization code with realmId will be returned to the redirect URI we specified in config.php file.
We will pass these values to the OAuth2LoginHelper object to generate our token. After this, the token generation step is considered complete.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <?php require_once(__DIR__ . '/vendor/autoload.php'); use QuickBooksOnline\API\DataService\DataService; session_start(); function processCode() { // Create SDK instance $config = include('config.php'); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $config['client_id'], 'ClientSecret' => $config['client_secret'], 'RedirectURI' => $config['oauth_redirect_uri'], 'scope' => $config['oauth_scope'], 'baseUrl' => "development" )); $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper(); $parseUrl = parseAuthRedirectUrl($_SERVER['QUERY_STRING']); /* * Update the OAuth2Token */ $accessToken = $OAuth2LoginHelper->exchangeAuthorizationCodeForToken($parseUrl['code'], $parseUrl['realmId']); $dataService->updateOAuth2Token($accessToken); /* * Setting the accessToken for session variable */ $_SESSION['sessionAccessToken'] = $accessToken; } function parseAuthRedirectUrl($url) { parse_str($url,$qsArray); return array( 'code' => $qsArray['code'], 'realmId' => $qsArray['realmId'] ); } $result = processCode(); ?> |