Implement Intuit’s QuickBooks Online API in RESTFUL Service C#

If you don’t know anything about QuickBooks, you are at right place. I will take you through each and every step necessary for implementing Intuit’s QuickBooks Online(QBO) API in RESTFUL Service C#.

Before I start talking about QuickBooks API, let me tell you that QuickBooks provides APIs for Accounting and Payment. I am going to focus on Accounting Section. Accounting Section will deal with Create/Read/Update/Delete (CRUD) Operations on customers/employees data. You can play with Invoice, Bill, Payment etc. But I will focus on Customer section.

 

What is QuickBooks?

QuickBooks is Intuit Inc’s software for small businesses to keep their finances organized and accurate. Some of the basic features include accounting, invoicing, reporting capabilities, payroll, inventory
tracking, and credit card processing etc.

 

Now, Lets get started.

First of all, we will create Intuit account to get consumerKey, consumerSecret, accessToken, accessTokenSecret, realmId/companyId and appToken. These parameters are very important to implement QuickBooks API.

 


Start Getting Keys**********************************************


 

Step 1: Visit the link mentioned below and create new account.

 https://developer.intuit.com/

Step 2: After creating your account, remember to verify your QuickBooks account by going to your email account and clicking on verification link sent by Intuit. If you don’t verify your Intuit account, you will face problems while generating keys necessary to implement QuickBooks API.

 

Step 3: Click on MyApps on the top of the page. You will be redirected to dashboard. Click Create new app button.

 

A new page with two options will open.

1. Choose an app: You can select this option to make use of sample codes. But I will not select this option, Since I am going to start from scratch.

2. Select APIs: I will select this option to create a solution from scratch.

MyApps→Create new app→Select APIs

 

Select APIs

 

Step 4: Next window will have two options

  1. Accounting

  2. Payments

Create App

I am going to select Accounting.

MyApps → Create new app → Select APIs → Accounting → CreateApp

Step 5: A new page with Dashboard will open. It will have three options:

  1. Development

  2. Production

  3. APP Cards

I am going to choose Development because I will work with sandbox while the app is in development mode, and not yet released to production. I will talk more about sandbox later.

 

Dashboard

In Development Section, you can navigate through four options:

  1. Dashboard

  2. Keys

  3. Settings

  4. Resources

Go to settings and change name of your application.

Step 6: Now click on Keys on the same Page.

You will find App Token, Consumer Key and Consumer Secret.

These key will be used to Implement QuickBooks API.

Keys

Step 7: Next you need accessToken, accessTokenSecret and realmId.

Go to QuickBooks playground by clicking this link –

https://appcenter.intuit.com/Playground/OAuth/IA

Make sure that you are already logged into your Intuit account.

Fill consumer Key, Consumer Secret and Access Token Secret (120000 seconds).

Connect to intuit icon

Now you have all keys to implement Accounting API.

Click on Connect to Intuit Icon as shown in the picture. You will be asked to select company. If you have more than one company connected to your sandbox account, choose any according to your requirement.

Then click Authorize Button.

You will get Access Token, Access Token Secret, RealmId (Company Id) and DataSource. Now you have all the keys to implement Accounting API.

 

NOTE: If you fill Access Token Duration field equals to 120000 sec, then keys will have validity of one day. By default it has a value of 120 seconds. If you get any error, then reduce Access Token Duration. Sometimes Intuit’s web pages have problem while running. So, you can also close tabs and restart again if you face some problem you don’t understand.

 


End Getting Keys**********************************************


 

Now, Lets get started with the actual implementation of Intuit’s QuickBooks Online API. I will be working with Visual Studio 2012 and Target Framework 4.5.

I will make WCF Service Application in C# to implement QuickBooks Online API in Restful Service. I will test the service though a web client Project. I will talk more about Web Client Project later.

 


Start QuickBook.service*****************************************


 

Step 1: Make WCF Service Application project as shown in picture.

WCF Service Application

 

Give name to your project and click ok. A project will be created as soon as you click ok button.

STEP 2: Installing SDK for .net framework.

Open Package Manager Console as shown in picture.

 

Nuget

 

Console screen will open at bottom of the page. Now Paste the following line in the console screen and hit enter key on keyboard.

Install-Package IppDotNetSdkForQuickBooksApiV3

 

Install Package

 

It will automatically download package. You will find new files in References Folder.

For more information, visit the link mentioned below.

https://www.nuget.org/packages/IppDotNetSdkForQuickBooksApiV3/

 

STEP 3: Now let’s change web.config file.

Add the following Code in web.config file.


<configSections>


<!–The SDK allows you to define a custom configuration for features such as
Retry and Logging
–>


