Quick start

The QuickBooks Online .NET SDK makes it easier for .NET developers to create apps for the QuickBooks Online APIs. This page describes how to create your integration, including features you will most likely want in your app.

Preliminaries

Use the links below to download the SDK, access the installation instructions, and view important information about the SDK.

    Develop an app using the .NET SDK

    The following are typical steps for developing an app using the .NET SDK:

    1. If you haven't already created an Intuit Developer account, create your account.
    2. Create your app on developer.intuit.com to get your development and production keys and URIs.
    3. Use API Explorer, Postman, and OAuth 2.0 Playground to explore and test the QuickBooks Online API and OAuth 2.0. For example code, see the .NET sample apps. For additional tools, see Third-party tools.
    4. In Visual Studio, create your web app.
    5. Configure your .NET SDK settings:
      1. Add the app keys to your web.config file along with an openid_identifier.
      2. Configure the base URL for either Sandbox or Production.
      3. Check the latest minor version supported and set this in your config file.
      4. Configure logging in the web.config file or in your code. 
    6. Set up authorization and implement the Connect to QuickBooks button in your app.
    7. Use your development keys for developing and testing your app in the sandbox, or production keys for Production or live QuickBooks company testing. Production keys can be obtained from the Keys tab under the Production tab of the app.
    8. Make sure that you set a unique requestId for each API call.
    9. Use the Class library reference to get details for the supported fields, functions, and classes provided by the .NET SDK.
    10. For details on how to make QuickBooks Online API calls, see Make QuickBooks Online API calls.

    Configure your settings

    The .NET SDK is configured with default values for settings such as minor version, number of retries, and logging. You can override these default settings by either editing the configuration file or setting the properties of the IppConfiguration object in your code. For details on how to configure the settings, see Configuration.

    Use the Class Library

    Classes provided in the .NET class library correspond to the QuickBooks Online API resources. The Class Library provides wrappers for calling QuickBooks Online API resources. For example, the properties of the Account class correspond to the properties defined for the Account resource of the QuickBooks Online API.

    Make QuickBooks Online API calls

    The following sections describe how to make QuickBooks Online API calls using the .NET SDK.

    Set up authorization

    For your app to access a user's data, the app redirects the user to Intuit's OAuth 2.0 server for authentication. The server authenticates the user and redirects them back to your app's OAuth 2.0 redirect URL with an authorization code, which is exchanged for an access token. Your application can use the access token to call QuickBooks Online APIs. You must refresh the token before each call to the QuickBooks Online API. For more information on setting up OAuth authorization, see Authorization. Use the OAuth 2.0 playground to experiment with the OAuth 2.0 protocol and QuickBooks Online APIs. It is pre-configured to use with Intuit's OAuth 2.0 endpoints so you can quickly get started.

    Use the RequestId parameter

    The requestId parameter uniquely identifies the HTTP request sent from the app to the service. The following is an example of a basic call for a requestId:

    context.RequestId = "unique string";
    

    Whenever you make a new API call, you must get a new requestId for that call. For details on the requestId parameter, see REST API quick reference. For additional useful information, see Request ID update for QuickBooks Online integration.

    Use includeQueryParam

    Use includeQueryParam to request that a reserved name/value pair be included in the response. This is analogous to using query parameters for reserved name/value pairs in REST API requests. For example, you can add the firsttxndate query parameter to get the first transaction date from the CompanyInfo resource. The following example adds the allowduplicatedocnum query parameter to the request from the Purchase resource to allow duplicate check numbers to be generated:

    List<String> includeQueryParam = new List<String>();
    includeQueryParam.Add("allowduplicatedocnum");
    context.Include = includeQueryParam;
    

    Invoices

    This section describes how to perform some common invoicing tasks using the .NET SDK. For information about the invoice resource, see Invoice.

    Create an invoice

    To create an invoice, create an object from the DataService class. The following example creates an invoice for a US company with sales line item details using an instance of DataService and query calls to populate the details. For more information, see Create an invoice.

    Click to view example.
    static void CreateQBOInvoice(DataService dataService, ServiceContext context)
    {
        //Find Customer
        QueryService<Customer> customerQueryService = new QueryService<Customer>(context);
        Customer customer = customerQueryService.ExecuteIdsQuery("Select * From Customer StartPosition 1 MaxResults 1").FirstOrDefault<Customer>();
        //Find Tax Code for Invoice - Searching for a tax code named 'StateSalesTax' in this example
        QueryService<TaxCode> stateTaxCodeQueryService = new QueryService<TaxCode>(context);
        TaxCode stateTaxCode = stateTaxCodeQueryService.ExecuteIdsQuery("Select * From TaxCode Where Name='StateSalesTax' StartPosition 1 MaxResults 1").FirstOrDefault<TaxCode>();
        //Find Account - Accounts Receivable account required
        QueryService<Account> accountQueryService = new QueryService<Account>(context);
        Account account = accountQueryService.ExecuteIdsQuery("Select * From Account Where AccountType='Accounts Receivable' StartPosition 1 MaxResults 1").FirstOrDefault<Account>();
        //Find Item
        QueryService<Item> itemQueryService = new QueryService<Item>(context);
        Item item = itemQueryService.ExecuteIdsQuery("Select * From Item StartPosition 1 MaxResults 1").FirstOrDefault<Item>();
        //Find Term
        QueryService<Term> termQueryService = new QueryService<Term>(context);
        Term term = termQueryService.ExecuteIdsQuery("Select * From Term StartPosition 1 MaxResults 1").FirstOrDefault<Term>();
        Invoice invoice = new Invoice();
        //DocNumber - QBO Only, otherwise use DocNumber
        invoice.AutoDocNumber = true;
        invoice.AutoDocNumberSpecified = true;
        //TxnDate
        invoice.TxnDate = DateTime.Now.Date;
        invoice.TxnDateSpecified = true;
        //PrivateNote
        invoice.PrivateNote = "This is a private note";
        //Line
        Line invoiceLine = new Line();
        //Line Description
        invoiceLine.Description = "Invoice line description.";
        //Line Amount
        invoiceLine.Amount = 330m;
        invoiceLine.AmountSpecified = true;
        //Line Detail Type
        invoiceLine.DetailType = LineDetailTypeEnum.SalesItemLineDetail;
        invoiceLine.DetailTypeSpecified = true;
        //Line Sales Item Line Detail
        SalesItemLineDetail lineSalesItemLineDetail = new SalesItemLineDetail();
        //Line Sales Item Line Detail - ItemRef
        lineSalesItemLineDetail.ItemRef = new ReferenceType()
        {
            name = item.Name,
            Value = item.Id
        };
        //Line Sales Item Line Detail - UnitPrice
        lineSalesItemLineDetail.AnyIntuitObject = 33m;
        lineSalesItemLineDetail.ItemElementName = ItemChoiceType.UnitPrice;
        //Line Sales Item Line Detail - Qty
        lineSalesItemLineDetail.Qty = 10;
        lineSalesItemLineDetail.QtySpecified = true;
        //Line Sales Item Line Detail - TaxCodeRef
        //For US companies, this can be 'TAX' or 'NON'
        lineSalesItemLineDetail.TaxCodeRef = new ReferenceType()
        {
            Value = "TAX"
        };
        //Line Sales Item Line Detail - ServiceDate
        lineSalesItemLineDetail.ServiceDate = DateTime.Now.Date;
        lineSalesItemLineDetail.ServiceDateSpecified = true;
        //Assign Sales Item Line Detail to Line Item
        invoiceLine.AnyIntuitObject = lineSalesItemLineDetail;
        //Assign Line Item to Invoice
        invoice.Line = new Line[] { invoiceLine };
        //TxnTaxDetail
        TxnTaxDetail txnTaxDetail = new TxnTaxDetail();
        txnTaxDetail.TxnTaxCodeRef = new ReferenceType()
        {
            name = stateTaxCode.Name,
            Value = stateTaxCode.Id
        };
        Line taxLine = new Line();
        taxLine.DetailType = LineDetailTypeEnum.TaxLineDetail;
        TaxLineDetail taxLineDetail = new TaxLineDetail();
        //Assigning the fist Tax Rate in this Tax Code
        taxLineDetail.TaxRateRef = stateTaxCode.SalesTaxRateList.TaxRateDetail[0].TaxRateRef;
        taxLine.AnyIntuitObject = taxLineDetail;
        txnTaxDetail.TaxLine = new Line[] { taxLine };
        invoice.TxnTaxDetail = txnTaxDetail;
        //Customer (Client)
        invoice.CustomerRef = new ReferenceType()
        {
            name = customer.DisplayName,
            Value = customer.Id
        };
        //Billing Address
        PhysicalAddress billAddr = new PhysicalAddress();
        billAddr.Line1 = "123 Main St.";
        billAddr.Line2 = "Unit 506";
        billAddr.City = "Brockton";
        billAddr.CountrySubDivisionCode = "MA";
        billAddr.Country = "United States";
        billAddr.PostalCode = "02301";
        billAddr.Note = "Billing Address Note";
        invoice.BillAddr = billAddr;
        //Shipping Address
        PhysicalAddress shipAddr = new PhysicalAddress();
        shipAddr.Line1 = "100 Fifth Ave.";
        shipAddr.City = "Waltham";
        shipAddr.CountrySubDivisionCode = "MA";
        shipAddr.Country = "United States";
        shipAddr.PostalCode = "02452";
        shipAddr.Note = "Shipping Address Note";
        invoice.ShipAddr = shipAddr;
        //SalesTermRef
        invoice.SalesTermRef = new ReferenceType()
        {
            name = term.Name,
            Value = term.Id
        };
        //DueDate
        invoice.DueDate = DateTime.Now.AddDays(30).Date;
        invoice.DueDateSpecified = true;
        //ARAccountRef
        invoice.ARAccountRef = new ReferenceType()
        {
            name = account.Name,
            Value = account.Id
        };
        Invoice invoiceAdded = dataService.Add<Invoice>(invoice);
        #region " Logged Request and Response "
        //Request
        //POST https://<baseUrl>/v3/company/<realmId>/invoice HTTP/1.1
        //Content-Type: application/json
        //Host: <baseUrl>
        //Authorization: OAuth oauth_token="lvprdTJzbZqooMvYCvU35HwpwYsL1ZaJsvJwRYAIvZcL906W",oauth_nonce="b93219b6-430d-46c8-a217-a0918ed5aff8",oauth_consumer_key="qyprdcAQ7lV9AbDAdMA5WEkHEkvcj4",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1378833234",oauth_version="1.0",oauth_signature="5kWNe6uXOEGHT%2BIAbJHHwxSaV%2BQ%3D"
        //User-Agent: V3DotNetSDK1.0.7
        //Content-Length: 1488
        //Expect: 100-continue
        //{
        //    "TxnDate": "2016-01-07-04:00",
        //    "PrivateNote": "This is a private note",
        //    "Line": [{
        //        "Description": "Invoice line description.",
        //        "Amount": 330,
        //        "DetailType": "SalesItemLineDetail",
        //        "SalesItemLineDetail": {
        //            "ItemRef": {
        //                "value": "1",
        //                "name": "Services"
        //            },
        //            "UnitPrice": 33,
        //            "Qty": 10,
        //            "TaxCodeRef": {"value": "TAX"},
        //            "ServiceDate": "2016-01-07-04:00"
        //        }
        //    }],
        //    "TxnTaxDetail": {
        //        "TxnTaxCodeRef": {
        //            "value": "2",
        //            "name": "California"
        //        },
        //        "TaxLine": [{
        //            "TaxLineDetail": {
        //                "TaxRateRef": {
        //                    "value": "3",
        //                    "name": "California"
        //                }
        //            }
        //        }]
        //    },
        //    "CustomerRef": {
        //        "value": "1",
        //        "name": "Amy's Bird Sanctuary"
        //    },
        //    "BillAddr": {
        //        "Line1": "4581 Finch St.",
        //        "City": "Bayshore",
        //        "CountrySubDivisionCode": "CA",
        //        "PostalCode": "94326"
        //    },
        //    "ShipAddr": {
        //        "Line1": "4581 Finch St.",
        //        "City": "Bayshore",
        //        "CountrySubDivisionCode": "CA",
        //        "PostalCode": "94326"
        //    },
        //    "SalesTermRef": {
        //        "value": "1",
        //        "name": "Due on receipt"
        //    },
        //    "DueDate": "2016-02-06",
        //    "ARAccountRef": {
        //        "value": "84",
        //        "name": "Accounts Receivable (A/R)"
        //    }
        //}
        #endregion
        #region " Screenshot of result in QBO UI "
        //http://i.imgur.com/LlrP5ca.png
        #endregion
    }
    

    Send an invoice

    To email an invoice to a customer from your app, use the sendMail method as shown in the following example:

    QueryService<Invoice> invResult = new QueryService<Invoice>(context);
    Invoice invresult = invResult.ExecuteIdsQuery("Select * From Invoice").FirstOrDefault();
    commonServiceQBO.SendEmail<Invoice>(invresult, “ni@gmail.com”);

    Get an invoice in PDF format

    The following example gets an invoice in PDF format:

    QueryService<Invoice> invResult = new QueryService<Invoice>(context);
    byte[] response = commonServiceQBO.GetPdf<Invoice>(invresult);
    string fileName = string.Format(@"C:\invoice_{0}.pdf", Guid.NewGuid());
    System.IO.File.WriteAllBytes(fileName, response);
    

    Void an invoice

    To void an invoice, pass the Invoice object to the Void method as shown in the following example:

    Invoice invoiceAdded = service.Void<Invoice>(objInvoice);
    

    Query data

    Query filters enable your app to retrieve specific entities. For example, your app can retrieve only those customer entities that have been created within the last twenty days. The following example query retrieves customer data:

    QueryService<Customer> customerQueryService = new QueryService<Customer>(context);
    Customer customer = customerQueryService.ExecuteIdsQuery("Select * From Customer where Id=1").FirstOrDefault<Customer>();
    

    For details on how to create queries, see Query filters.

    Batch calls

    Batch calls can be made to add, delete, or update data, or to make a query. The following example adds customer information using a batch call. For more information, see Batch.

    DataService commonServiceQBO = new DataService(context);
    
    Customer customer12 = new Customer();
        string guid = Guid.NewGuid().ToString("n");
        customer12.GivenName = guid.Substring(0, 25);
        string GivenNameCustomer1 = customer12.GivenName;
        customer12.Title = guid.Substring(0, 15);
        customer12.MiddleName = guid.Substring(0, 5);
        customer12.FamilyName = guid.Substring(0, 25);
        customer12.DisplayName = guid.Substring(0, 20);
    
        Customer customer22 = new Customer();
        guid = Guid.NewGuid().ToString("n");
        customer22.GivenName = guid.Substring(0, 25);
        string GivenNameCustomer2 = customer22.GivenName;
        customer22.Title = guid.Substring(0, 15);
        customer22.MiddleName = guid.Substring(0, 5);
        customer22.FamilyName = guid.Substring(0, 25);
        customer22.DisplayName = guid.Substring(0, 20);
    
        Batch batchTest1 = commonServiceQBO.CreateNewBatch();
        batchTest1.Add(customer12, "Customer1", OperationEnum.create);
    
        batchTest1.Add(customer22, "Customer2", OperationEnum.create);
        batchTest1.Execute();
    

    CDC calls

    Change data capture (CDC) calls return a list of entities that have changed since a specified time. This operation is useful for an app that periodically polls Data Services and then refreshes its local copy of entity data. The following example code makes a CDC call:           

    List<Intuit.Ipp.Data.IEntity>  entityList1 = new List<Intuit.Ipp.Data.IEntity>();
    entityList1.Add(new Intuit.Ipp.Data.Customer());
    entityList1.Add(new Intuit.Ipp.Data.Invoice());
    entityList1.Add(new Intuit.Ipp.Data.Bill());
    var DataService1 = new DataService(context);
    var Response1 = DataService1.CDC(entityList1, DateTime.Now.AddDays(-30)).entities;

    For more information on making CDC calls, see Change data capture.

    Create and update custom fields

    Custom fields enable you to add attributes to existing QuickBooks objects to store information that is specific to your business. You cannot create custom fields using an API. Instead, read the Preferences entity for an existing Invoice, and then update the custom field value. To update the field, send the DefinitionId of the custom field; otherwise, the update will not be successful. For more about how to update custom fields, see Create custom fields.

    DataService commonServiceQBO = new DataService(context);
    QueryService<Invoice> qsa3 = new QueryService<Invoice>(context);   
        Invoice ad3 = qsa3.ExecuteIdsQuery("select * from Invoice where Id='1663'").FirstOrDefault();
        StringTypeCustomFieldDefinition custField = new StringTypeCustomFieldDefinition();
        List<CustomField> culist = new List<CustomField>();
        CustomField c1 = new CustomField();
        c1.DefinitionId = "1";
        c1.Name = "PO Number";
        c1.Type = CustomFieldTypeEnum.StringType;
        c1.AnyIntuitObject = "Gold11";
         
        culist.Add(c1);
         
        //CustomField c2 = new CustomField();
        //c2.DefinitionId = "2";
        //c2.Name = "Check Number";
        //c2.Type = CustomFieldTypeEnum.StringType;
        //c2.AnyIntuitObject = "Polo11";
        //culist.Add(c2);
         
        custField.CustomField = culist.ToArray();
        ad3.CustomField = custField.CustomField;
         
        Invoice reInvoice1 = commonServiceQBO.Update(ad3)
    

    Generate reports

    To generate reports, create a ReportService object. The following code provides an example for generating a report. For more about generating reports, see Reports.

    Click to view example.
    ReportService reportService = new ReportService(context); 

    
    //Date should be in the format YYYY-MM-DD 


    
    reportService.accounting_method = "Accrual"; 

    reportService.start_date = "1997-01-01"; 

    reportService.end_date = "2014-12-18"; 

    reportService.classid = "2800000000000634813"; 
    
