Build a demo app

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

  1. Sign in to your developer account.
  2. Visit the API Explorer.
  3. Choose a sandbox company from the dropdown.
  4. Find an API entity and operation.
  5. Select Try it.

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

.NET
Step 1: Clone the “Hello world” repository

Before you start, you should have a basic understanding of ASP.NET MVC Framework.


Start by installing the following on your machine:

  • Visual Studio 2015 or later
  • .Net framework 4.6.1
  • IIS or IIS Express 8.0

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.

Step 2: Create a demo app on the Intuit Developer Portal

Now you have sample code. Create an app on the developer portal:


  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Create an app specifically for this demo. Name it “Demo app”.
  4. Select the Accounting scope from the Select a scope dropdown.
  5. If you haven’t already, create a QuickBooks Online sandbox company for testing.

This generates credentials and lets you set the demo’s URIs.

Step 3: Get the demo app’s credentials
  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Select and open the “Demo app” app you just created.
  4. Go to the Development section and select Keys & OAuth.
  5. Copy the Client ID and Client Secret.
Step 4: Add the cloned “Hello world” repo’s redirect URI

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:


  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Select and open the “Demo app.”
  4. Go to the Development section and select Keys & OAuth.
  5. In the Redirect URIs section, select the Link field.
  6. Enter: http://localhost:27353/callback.
  7. Select Save.
Step 5: Configure the authorization flow

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. Open and edit the Web.config file in the root directory of the “Hello World” repo you cloned in Step 1.
  2. Edit the file using the sample code below.
  3. Enter the Client ID and Client Secret for your “Demo app.”
  4. Review the Redirect URI.

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>
Step 6: Simulate the authorization flow
  1. Launch your app in Visual Studio.
  2. Select Connect to QuickBooks.
  3. Follow the onscreen steps to connect a sandbox company. Sign in using the same sign-in and password as your developer account.
  4. Select Authorize.

View Screenshot

../../../_images/build-net-screenshot2.png

View Screenshot

../../../_images/build-net-screenshot3.png

After you select Authorize, you’ll redirect to the URI you added in Step 4.

Step 7: Make your first API call

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

../../../_images/build-net-screenshot4.png

This automatically makes an API call to the CompanyInfo entity for the sandbox company you just connected.

Start building your app using a .NET SDK

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

Here’s more info about:

  • Web.config with your app’s configuration
  • AppController which has the homepage, initiates authorization flow, makes API request
  • CallbackController which handles redirection after QuickBooks Online users authorize your app, exchanges authorization code to get Access and Refresh tokens, and then gives control back to AppController.

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 OAuth2Client object

Initialize the OAuth2Client object with clientid, clientecret, redirectUrl and appEnvironment

1
public static OAuth2Client auth2Client = new OAuth2Client(clientid, clientsecret, redirectUrl, environment);
  • InitiateAuth (string submitButton)

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);
    }
  • ApiCallService()

Once the tokens are received, apps can make calls to the QuickBooks Online Accounting API.

  • First, create a ServiceContext object. ServiceContext is created with API Access Token along with the realmId and works as a context for the API request.
  • This ServiceContext object can then be used in QueryService to query for CompanyInfo data.
  • QueryService can be used to execute any API supported query as a string in a parameter as shown below:

 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:

  • Index()

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);
}
  • GetAuthTokensAsync(string code, string 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;
}
Java
Step 1: Clone the “Hello world” repository

Before you start, you should have a basic understanding of Spring Boot.


Start by installing the following on your machine:

  • Java 1.8

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.

Step 2: Create a demo app on the Intuit Developer Portal

Now you have sample code. Create an app on our portal:


  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Create an app specifically for this demo. Name it “Demo app”.
  4. Select the Accounting scope from the Select a scope dropdown.
  5. If you haven’t already, create a QuickBooks Online sandbox company for testing.

This generates credentials and lets you set the demo’s URIs.

Step 3: Get the demo app’s credentials
  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Select and open the “Demo app” app you just created.
  4. Go to the Development section and select Keys & OAuth.
  5. Copy the Client ID and Client Secret.
Step 4: Add the cloned “Hello world” repo’s redirect URI

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:


  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Select and open the “Demo app.”
  4. Go to the Development section and select Keys & OAuth.
  5. In the Redirect URIs section, select the Link field.
  6. Enter: http://localhost:8080/oauth2redirect.
  7. Select Save.
Step 5: Configure the authorization flow

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. Open and edit the application.properties file in the resources folder (src/main/resources) folder of the “Hello World” repo you cloned in Step 1.
  2. Edit the file using the sample code below.
  3. Enter the Client ID and Client Secret for your “Demo app.”
  4. Review the Redirect URI.