<sectionGroup name=intuit>
<section name=ipp” type=Intuit.Ipp.Utility.IppConfigurationSection, 

Intuit.Ipp.Utility” allowDefinition=Everywhere” allowLocation=true/>
</sectionGroup>
</configSections>

 

Replace system.serviceModel code in web.config file with the code written below.

 

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name=servicebehavior>
<serviceMetadata httpGetEnabled=false” httpsGetEnabled=false/>
<serviceDebug includeExceptionDetailInFaults=false/>
<serviceCredentials>
<windowsAuthentication allowAnonymousLogons=false” includeWindowsGroups=true/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>


<behavior name=restbehavior>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name=QuickBooks.Service.Service1” behaviorConfiguration=servicebehavior>

<endpoint name=RESTEndPoint” address=“” binding=webHttpBinding” bindingConfiguration=wbBind

contract=QuickBooks.Service.IService1” behaviorConfiguration=restbehavior/>
</service>
</services>
<bindings>

<webHttpBinding>
<binding name=wbBind” allowCookies=false” maxReceivedMessageSize=2147483647” maxBufferSize=2147483647” maxBufferPoolSize=2147483647>
<readerQuotas maxDepth=500” maxArrayLength=2147483647” maxStringContentLength=2147483647/>
<security mode=None>
<transport clientCredentialType=None” proxyCredentialType=Windows/>
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>

 

Replace appSettings code in web.config file with the code written below.

 

<appSettings>
<add key=webpages:Version” value=3.0.0.0/>
<add key=webpages:Enabled” value=false/>
<add key=ClientValidationEnabled” value=true/>
<add key=UnobtrusiveJavaScriptEnabled” value=true/>
</appSettings>

 

I have uploaded the project on my google drive. So, you can directly download it.

 

Read the link to understand more about configuration required for implementing QuickBooks API

https://developer.intuit.com/docs/0100_accounting/0500_developer_kits/0010.net_tools/.net_sdk_for_quickbooks_v3.0/configuration#/Configuration_file_structure

 

STEP 4: Create Private Method to create Service Instance in Service1.svc file.

 

#region– Private Method –
#region – CreateServiceInstance –
private static DataService CreateServiceInstance()
{

//Key values that we got from QuickBooks Playground
var consumerKey = QuickbooksConstants.consumerKey;
var consumerSecret = QuickbooksConstants.consumerSecret;
var accessToken = QuickbooksConstants.accessToken;

var accessTokenSecret = QuickbooksConstants.accessTokenSecret;

var realmId = QuickbooksConstants.realmId;

var appToken = QuickbooksConstants.appToken;

//Assigned to your app by Intuit and displayed in the app profile as App Token
on the Intuit Developer site.

var companyID = realmId;
//TimeSpan(days, hours, minutes, seconds)
TimeSpan retryInterval = new TimeSpan(0, 0, 0, 1);

// To give a time interval of 1 second
// A valid OAuthRequestValidator object ensures that your app is
authorized to access QuickBooks data.


OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);


//Create an instance of the ServiceContext class. The following code
creates a ServiceContext object for a QuickBooksAPI app.


ServiceContext context = new ServiceContext(appToken, companyID, IntuitServicesType.QBO, oauthValidator);


//Minor version is 5.
context.IppConfiguration.MinorVersion.Qbo = “5”;
//since our work environment is Development(not Production), so we will use
https://sandbox-quickbooks.api.intuit.com/

context.IppConfiguration.BaseUrl.Qbo = https://sandbox-quickbooks.api.intuit.com/&#8221;;
//SerializatioFormat Json or xml

 context.IppConfiguration.Message.Request.SerializationFormat = SerializationFormat.Json;

 context.IppConfiguration.Message.Response.SerializationFormat = SerializationFormat.Json;
// Compression Format GZip or Deflate
context.IppConfiguration.Message.Request.CompressionFormat = CompressionFormat.GZip;

context.IppConfiguration.Message.Response.CompressionFormat = CompressionFormat.GZip;
//retry 5 time at an interval of 1 Second if service fails.
context.IppConfiguration.RetryPolicy = new Intuit.Ipp.Retry.IntuitRetryPolicy(5, retryInterval);
DataService service = new DataService(context);
return service;

}
#endregion – CreateServiceInstance –
#endregion– Private Method –

STEP 5: Understanding “Add Customer” code in Service1.svc file.

 

