QuickBooks API Integration With Working Example.

This example uses the Intuit API V3 SDK version 8.1.0 and the Microsoft MVC framework written in C#

The full working example can be downloaded from GitHub

Have you ever needed to integrate your app with Intuit QuickBooks, in this blog which will be over two parts, I will show you how to do the following:

In today's blog, I will show you how to add the clientSecret and clientId, so that you can return an AccessToken and RefreshToken using the Intuit developer QuickBooks API.

To start ensure that you have an Intuit developer account setup as you will need to use the sandbox.  

So let's get started, first create the class that will retrieve our credentials from the web.config appSettings

using System.Configuration;

namespace QuickBooksIntergration.Models
{
    public static class ConfigurationTuples
    {
        public static (string clientId, string clientSecret, string redirectUrl, string appEnvironment) ReturnIntuitAppSettings()
        {
            string clientId         = ConfigurationManager.AppSettings["clientId"];
            string clientSecret     = ConfigurationManager.AppSettings["clientSecret"];
            string redirectUrl      = ConfigurationManager.AppSettings["redirectUrl"];
            string appEnvironment   = ConfigurationManager.AppSettings["appEnvironment"];

            return (clientId, clientSecret, redirectUrl, appEnvironment);
        }
    }
}

Next, create our TokenModel as we will be using this later.

using System;

namespace QuickBooksIntergration.Models.OAuth2ClientModel
{
    public class TokenModel
    {
        public string AccessToken                   { get; set; }
        public DateTime AccessTokenExpires          { get; set; }
        public string AccessRefreshToken            { get; set; }
        public DateTime AccessRefreshTokenExpires   { get; set; }
        public string RealmId                       { get; set; }
    }
}

Next, we need to create the OAuth2Client class that creates the Intuit developer GetAuthorizationURL.

using System.Collections.Generic;
using Intuit.Ipp.OAuth2PlatformClient;

namespace QuickBooksIntergration.Models.OAuth2ClientModel
{
    public static class OAuth2ClientModel
    {
        public static string OAuth2Client(List scopes)
        {
            OAuth2Client client = new OAuth2Client(clientID: ConfigurationTuples.ReturnIntuitAppSettings().clientId, clientSecret: ConfigurationTuples.ReturnIntuitAppSettings().clientSecret, redirectURI: ConfigurationTuples.ReturnIntuitAppSettings().redirectUrl, environment: ConfigurationTuples.ReturnIntuitAppSettings().appEnvironment);

            //AS OFF 24 Nov 2021, DO NOT UPGRADE Serilog as it throws the following error: System.MissingMethodException: Method not found:
            return client.GetAuthorizationURL(scopes:scopes);
        }
        
    }
}

After that, create our controller, this is a simple controller and the code is below.

using System.Collections.Generic;
using System.Web.Mvc;
using Intuit.Ipp.OAuth2PlatformClient;
using QuickBooksIntergration.Models.OAuth2ClientModel;

namespace QuickBooksIntergration.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Authenticate()
        {
            List scopes = new List
            {
                OidcScopes.Accounting
            };

            string authorizeUrl = OAuth2ClientModel.OAuth2Client(scopes);
            return Redirect(authorizeUrl);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        [HttpGet]
        public ActionResult CallBack(string code = "none", string realmId = "none")
        {

            OAuthToken token = new OAuthToken();

            token.GetOAuthToken(code, realmId);

            return View();
        }
    }
}

Once all that is done, you will need the code to create the customer, in this post the values are hardcoded, but in the next post, I will move the code into a separate class.

using System;
using System.IO;
using System.Web;
using Intuit.Ipp.Core;
using Intuit.Ipp.Data;
using Intuit.Ipp.DataService;
using Intuit.Ipp.OAuth2PlatformClient;
using Intuit.Ipp.QueryFilter;
using Intuit.Ipp.Security;
using Newtonsoft.Json;
using System.Linq;
using SystemTask = System.Threading.Tasks.Task;

namespace QuickBooksIntergration.Models.OAuth2ClientModel
{
    public class OAuthToken
    {
        public void GetOAuthToken(string code, string realmId)
        {
            OAuth2Client client                     = new OAuth2Client(clientID: ConfigurationTuples.ReturnIntuitAppSettings().clientId, clientSecret: ConfigurationTuples.ReturnIntuitAppSettings().clientSecret, redirectURI: ConfigurationTuples.ReturnIntuitAppSettings().redirectUrl, environment: ConfigurationTuples.ReturnIntuitAppSettings().appEnvironment);
            var intuitResponse                      = SystemTask.Run(() => client.GetBearerTokenAsync(code)).Result;

            DateTime dtAccessTokenExpiresIn         = DateTime.Now.AddSeconds(intuitResponse.AccessTokenExpiresIn);  //Valid for 60 minutes
            DateTime dtAccessRefreshTokenExpires    = DateTime.Now.AddSeconds(intuitResponse.RefreshTokenExpiresIn); //Valid for 100 days
            
            //save access token and refresh token to disk
            TokenModel model = new TokenModel
            {
                AccessToken                 = intuitResponse.AccessToken,
                AccessTokenExpires          = dtAccessTokenExpiresIn,
                AccessRefreshToken          = intuitResponse.RefreshToken,
                AccessRefreshTokenExpires   = dtAccessRefreshTokenExpires,
                RealmId                     = realmId
            };

            var dir         = HttpContext.Current.Server.MapPath("~/IntuitToken");
            var file        = Path.Combine(dir, "intuitToken.json");
            string serilizeToken   = JsonConvert.SerializeObject(model);
            File.WriteAllText(file, serilizeToken);

           

            OAuth2RequestValidator oAuth2RequestValidator = new OAuth2RequestValidator(intuitResponse.AccessToken);
            ServiceContext serviceContext = new ServiceContext(realmId: realmId, IntuitServicesType.QBO,oAuth2RequestValidator);
            serviceContext.IppConfiguration.MinorVersion.Qbo = "62";
            serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/";


            QueryService customerQueryService = new QueryService(serviceContext);

            DataService dataService = new DataService(serviceContext);


            Customer customer = new Customer
            {
                CompanyName = "Company Name",
                DisplayName = "Display Name",
                Title = "Mr",
                FamilyName = "Family Name",
                GivenName = "Given Name",
                MiddleName = "Middle Name",
                BillAddr = new PhysicalAddress
                {
                    Line1 = "Line 1",
                    City = "Washington",
                    CountrySubDivisionCode = "Tyne Wear",
                    PostalCode = "NE36 9PP",
                    Country = "United Kingdom"
                },
                PrimaryEmailAddr = new EmailAddress
                {
                    Address = "test@test.com"
                },
                PrimaryPhone = new TelephoneNumber
                {
                    FreeFormNumber = "+44191789456"
                }
            };

            dataService.Add(customer);

            //Sanity check that the customer was created.
            Customer customerCount = customerQueryService.ExecuteIdsQuery("SELECT * FROM Customer WHERE PrimaryEmailAddr = 'test@test.com'").FirstOrDefault();
        }
    }
}

And that's it after you add the customer a simple sanity check is run to see if the customer was created and you can also log in to your Intuit account and check the customer is there as the image below shows.

QuickBooks API Integration

In the next blog, I will show you how to attach an invoice to the customer, thanks for reading.