Build your first app

Build your first app

You’ll learn how to create and run a new application, i.e., a “Hello World App”, with QuickBooks Online.

qbo/docs/workflow-related-7.svg

.NET

Java

PHP

Prerequisites:

1

To follow this tutorial, you will need the following installed on your machine:

a
Visual Studio 2015 or later
b
.Net framework 4.6.1
c
IIS or IIS Express 8.0
2
You have basic knowledge of ASP.NET MVC Framework.
  1. Clone Hello World App to get started

1
2
$ git clone https://github.com/IntuitDeveloper/HelloWorldApp-MVC5-Dotnet
$ cd HelloWorldApp-MVC5-Dotnet
To run Hello World App, you will need to create and configure an app on developer portal to allow accessing QuickBooks Online.
  1. Create and Configure an App in Developer portal
If you have already created an app in the developer portal, you can skip to step 2.d
1
Sign into the developer portal and click My Apps.
2
Click Create new app .
3

Click Select APIs under Just start coding.

View Screenshot

qbo/docs/build-screenshot1.png
4

Select Accounting and click on Create app.

View Screenshot

qbo/docs/build-screenshot2.png
5

Click on the Keys tab to get your development keys – Client ID and Client Secret – from the developer portal.


View Screenshot

qbo/docs/build-screenshot3.png
6

As a developer of this App, you have to redirect customers using your app after they go through authorization flow. For this Tutorial, we will redirect users of Hello World App to the callback page. Set the Redirect URI in the Keys tab. For Hello, World! Sample app, Redirect URL is http://localhost:27353/callback

View Screenshot

qbo/docs/build-net-screenshot1.png
  1. Go through Authorization flow
To get access to data of a QuickBooks company, a QBO user must authorize your app through an authorization flow. You will get an Access Token at the end of the process which is used to make QBO API requests. To initiate the authorization flow, QBO users click on Connect to QuickBooks button.
Creating a developer account also creates a QuickBooks test company (also referred to as Sandbox company). You will use this Sandbox company to go through the authorization flow to see what it looks like.
1
Let’s configure the “Hello, World” app first with your Client Id, Client Secret and Redirect URI. Modify the Web.config file located in the root directory of your Hello World app.

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>
2

Launch your app in Visual Studio, which looks like:

View Screenshot

qbo/docs/build-net-screenshot2.png
3

Click Connect to QuickBooks to connect your app with the Sandbox company. Sign In with your developer account and click Authorize

View Screenshot

qbo/docs/build-net-screenshot3.png
  1. Make first API call
After you click Authorize, you are redirected to the URI you specified earlier, i.e., http://localhost:27353/callback

On this web page, you will make your first API call to the Sandbox QuickBooks company you connected to and get the CompanyInfo.

View Screenshot

qbo/docs/build-net-screenshot4.png

Important

Congratulations

You have just developed your first QuickBooks app!

  1. Review the code
The code we will review here is Web.config with your app’s configuration, AppController which has the homepage, initiates authorization flow, makes QBO API request and CallbackController which handles redirection after QBO user has authorized an app, exchanges authorization code to get Access and Refresh tokens and then gives control back to AppController.
Client Id and Client Secret that you retrieved in Step 2.5 from the developer portal. These tokens are used by your app to uniquely establish its identity with the QuickBook online platform.
The value of Redirect URI will define where your app’s customer will be redirected in your app after they authorize the app. Specify which environment your application is running in with appEnvironment value so that OAuth2Client can get the right Discovery document (this is done as part of the OAuth2Client initialization). Discovery documents contains AuthorizationEndpoint, TokenEndpoint, etc required for the OAuth 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>
AppController has these important steps:
1

Initialize OAuth2Client object

Initialize OAuth2Client object with clientid, clientecret, redirectUrl and appEnvironment

1
public static OAuth2Client auth2Client = new OAuth2Client(clientid, clientsecret, redirectUrl, environment);
2

InitiateAuth(string submitButton)