#region– AddCustomer –
public string AddCustomer()
{

try
{

DataService service = CreateServiceInstance();

// call CreateServiceInstance() Private method to create DataService Instance
//Fill Customer Object


Customer customer = new Customer()
{

//MandatoryFields
GivenName = “Vivek”,
Title = “Er.”
MiddleName = “”
FamilyName = “Pandey”,
Notes = “I am a RockStar”,
PrimaryEmailAddr = new EmailAddress()
{

Address = “vivekgari@gmail.com”,
},

PrimaryPhone= new TelephoneNumber() 
{

FreeFormNumber = “52356523”,
},

Mobile = new TelephoneNumber() 

FreeFormNumber = “8965369856”
},

WebAddr = new WebSiteAddress()
{

URI = https://vivekkumar11432.branded.me/&#8221;
},

};

//CallService to Add customer as Customer
Customer resultCustomer = service.Add(customer) as Customer;
//If Cudtomer is added successfully, reponse will be returned in Customer Object
return resultCustomer.Id;
}

catch
{

return null;
}

}

#endregion – AddCustomer –

 

STEP 6: Understanding “Find Customer” Code in Service1.svc file.

 

#region – FindCustomer –
public string FindCustomer()
{

try
{

//Call CreateServiceInstance Private Method to create Service Instance
DataService service = CreateServiceInstance();
//We will find customer by Id, So fill Id in customer Object. We cannot
directly use Id in service.FindById(customer).

Customer customer = new Customer()

Id = “120”
};

Customer resultCustomerFind = service.FindById(customer) as Customer;

//Customer Details will be returned from service in Json Format if found.


return resultCustomerFind.DisplayName;
}

catch 
{

return null;
}

}

#endregion– FindCustomer –

 

STEP 7: Understanding “Delete Customer” Code in Service1.svc file.


#region – DeleteCustomer –
public string DeleteCustomer()
{

try
{

//Call CreateServiceInstance Private Method to create Service Instance
DataService service = CreateServiceInstance();


//We will find the details of Customer on the basis of Id. We can not
delete Customer directly by Id because the SDK for .net has bug.

//So, we will find the customer and then soft delete it by making Active
field false.

Customer customerFind = new Customer()

{
Id = “120”
};

Customer resultCustomerFind = service.FindById(customerFind) as Customer;
resultCustomerFind.Active = false;
Customer resultDeleteCustomer = service.Update(resultCustomerFind) as Customer;
return “Success”;
}

catch
{

return null;
}

}

#endregion– DeleteCustomer –

 

You can find the list of SDK bugs on this link

https://developer.intuit.com/docs/0100_accounting/0600_more/qbo_v3_known_issues

 

STEP 7: Understanding “Update Customer” Code in Service1.svc file.


#region– UpdateCustomer –
public string UpdateCustomer() 
{

try
{

//Call CreateServiceInstance Private Method to create Service Instance
DataService service = CreateServiceInstance();
//We will find customer by Id, So fill Id in customer Object. We cannot
directly use Id in service.FindById(customer).

Customer customerFind = new Customer() 

Id = “120”
};

Customer resultCustomerFind = service.FindById(customerFind) as Customer;
//After finding customer, fill the details that you want to update. 

resultCustomerFind.DisplayName = “”;
resultCustomerFind.FullyQualifiedName = “”;
resultCustomerFind.GivenName= “Vivek Kumar”;
resultCustomerFind.Title = “Er.”;
resultCustomerFind.MiddleName = “”;
resultCustomerFind.FamilyName = “Pandey”;
resultCustomerFind.Notes = “Need a Change”;
/*make sure that sparse is true 
The sparse update operation provides the ability to 

update a subset of attributes for a given object; only those specified in
the request 
are updated. Missing attributes are left untouched. This is in contrast 
to the full update operation, where elements missing from the request 

are cleared.*/
resultCustomerFind.sparse = true;
resultCustomerFind.PrimaryEmailAddr = new EmailAddress()
{

Address = “vivekgari@gmail.com”,
};

resultCustomerFind.PrimaryPhone = new TelephoneNumber()
{

FreeFormNumber = “98653232”,
};

resultCustomerFind.Mobile = new TelephoneNumber()
{

FreeFormNumber = “9896532658”,
};

//Update Customer by calling service.Update(resultCustomerFind)
Customer resultCustomer = service.Update(resultCustomerFind) as Customer;
return resultCustomer.DisplayName;
}

catch
{

return null;
}

}

#endregion– UpdateCustomer –

 


End QuickBooks.Service*****************************************************


 

Now we will make Web Client to test Quickbooks.Service APIs.

So, let’s get started.

 


Start QuickBooksWebClient**************************************************


 

STEP 1: First of all, we will create ASP.NET Empty Web Application in .NET Framework 4 as shown in picture.

 

webClient

 

STEP 2: Add new web form and name it CustomerCrudTest.

 