1
2
3
#OAuth2 App Configuration
OAuth2AppClientId=add your clientId
OAuth2AppClientSecret=add your clientSecret
Step 6: Simulate the authorization flow
  1. For Mac OS, open Terminal and run the command ./gradlew bootRun. For Windows, open cmd.exe and run the command gradlew.bat bootRun.
  2. Open a web browser and go to http://localhost:8080/. This launches the authorization flow.
  3. Select Connect to QuickBooks.
  4. Follow the onscreen steps to connect a sandbox company. Sign in using the same sign-in and password as your developer account.
  5. Select Authorize.

View Screenshot

../../../_images/build-java-screenshot2.png

View Screenshot

../../../_images/build-java-screenshot3.png

After you select Connect, you’ll redirect to the URI you added in Step 4.

Step 7: Make your first API call

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

../../../_images/build-java-screenshot4.png

Select the QuickBooks CompanyInfoAPI Call button. This makes an API call to the CompanyInfo entity for the sandbox company you just connected.

Start building your app using a Java SDK

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

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:

  • home: Redirects to home page - index.html
  • connected: Redirects to connected page after authorization - connect.html
  • connectToQuickBooks: Initiates the Authorization Flow by specifying the Accounting scope, Client Id, Redirect Url to redirect user to AuthorizeEndpoint.

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.


Note: Here’s how to view the complete code. The code above has reference to factory class that initializes OAuth2Config and reads data from application.properties. This is a helper class that is shared across all Controllers.

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);
}
PHP
Step 1: Clone the “Hello world” repository

To start, install the following on your machine:

  • PHP > 5.6
  • Composer
  • Git Client

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.

Step 2: Create a demo app on the Intuit Developer Portal

Now you have sample code. Create an app on our portal:

  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Create an app specifically for this demo. Name it “Demo app”.
  4. Select the Accounting scope from the Select a scope dropdown.
  5. If you haven’t already, create a QuickBooks Online sandbox company for testing.

This generates credentials and lets you set the demo’s URIs.

Step 3: Get the demo app’s credentials
  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Select and open the “Demo app” app you just created.
  4. Go to the Development section and select Keys & OAuth.
  5. Copy the Client ID and Client Secret.
Step 4: Add the cloned “Hello world” repo’s redirect URI

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:


  1. Sign in to your developer account.
  2. Select the Dashboard link on the toolbar.
  3. Select and open the “Demo app.”
  4. Go to the Development section and select Keys & OAuth.
  5. In the Redirect URIs section, select the Link field.
  6. Enter: http://localhost:3000/callback.
  7. Select Save.
Step 5: Configure the authorization flow

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. Open and edit the config.php file in the “Hello World” repo you cloned in Step 1.
  2. Edit the file using the sample code below.
  3. Enter the Client ID and Client Secret for your “Demo app.”
  4. Review the Redirect URI.

1
2
'client_id' => 'Enter the clietID from Developer Portal',
'client_secret' => 'Enter the clientSecret from Developer Portal',
Step 6: Simulate the authorization flow
  1. For Mac OS, open Terminal and run $ php -S localhost:3000.
  2. Open a web browser and go to localhost:3000. This launches the authorization flow.
  3. Select Connect to QuickBooks.
  4. Follow the onscreen steps to connect a sandbox company. Sign in using the same sign-in and password as your developer account.
  5. Select Authorize.

View Screenshot

../../../_images/build-php-screenshot2.png

View Screenshot

../../../_images/build-php-screenshot3.png

After you select Authorize, you’ll redirect to the URI you added in Step 4.

Step 7: Make your first API call

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

../../../_images/build-php-screenshot4.png

Select the Get Company Info button. This makes an API call to the CompanyInfo entity for the sandbox company you just connected.

Start building your app using a PHP SDK

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

  • The index.php file will have the homepage, initiates authorization flow, makes API request
  • The callback.php file handles redirection after QuickBooks users authorize an app, exchanges authorization code to get Access and Refresh tokens and then gives control back to index.php file.

To connect to QuickBooks, developers will need to provide following necessary parameters to the DataService object:

  • auth_mode: It will be “oauth2’” here
  • Client ID: “Client ID” from the app’s keys tab
  • Client Secret: “Client Secret” from the app’s keys tab
  • RedirectURI: Determines where the response is sent. The value of this parameter must exactly match one of the values listed for this app in the app settings
  • scope: the amount of access that is granted to the DataService, it is “com.intuit.quickbooks.accounting”
  • baseUrl: The API endpoint used for this application.

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();

?>