To initiate the Authorization Flow, specify the Accounting scope. Use GetAuthorizationURL method of OAuth2Client object to get the Authorization URL. It is redirected to show the QBO user Connect screen shown in step 3.3 above. Snippet of code is shown here.

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);
}
3

ApiCallService()

Once the tokens are received, they can be used to make QBO API calls. First, create a ServiceContext object. ServiceContext is created with API Access Token along with the QBO RealmId and works as a context for the API request. This ServiceContext object is then used in QueryService to query for CompanyInfo data. QueryService can be used to execute any QBO 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
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));
}
CallbackController has 2 important methods:
1

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 QBO Company ID (also called 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);
}
2

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;
}

Prerequisites:

1
To follow this tutorial, you will need Java 1.8 installed on your machine.
2
You should have basic knowledge of Spring Boot.
  1. Clone Hello World App to get started

1
2
$ git clone https://github.com/IntuitDeveloper/HelloWorld-Java.git
$ cd HelloWorld-Java
To run Hello World App, you will need to create and configure an app on developer portal to allow accessing QuickBooks Online.
  1. Create and Configure an App in Developer portal
1
Sign into the developer portal and click My Apps.
2
Click Create new app .
3

Click Select APIs under Just start coding.

View Screenshot

qbo/docs/build-screenshot1.png
4

Select Accounting and click on Create app.

View Screenshot

qbo/docs/build-screenshot2.png
5

Click on the Keys tab to get your development keys – Client ID and Client Secret – from the developer portal.


View Screenshot

qbo/docs/build-screenshot3.png
6

As a developer of this App, you have to redirect customers using your app after they go through authorization flow. For this Tutorial, we will redirect users of Hello World App to following callback page http://localhost:8080/oauth2redirect. Set the Redirect URI in the Keys tab with the same url.

View Screenshot

qbo/docs/build-java-screenshot1.png
  1. Go through Authorization flow
To get access to data of a QuickBooks company, a QBO user must authorize your app through an authorization flow. You will get an Access Token at the end of the process which is used to make QBO API requests. To initiate the authorization flow, QBO users click on Connect to QuickBooks button which is added to the home page of the app.
Creating a developer account also creates a QuickBooks test company (also referred to as Sandbox company). You will use this Sandbox company to go through the authorization flow to see what it looks like.
1
Let’s configure the “Hello, World” app first with your Client Id, Client Secret and Redirect URI. Modify the application.properties file located in the resources (src/main/resources) folder of the Hello World app to add the client id and secret from your app.

1
2
3
#OAuth2 App Configuration
OAuth2AppClientId=add your clientId
OAuth2AppClientSecret=add your clientSecret
2

Run the command ./gradlew bootRun (Mac OS) or gradlew.bat bootRun (Windows) from the terminal and launch the app in your browser by going to the url http://localhost:8080/

View Screenshot

qbo/docs/build-java-screenshot2.png
3

Click Connect to QuickBooks to connect your app with the Sandbox company. Sign In with your developer account and click Connect to authorize access to your data to the app.

View Screenshot

qbo/docs/build-java-screenshot3.png
  1. Make first API call
After you click Connect, you are redirected to the URI you specified earlier, i.e., http://localhost:8080/oauth2redirect where the temporary authorization code returned by Intuit’s OAuth service is exchanged to obtain the accessToken.

The callback controller then redirects to the “Connected” page where you will make your first API call to the Sandbox QuickBooks company you just connected to and get the CompanyInfo.

View Screenshot

qbo/docs/build-java-screenshot4.png

Important

Congratulations

You have just developed your first QuickBooks app!

  1. Review the code
This file holds all the configurations to run your app. Client Id and Client Secret that you retrieved in Step 2.5 from the developer portal 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 in Step 2.6 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.
HomeController has 3 request mappings:
1
home - Redirects to home page - index.html
2
connected - Redirects to connected page after authorization - connect.html
3
connectToQuickBooks - Initiates the Authorization Flow by specifying the Accounting scope, Client Id, Redirect Url to redirect user to AuthorizeEndpoint. Snippet of code is shown here.

 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 (a resource that has information about the API-level properties such as an API description, resource schemas, authentication scopes, and methods)I 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: Click here 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.