Addaspx.png

 

STEP 3: Change the target Framework to 4.5 if running the application shows Framework error. Call the QuickBooks.Service through this project. For reference I have uploaded Project. You can go through the code and test it.

 


End QuickBooksWebClient***************************************************


 

Important Links

 

1. Navigate sandbox

https://sandbox.qbo.intuit.com/app/homepage

 

2. API explorer – You can test APIs online to check whether your request object is correct or not.

https://developer.intuit.com/v2/apiexplorer

 

3. How to use SDK used in this project

https://developer.intuit.com/docs/0100_accounting/0500_developer_kits/0010.net_tools/.net_sdk_for_quickbooks_v3.0

 

4. Manage Sandboxes

https://developer.intuit.com/v2/ui#/sandbox

 

Download Link –

You can download QuickBooks.Service and QuickBooksWebClient projects from my google drive link.

https://drive.google.com/folderview?id=0B–H79LXUyHydXhJUTE1NjJQalk&usp=sharing

 

Advertisements

15 thoughts on “Implement Intuit’s QuickBooks Online API in RESTFUL Service C#

  1. Harish says:

    How can i add invoice??
    I am getting this error.

    “An exception of type ‘Intuit.Ipp.Exception.IdsException’ occurred in Intuit.Ipp.DataService.dll”

    Like

  2. vivek kumar says:

    If you correctly fill data in lineObject, then it will add invoice. You can test your data using Intuit’s API explorer (https://developer.intuit.com/v2/apiexplorer).

    Below is the code for your reference –

    DataService service = CreateServiceInstance();
    List lineList = new List();
    Line lineObject = new Line()
    {
    Amount = 100,
    //DetailType = LineDetailTypeEnum.SalesItemLineDetail,
    DetailType = LineDetailTypeEnum.SalesItemLineDetail,

    AnyIntuitObject = new SalesItemLineDetail()
    {
    ItemRef = new ReferenceType()
    {
    Value = “26”,
    name = “Test 1”
    },
    Qty = 1,
    QtySpecified = true,
    },
    AmountSpecified = true,
    DetailTypeSpecified = true,

    };
    lineList.Add(lineObject);

    Line lineObjectTest = new Line()
    {
    Amount = 120,
    //DetailType = LineDetailTypeEnum.SalesItemLineDetail,
    DetailType = LineDetailTypeEnum.SalesItemLineDetail,

    AnyIntuitObject = new SalesItemLineDetail()
    {
    ItemRef = new ReferenceType()
    {
    Value = “29”,
    name = “Paint Detail Test”
    },
    Qty=1,
    QtySpecified=true,

    },
    AmountSpecified = true,
    DetailTypeSpecified = true,

    };
    lineList.Add(lineObjectTest);

    Invoice invoiceObject = new Invoice()
    {
    //DocNumber=”AUTO_GENERATE”, // In order to give customr Invoice no.
    Line = lineList.ToArray(),
    CustomerRef = new ReferenceType()
    {
    Value=”62″
    },
    };

    Invoice returnPayment = service.Add(invoiceObject);

    Like

  3. Partha says:

    Hi, Whenever I am trying to run the service in my local machine, I am getting the below error, Am I missing anything, please let me know.

    Error: Cannot obtain Metadata from http://localhost:51136/Service1.svc If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost:51136/Service1.svc Metadata contains a reference that cannot be resolved: ‘http://localhost:51136/Service1.svc’. There was no endpoint listening at http://localhost:51136/Service1.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. The remote server returned an error: (404) Not Found.HTTP GET Error URI: http://localhost:51136/Service1.svc The HTML document does not contain Web service discovery information.

    Like

  4. Sharad says:

    Hey Vivek,

    Thanks for the post. It is pretty informative. I am trying to add invoices and each invoice needs a customer reference. For that I would have to implement a Find or add customer first and then use the ID returned in response by Quickbooks and use it with Invoice creation. How would you recommend going about it? Should I add my customers before and save their ids on a persistent storage(DB) and then send an invoice using that.

    Any help is appreciated. thanks a lot.

    Regards,
    Sharad

    Like

    • vivek kumar says:

      I would recommend storing “customer id” in DB along with other important customer data. This would help in reducing calls to Quickbooks API to find customer.

      Like

  5. Alexander Werner says:

    Hi Vivek, thank you for brilliant post!

    I made the connection to QBO from the first shot!

    When adding a new Customer, I am getting an error Newtonsoft.Json.JsonReaderException’ occurred in Newtonsoft.Json.dll. Unexpected character encountered while parsing value: <. Path ”, line 0, position 0.

    Do you know what would that be?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s