reportService.date_macro = "Last Month"; 

    
reportService.summarize_column_by = "Month"; 



    
    List<String> columndata = new List<String>(); 

    
columndata.Add("tx_date"); 

    
columndata.Add("dept_name"); 

    
string coldata = String.Join(",", columndata); 

    
reportService.columns = coldata;
    
 
    


var report1 = reportService.ExecuteReport("GeneralLedger");
    

    The following example code retrieves a report and prints it to the console:

    Click to view example.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Intuit.Ipp.Core;
    using Intuit.Ipp.Data;
    using Intuit.Ipp.ReportService;
    static class SampleCalls
    {
        public static void GetReportAndPrintToConsole(ServiceContext qboServiceContext, String reportName, String startDate, String endDate)
        {
            //JSON required for QBO Reports API
            qboServiceContext.IppConfiguration.Message.Response.SerializationFormat = Intuit.Ipp.Core.Configuration.SerializationFormat.Json;
            //Instantiate ReportService
            ReportService reportsService = new ReportService(qboServiceContext);
            //Set properties for Report
            reportsService.start_date = startDate;
            reportsService.end_date = endDate;
            //Execute Report API call
            Report report = reportsService.ExecuteReport(reportName);
            //Format the report data and print to the console
            PrintReportToConsole(report);
        }
        private static void PrintReportToConsole(Report report)
        {
            StringBuilder reportText = new StringBuilder();
            //Append Report Header
            PrintHeader(reportText, report);
            //Determine Maxmimum Text Lengths to format Report
            int[] maximumColumnTextSize = GetMaximumColumnTextSize(report);
            //Append Column Headers
            PrintColumnData(reportText, report.Columns, maximumColumnTextSize, 0);
            //Append Rows
            PrintRows(reportText, report.Rows, maximumColumnTextSize, 1);
            //Print Formatted Report to Console
            Console.Write(reportText.ToString());
        }
        #region " Helper Methods "
        #region " Determine Maximum Column Text Length "
        private static int[] GetMaximumColumnTextSize(Report report)
        {
            if (report.Columns == null) { return null; }
            int[] maximumColumnSize = new int[report.Columns.Count()];
            for (int columnIndex = 0; columnIndex < report.Columns.Count(); columnIndex++)
            {
                maximumColumnSize[columnIndex] = Math.Max(maximumColumnSize[columnIndex], report.Columns[columnIndex].ColTitle.Length);
            }
            return GetMaximumRowColumnTextSize(report.Rows, maximumColumnSize, 1);
        }
        private static int[] GetMaximumRowColumnTextSize(Row[] rows, int[] maximumColumnSize, int level)
        {
            for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
            {
                Row row = rows[rowIndex];
                Header rowHeader = GetRowProperty<Header>(row, ItemsChoiceType1.Header);
                if (rowHeader != null) { GetMaximumColDataTextSize(rowHeader.ColData, maximumColumnSize, level); }
                ColData[] colData = GetRowProperty<ColData[]>(row, ItemsChoiceType1.ColData);
                if (colData != null) { GetMaximumColDataTextSize(colData, maximumColumnSize, level); }
                Rows nestedRows = GetRowProperty<Rows>(row, ItemsChoiceType1.Rows);
                if (nestedRows != null) { GetMaximumRowColumnTextSize(nestedRows.Row, maximumColumnSize, level + 1); }
                Summary rowSummary = GetRowProperty<Summary>(row, ItemsChoiceType1.Summary);
                if (rowSummary != null) { GetMaximumColDataTextSize(rowSummary.ColData, maximumColumnSize, level); }
            }
            return maximumColumnSize;
        }
        private static int[] GetMaximumColDataTextSize(ColData[] colData, int[] maximumColumnSize, int level)
        {
            for (int colDataIndex = 0; colDataIndex < colData.Length; colDataIndex++)
            {
                maximumColumnSize[colDataIndex] = Math.Max(maximumColumnSize[colDataIndex], (new String(' ', level * 3) + colData[colDataIndex].value).Length);
            }
            return maximumColumnSize;
        }
        #endregion
        #region " Print Report Sections "
        private static void PrintHeader(StringBuilder reportText, Report report)
        {
            const string lineDelimiter = "-----------------------------------------------------";
            reportText.AppendLine(report.Header.ReportName);
            reportText.AppendLine(lineDelimiter);
            reportText.AppendLine("As of " + report.Header.StartPeriod);
            reportText.AppendLine(lineDelimiter);
            reportText.AppendLine(lineDelimiter);
        }
        private static void PrintRows(StringBuilder reportText, Row[] rows, int[] maxColumnSize, int level)
        {
            for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
            {
                Row row = rows[rowIndex];
                //Get Row Header
                Header rowHeader = GetRowProperty<Header>(row, ItemsChoiceType1.Header);
                //Append Row Header
                if (rowHeader != null && rowHeader.ColData != null) { PrintColData(reportText, rowHeader.ColData, maxColumnSize, level); }
                //Get Row ColData
                ColData[] colData = GetRowProperty<ColData[]>(row, ItemsChoiceType1.ColData);
                //Append ColData
                if (colData != null) { PrintColData(reportText, colData, maxColumnSize, level); }
                //Get Child Rows
                Rows childRows = GetRowProperty<Rows>(row, ItemsChoiceType1.Rows);
                //Append Child Rows
                if (childRows != null) { PrintRows(reportText, childRows.Row, maxColumnSize, level + 1); }
                //Get Row Summary
                Summary rowSummary = GetRowProperty<Summary>(row, ItemsChoiceType1.Summary);
                //Append Row Summary
                if (rowSummary != null && rowSummary.ColData != null) { PrintColData(reportText, rowSummary.ColData, maxColumnSize, level); }
            }
        }
        private static void PrintColData(StringBuilder reportText, ColData[] colData, int[] maxColumnSize, int level)
        {
            for (int colDataIndex = 0; colDataIndex < colData.Length; colDataIndex++)
            {
                if (colDataIndex > 0) { reportText.Append("     "); }
                StringBuilder rowText = new StringBuilder();
                if (colDataIndex == 0) { rowText.Append(new String(' ', level * 3)); };
                rowText.Append(colData[colDataIndex].value);
                if (rowText.Length < maxColumnSize[colDataIndex])
                {
                    rowText.Append(new String(' ', maxColumnSize[colDataIndex] - rowText.Length));
                }
                reportText.Append(rowText.ToString());
            }
            reportText.AppendLine();
        }
        private static void PrintColumnData(StringBuilder reportText, Column[] columns, int[] maxColumnSize, int level)
        {
            for (int colDataIndex = 0; colDataIndex < columns.Length; colDataIndex++)
            {
                if (colDataIndex > 0) { reportText.Append("     "); }
                StringBuilder rowText = new StringBuilder();
                if (colDataIndex == 0) { rowText.Append(new String(' ', level * 3)); };
                rowText.Append(columns[colDataIndex].ColTitle);
                if (rowText.Length < maxColumnSize[colDataIndex])
                {
                    rowText.Append(new String(' ', maxColumnSize[colDataIndex] - rowText.Length));
                }
                reportText.Append(rowText.ToString());
            }
            reportText.AppendLine();
        }
        #endregion
        #region " Get Row Property Helper Methods - Header, ColData, Rows (children), Summary "
        //Returns typed object from AnyIntuitObjects array
        private static T GetRowProperty<T>(Row row, ItemsChoiceType1 itemsChoiceType)
        {
            int choiceElementIndex = GetChoiceElementIndex(row, itemsChoiceType);
            if (choiceElementIndex == -1) { return default(T); } else { return (T)row.AnyIntuitObjects[choiceElementIndex]; }
        }
        //Finds element index in ItemsChoiceType array
        private static int GetChoiceElementIndex(Row row, ItemsChoiceType1 itemsChoiceType)
        {
            if (row.ItemsElementName != null)
            {
                for (int itemsChoiceTypeIndex = 0; itemsChoiceTypeIndex < row.ItemsElementName.Count(); itemsChoiceTypeIndex++)
                {
                    if (row.ItemsElementName[itemsChoiceTypeIndex] == itemsChoiceType) { return itemsChoiceTypeIndex; }
                }
            }
            return -1;
        }
        #endregion
        #endregion
    }
    

    Create and read a TaxCode

    To create a TaxCode object, use GlobalTaxService. To read a TaxCode object, create an Intuit.Ipp.Data.TaxService object as shown in the following example. For more information, see Manage tax for US locales or Manage tax for non-US locales.

    Click to view example.
    String guid = Helper.GetGuid();
        GlobalTaxService.GlobalTaxService taxSvc = new GlobalTaxService.GlobalTaxService(qboContextoAuth);
        Intuit.Ipp.Data.TaxService taxCodetobeAdded = new Data.TaxService();
        taxCodetobeAdded.TaxCode = "taxC_"+guid;
        
    QueryService<TaxAgency> taxAgencyQueryService = new QueryService<TaxAgency>(context);
    TaxAgency taxagency = taxAgencyQueryService.ExecuteIdsQuery("Select * From TaxAgency where Id=1").FirstOrDefault<Customer>();
    
        List<TaxRateDetails> lstTaxRate = new List<TaxRateDetails>();
        TaxRateDetails taxdetail1 = new TaxRateDetails();
        taxdetail1.TaxRateName = "taxR1_"+guid;
        taxdetail1.RateValue = 3m;
        taxdetail1.RateValueSpecified = true;
        taxdetail1.TaxAgencyId = taxagency.Id.ToString();
        taxdetail1.TaxApplicableOn = TaxRateApplicableOnEnum.Sales;
        taxdetail1.TaxApplicableOnSpecified = true;
        lstTaxRate.Add(taxdetail1);
                
        TaxRateDetails taxdetail2 = new TaxRateDetails();
        taxdetail2.TaxRateName = "taxR2_" + guid;
        taxdetail2.RateValue = 2m;
        taxdetail2.RateValueSpecified = true;
        taxdetail2.TaxAgencyId = taxagency.Id.ToString();
        taxdetail2.TaxApplicableOn = TaxRateApplicableOnEnum.Sales;
        taxdetail2.TaxApplicableOnSpecified = true;
        lstTaxRate.Add(taxdetail2);
                
    taxCodetobeAdded.TaxRateDetails = lstTaxRate.ToArray();
        Intuit.Ipp.Data.TaxService taxCodeAdded = taxSvc.AddTaxCode(taxCodetobeAdded);
    

    Attachments

    A file, such as a receipt image, product photo, or note, can be linked to a transaction or Item object. For details about attachments, see Attach images and notes.

    Attach a note to a transaction using an Attachable endpoint

    Notes can be linked to an object using the Attachable and AttachableRef classes, as shown in the following example. For details, see Attach images and notes.

    Click to view example.
    string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Services\\Resource\\image.jpg");
        System.IO.FileInfo file = new System.IO.FileInfo(imagePath);
        Attachable attachable = new Attachable();
        attachable.Lat = "25.293112341223";
        attachable.Long = "-21.3253249834";
        attachable.PlaceName = "Fake Place";
        attachable.Note = "Attachable note123 ";
        attachable.Tag = "Attachable tag123 ";
                                
        AttachableRef[] attachments = new AttachableRef[1];
        AttachableRef ar = new AttachableRef();
        ar.EntityRef = new ReferenceType();
        ar.EntityRef.type = objectNameEnumType.Invoice.ToString();
        ar.EntityRef.name = objectNameEnumType.Invoice.ToString();
        ar.EntityRef.Value = "1655";
        //ar.EntityRef.type = objectNameEnumType.Bill.ToString();
        //ar.EntityRef.name = objectNameEnumType.Bill.ToString();
        //ar.EntityRef.Value = "1484";
        attachments[0] = ar;
        attachable.AttachableRef = attachments;
        
        Attachable res11 = commonServiceQBO.Add<Attachable>(attachable);
    

    Attach a file to a transaction using an Upload endpoint

    Use the Attachable and AttachableRef classes to attach a file to a transaction by uploading an endpoint as shown in the following example, which uploads an image attachment using an HTTP endpoint. For more on uploading attachments using an endpoint, see Attach images and notes.

    Click to view example.
    string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Services\\Resource\\image.jpg");
        System.IO.FileInfo file = new System.IO.FileInfo(imagePath);
        Attachable attachable = new Attachable();
        attachable.Lat = "25.293112341223";
        attachable.Long = "-21.3253249834";
        attachable.PlaceName = "Fake Place";
        attachable.Note = "Attachable note123 ";
        attachable.Tag = "Attachable tag123 ";
                                
        AttachableRef[] attachments = new AttachableRef[1];
        AttachableRef ar = new AttachableRef();
        ar.EntityRef = new ReferenceType();
        ar.EntityRef.type = objectNameEnumType.Invoice.ToString();
        ar.EntityRef.name = objectNameEnumType.Invoice.ToString();
        ar.EntityRef.Value = "1655";
        //ar.EntityRef.type = objectNameEnumType.Bill.ToString();
        //ar.EntityRef.name = objectNameEnumType.Bill.ToString();
        //ar.EntityRef.Value = "1484";
        attachments[0] = ar;
        attachable.AttachableRef = attachments;
         
        using (System.IO.FileStream fs = file.OpenRead())
        {
            //attachable.ContentType = "image/bmp";
            ////attachable.FileName = file.Name;
            //attachable.FileName = "image.bmp";
            //Attachable attachableUploaded = commonServiceQBO.Upload(attachable, fs);
            //byte[] responseByte = commonServiceQBO.Download(attachableUploaded);
            //fs.Close();
            attachable.ContentType = "application/pdf";
            //attachable.FileName = file.Name;
            attachable.FileName = "merged1.pdf";
            Attachable attachableUploaded = commonServiceQBO.Upload(attachable, fs);
            byte[] responseByte = commonServiceQBO.Download(attachableUploaded);
            fs.Close();
       }
       
       Attachable res11 = commonServiceQBO.Add<Attachable>(attachable);
    

    Attach a file using multi-part form data

    This example sends a POST operation using an HTTP call to attach a file:

    Click to view example.
    private static string AttachToInvoice(string invoiceID, string docPath, string filename, List<string> parms)
    {
        string sRet = "fail";
        
        try
        {
            string uri = string.Format("{0}/v3/company/{1}/upload?minorversion=1", theBaseUrl, parms[0]);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            
            string boundary = "CaMoUtPuTRuLeSxYzWq1U2I3H4B";
            string boundaryStart = "--" + boundary; // << add two dashes at beginning
            string boundaryEnd = boundaryStart + "--";
            
            request.Method = "POST";
            request.Headers.Add("Authorization", GetDevDefinedOAuthHeader(parms[1], parms[2], parms[3], parms[4], request, null));
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Accept = "application/json";
                         
            byte[] fileBytes = System.IO.File.ReadAllBytes(docPath);
                    
            string jsonDisposition = "Content-Disposition: form-data; name=\"file_metadata_0\"";
            string jsonContentType = "Content-Type: application/json";
            string jsonRequest = "{\"FileName\":\"" + filename + "\",\"ContentType\":\"" + MimeType(docPath) + "\",\"Lat\":\"25.293112341223\",\"Long\":\"-21.3253249834\"," +
                        "\"PlaceName\":\"Fake Place\",\"Note\":\"Cam Output note123 \",\"Tag\":\"Cam Output tag123 \"," +
                        "\"AttachableRef\":[{\"EntityRef\":{\"name\":\"Invoice\",\"type\":\"Invoice\",\"value\":\"" + invoiceID + "\"}}]}";
                        
            byte[] bytesJsonRequest = Encoding.UTF8.GetBytes((string)jsonRequest);
                    
            string dataDispositionHeader = String.Format("Content-Disposition: form-data; name=\"file_content_0\"; filename=\"{0}\"", filename.ToLower());
            string dataTypeHeader = "Content-Type: " + MimeType(docPath);
            string dataContentXfer = "Content-Transfer-Encoding: " + GetEncoding(docPath);
                    
            string oneCr = "\r\n";
            string twoCrs = "\r\n\r\n";
                    
            request.ContentLength = boundaryStart.Count() +
                oneCr.Count() +
                jsonDisposition.Count() +
                oneCr.Count() +
                jsonContentType.Count() +
                twoCrs.Count() +
                bytesJsonRequest.Length +
                twoCrs.Count() +
                boundaryStart.Count() +
                oneCr.Count() +
                dataDispositionHeader.Count() +
                oneCr.Count() +
                dataTypeHeader.Count() +
                oneCr.Count() +
                dataContentXfer.Count() +
                twoCrs.Count() +
                fileBytes.Length +
                oneCr.Count() +
                boundaryEnd.Count() +
                twoCrs.Count();
                                                
                using (System.IO.Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(Encoding.UTF8.GetBytes(boundaryStart), 0, boundaryStart.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(oneCr), 0, oneCr.Count());
                        
                    requestStream.Write(Encoding.UTF8.GetBytes(jsonDisposition), 0, jsonDisposition.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(oneCr), 0, oneCr.Count());
                        
                    requestStream.Write(Encoding.UTF8.GetBytes(jsonContentType), 0, jsonContentType.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(twoCrs), 0, twoCrs.Count());
                        
                    requestStream.Write(bytesJsonRequest, 0, bytesJsonRequest.Length);
                    requestStream.Write(Encoding.UTF8.GetBytes(twoCrs), 0, twoCrs.Count());
                        
                    requestStream.Write(Encoding.UTF8.GetBytes(boundaryStart), 0, boundaryStart.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(oneCr), 0, oneCr.Count());
                        
                    requestStream.Write(Encoding.UTF8.GetBytes(dataDispositionHeader), 0, dataDispositionHeader.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(oneCr), 0, oneCr.Count());
                        
                    requestStream.Write(Encoding.UTF8.GetBytes(dataTypeHeader), 0, dataTypeHeader.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(oneCr), 0, oneCr.Count());
                        
                    requestStream.Write(Encoding.UTF8.GetBytes(dataContentXfer), 0, dataContentXfer.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(twoCrs), 0, twoCrs.Count());
                        
                    requestStream.Write(fileBytes, 0, fileBytes.Length);
                    requestStream.Write(Encoding.UTF8.GetBytes(oneCr), 0, oneCr.Count());
                        
                    requestStream.Write(Encoding.UTF8.GetBytes(boundaryEnd), 0, boundaryEnd.Count());
                    requestStream.Write(Encoding.UTF8.GetBytes(twoCrs), 0, twoCrs.Count());
                        
                    requestStream.Close();
                }
                    
                System.Net.HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), true))
                {
                    string result = streamReader.ReadToEnd();
                    sRet = result.Contains("FileAccessUri") ? "Success" : "Fail";
                }
            }
            catch (Exception e)
            {
                return "false";
            }
                
            return sRet;
        }
            
        private static string MimeType(string doc)
        {
            string sRet = "";
            string ext = Path.GetExtension(doc).ToLower();
            switch (ext)
            {
                case ".gif":
                    sRet = "image/gif";
                    break;
                case ".jpeg":
                case ".jpg":
                    sRet = "image/jpeg";
                    break;
                case ".png":
                    sRet = "image/png";
                    break;
                case ".pdf":
                    sRet = "application/pdf";
                    break;
                case ".txt":
                    sRet = "text/plain";
                    break;
            }
            return sRet;
        }
            
        private static string GetEncoding(string docPath)
        {
            string sRet = "";
            string ext = Path.GetExtension(docPath).ToLower();
            switch (ext)
            {
                case ".gif":
                case ".jpeg":
                case ".jpg":
                case ".png":
                    sRet = "binary";
                    break;
                case ".pdf":
                    sRet = "application/pdf";
                    break;
                case ".txt":
                    sRet = "text/plain";
                    break;
            }
            return sRet; 
        }
    }
    

    Develop an app using the DevDefined library

    To develop an app using the DevDefined library:

    • Download the DevDefined library for OAuth using Nuget Package Manager.
    • Call the QuickBooks Online API using the third-party DevDefined library.

    GET and POST

    POST and GET operations can be used to make queries.

    GET

    The following example uses a GET operation to make a query:

    Click to view example.
    using DevDefined.OAuth.Consumer;
    using DevDefined.OAuth.Framework;
    using System.IO;
    using System.Text;
    using System.Net;
    using Intuit.Ipp.DataService;
    using Intuit.Ipp.Security;
    using System.Web;
    namespace IPPQbApiConsoleApp
    {
        static class SampleCalls
        {
            public static string ExecuteV3Query(string consumerKey, string consumerSecret, string accessToken,  string accessTokenSecret, string realmId, string query)
            {
                string encodedQuery = System.Web.HttpUtility.UrlEncode(query);
                string uri = string.Format("https://quickbooks.api.intuit.com/v3/company/{0}/query?query={1}", realmId, encodedQuery);
                HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
                httpWebRequest.Method = "GET";
                httpWebRequest.Accept = "application/json";
                httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken, accessTokenSecret, httpWebRequest, null));
                HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                using (Stream data = httpWebResponse.GetResponseStream())
                {
                    //return XML response
                    return new StreamReader(data).ReadToEnd();
                }
            }
            private static string GetDevDefinedOAuthHeader(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, HttpWebRequest webRequest, string requestBody)
            {
                OAuthConsumerContext consumerContext = new OAuthConsumerContext
                {
                    ConsumerKey = consumerKey,
                    SignatureMethod = SignatureMethod.HmacSha1,
                    ConsumerSecret = consumerSecret,
                    UseHeaderForOAuthParameters = true
                };
                //We already have OAuth tokens, so OAuth URIs below are not used - set to example.com
                OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
                                        "https://www.example.com",
                                        "https://www.example.com");
                oSession.AccessToken = new TokenBase
                {
                    Token = accessToken,
                    ConsumerKey = consumerKey,
                    TokenSecret = accessTokenSecret
                };
                IConsumerRequest consumerRequest = oSession.Request();
                consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
                if (requestBody != null)
                {
                    consumerRequest = consumerRequest.Post().WithRawContentType(webRequest.ContentType).WithRawContent(System.Text.Encoding.ASCII.GetBytes(requestBody));
                }
                consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
                //consumerRequest = consumerRequest.SignWithToken();
                return consumerRequest.Context.GenerateOAuthParametersForHeader();
            }
        }
    }
    
    POST

    This example sends a POST request:

    Click to view example.
    //string res = CreateV3Customer(consumerKey, consumerSecret, accessToken, accessTokenSecret, realmId);
    
    public string CreateV3Customer(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string realmId)
        {
            StringBuilder request = new StringBuilder();
            StringBuilder response = new StringBuilder();
                    
            var requestBody = "{\"FamilyName\":\"Jack\"}";
            
            HttpWebRequest httpWebRequest = WebRequest.Create("https://quickbooks.api.intuit.com/v3/company/"+realmId+"/customer") as HttpWebRequest;
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(consumerKey, consumerSecret, accessToken,accessTokenSecret,httpWebRequest, requestBody));
            request.Append(requestBody);
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] content = encoding.GetBytes(request.ToString());
            using (var stream = httpWebRequest.GetRequestStream())
            {
                stream.Write(content, 0, content.Length);
            }
            HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
            using (Stream data = httpWebResponse.GetResponseStream())
            {
                string customerr = new StreamReader(data).ReadToEnd();
                return customerr;
            }
        }
    

    Did you find this page helpful?
    Your feedback helps us make our docs better. Please let us know if this page helped you, or if it needs improvement.

     Got Questions? Get Answers in our developer forums.