callBackFromOAuth - This method receives the callback from the 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";

}

Note: Click here to view the complete code.

Once the access token is obtained, it can be used to make QBO 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 QBO 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);
}

Note: Click here to view the complete code.

Prerequisites:

1

To follow this tutorial, you will need the following installed on your machine:

a
PHP > 5.6
b
Composer
c
Git Client
  1. Clone Hello World App to get started
Cloning Hello World App is the best way to bootstrap building a new QuickBooks application. It sets up your development environment so that you can use the latest SDK, provides a nice developer experience by enabling logging, and optimizes your app for production.

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
To run Hello World App, you will need to create and configure an app to allow accessing QuickBooks Online in the developer portal.
  1. Create and Configure an App in Developer portal
1
Sign into the developer portal and click My Apps on the top right corner.
2
Click Create new app .
3

Click Select APIs under Just start coding.

View Screenshot

qbo/docs/build-screenshot1.png
4

Select Accounting and click on Create app.

View Screenshot

qbo/docs/build-screenshot2.png
5

Click on the Keys tab to get your development keys – Client ID and Client Secret –from the developer portal.


View Screenshot

qbo/docs/build-screenshot3.png
6

As a developer of this App, you have to redirect customers using your app after they go through authorization flow. For this Tutorial, we will redirect users of Hello World App to the callback page. Set the Redirect URI in the Keys tab. For Hello, World! Sample app, Redirect URL is http://localhost:3000/callback

View Screenshot

qbo/docs/build-php-screenshot1.png
  1. Go through Authorization flow
To get access to data of a QuickBooks company, a QBO user must authorize your app through an authorization flow. You will get an Access Token at the end of the process which is used to make QBO API requests. To initiate the authorization flow, QBO users click on Connect to QuickBooks button.
Creating a developer account also creates a QuickBooks test company (also referred to as Sandbox company). You will use this Sandbox company to go through the authorization flow to see what it looks like.
1
Let’s configure the “Hello, World” app first with your Client Id, Client Secret and Redirect URI. Edit the config.php file to add your apps’ clientId and clientSecret

1
2
'client_id' => 'Enter the clietID from Developer Portal',
'client_secret' => 'Enter the clientSecret from Developer Portal',
2
Run your Hello World app on terminal by typing:

1
$ php -S localhost:3000
3

Open a browser, type localhost:3000, and you are ready to go. A window like this will present on your browser:

View Screenshot

qbo/docs/build-php-screenshot2.png
3

Click Connect to QuickBooks to connect your app with the Sandbox company. Sign In with your developer account and click Authorize.

View Screenshot

qbo/docs/build-php-screenshot3.png
  1. Make first API call
After you click Authorize, you are redirected to the URI you specified earlier, i.e., http://localhost:3000/callback

Now you are ready to make your first API call to the Sandbox QuickBooks company you connected to and get the CompanyInfo. Click on Get Company Info button, and you will see the result of your Company info:

View Screenshot

qbo/docs/build-php-screenshot4.png

Important

Congratulations

You have just developed your first QuickBooks app!

  1. Review the code
Below we will talk about the logics we used in the HelloWorld PHP sample. The index.php file will have the homepage, initiates authorization flow, makes QBO API request and callback.php which handles redirection after QBO user has authorized an app, exchanges authorization code to get Access and Refresh tokens and then gives control back to index.php file.

Explain index.php


In order 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, refer to Step 2
  • Client Secret: “Client Secret” from the app’s keys tab, refer to Step 2
  • 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 QBO 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();
    }
?>

Explain callback.php


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 RedirectURI we specified in config.php file. We will pass these values to the OAuth2LoginHelper object to generate our token.

After this step, the OAuth 2 token generation step is considered as 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();

?>
What’s next