A Short Introduction to Integrate QuickBooks to Django Application
By manhnv, at: March 28, 2025, 10:32 a.m.
Estimated Reading Time: __READING_TIME__ minutes


A Short Introduction to Integrate QuickBooks to Django Application
Integrating QuickBooks into a Django application can streamline accounting tasks, automate financial workflows, and enhance business efficiency. Whether you're building an app for invoicing, expense tracking, or syncing customer data, connecting QuickBooks with Django is a powerful solution. In this blog, we'll walk through the basic steps to get started with this integration.
Why Integrate QuickBooks with Django?
QuickBooks is a popular accounting software used by businesses to manage finances, while Django is a robust Python framework for building web applications. Combining the two allows you to:
- Automate data syncing between your app and QuickBooks.
- Provide real-time financial insights to users.
- Reduce manual data entry and errors.
Prerequisites
Before diving in, ensure you have:
- A Django project set up and running.
- A QuickBooks Online account (sandbox or live).
- Python packages like requests or an SDK such as intuit-oauth and quickbooks-python.
- Basic knowledge of OAuth 2.0 for authentication.
Steps to Integrate QuickBooks with Django
Step 1: Set Up QuickBooks API Access
First, you need to register your app on the Intuit Developer Portal to get your Client ID and Client Secret. This will allow your Django app to communicate with QuickBooks via its API. Enable the sandbox mode for testing purposes.
Step 2: Install Necessary Libraries
To interact with the QuickBooks API, we’ll rely on the python-quickbooks library, a lightweight and powerful Python package designed specifically for QuickBooks Online integration. This library simplifies authentication, API requests, and data handling, making it an excellent choice for our Django application.
Install the Library
Start by installing the python-quickbooks library. Open your terminal, navigate to your Django project directory, and run the following command:
pip install python-quickbooks
This will download and install the library along with its dependencies. Ensure your virtual environment is activated if you’re using one.
Why python-quickbooks?
The python-quickbooks library simplifies calling the QuickBooks API by providing ready-made classes. This means developers no longer need to manually handle raw requests and responses, making integration faster and easier.
For example, fetching invoice manually:
import json
# Authentication details and API endpoint
access_token = "your_access_token"
realm_id = "your_realm_id"
url = f"https://sandbox-quickbooks.api.intuit.com/v3/company/{realm_id}/query"
# Headers for the HTTP request
headers = {
"Authorization": f"Bearer {access_token}",
"Accept": "application/json",
"Content-Type": "application/text"
}
# SQL-like query to fetch an invoice
query = "SELECT * FROM Invoice WHERE Id = '123'"
# Send the POST request to QuickBooks API
response = requests.post(url, headers=headers, data=query)
# Process the response manually
if response.status_code == 200:
data = response.json()
invoices = data["QueryResponse"]["Invoice"]
print(invoices)
else:
print(f"Error: {response.status_code} - {response.text}")
and fetch invoice using this library
from quickbooks.objects import Invoice
# Initialize the QuickBooks client with credentials
client = QuickBooks(
sandbox=True, # Use sandbox mode for testing
consumer_key="your_client_id", # Client ID from Intuit Developer Portal
consumer_secret="your_client_secret", # Client Secret from Intuit
access_token="your_access_token", # OAuth 2.0 access token
access_token_secret="your_access_token_secret", # OAuth 2.0 token secret
company_id="your_realm_id" # QuickBooks company ID (Realm ID)
)
# Fetch an invoice by ID
invoice = Invoice.get(id=123, qb=client)
# Print invoice details
print(invoice.to_json()) # Or access attributes like invoice.TotalAmt
Step 3: Configure Authentication
QuickBooks uses OAuth 2.0 for secure access. To connect your Django app, you need to implement the authentication flow using class-based views:
- Get Tokens: Redirect users to QuickBooks’ authorization URL to obtain an authorization code, then exchange it for tokens.
- Store Credentials: Save tokens securely (e.g., in a database or session).
- Set Up Client: Use python-quickbooks to initialize the client.
For QuickBooks setup details, refer to the QuickBooks OAuth 2.0 documentation.
Here are the codes to handle the process in your Django apps:
views.py
import uuid
import requests
from django.views.generic import RedirectView, View
from django.shortcuts import redirect
from django.conf import settings
from quickbooks import QuickBooks
# View to start OAuth flow when button is clicked
class QuickBooksAuthView(RedirectView):
permanent = False
def get_redirect_url(self, *args, **kwargs):
# Generate a unique state token for CSRF protection
state_token = str(uuid.uuid4())
self.request.session['state_token'] = state_token
# QuickBooks OAuth 2.0 authorization URL
auth_url = (
"https://appcenter.intuit.com/connect/oauth2"
"?client_id={}&response_type=code"
"&scope=com.intuit.quickbooks.accounting"
"&redirect_uri={}&state={}"
).format(
settings.QB_CLIENT_ID, # Client ID from settings.py
settings.QB_REDIRECT_URI, # Redirect URI from settings.py
state_token # State token for security
)
return auth_url
# View to handle the redirect URI (callback) from QuickBooks
class QuickBooksCallbackView(View):
def get(self, request, *args, **kwargs):
# Extract code and state from the callback URL
auth_code = request.GET.get('code')
state = request.GET.get('state')
realm_id = request.GET.get('realmId')
# Verify state token matches to prevent CSRF
if state != request.session.get('state_token'):
return redirect('error_page') # Replace with your error URL
# Exchange authorization code for access and refresh tokens
token_url = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"
payload = {
'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': settings.QB_REDIRECT_URI,
'client_id': settings.QB_CLIENT_ID,
'client_secret': settings.QB_CLIENT_SECRET,
}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(token_url, data=payload, headers=headers)
if response.status_code == 200:
tokens = response.json()
# Save tokens securely (e.g., in session or database)
request.session['access_token'] = tokens['access_token']
request.session['refresh_token'] = tokens['refresh_token']
request.session['realm_id'] = realm_id
# Initialize QuickBooks client
client = QuickBooks(
sandbox=True,
consumer_key=settings.QB_CLIENT_ID,
consumer_secret=settings.QB_CLIENT_SECRET,
access_token=tokens['access_token'],
access_token_secret=tokens.get('access_token_secret', ''),
company_id=realm_id
)
# Store client or proceed with API calls
request.session['qb_client'] = client # Optional: store serialized client
return redirect('success_page') # Replace with your success URL
settings.py
QB_CLIENT_SECRET = 'your_client_secret'
QB_REDIRECT_URI = 'http://localhost:8000/callback/' # Đảm bảo khớp với QuickBooks app
urls.py
from django.urls import path
from .views import QuickBooksAuthView, QuickBooksCallbackView
urlpatterns = [
path('auth/', QuickBooksAuthView.as_view(), name='qb_auth'),
path('callback/', QuickBooksCallbackView.as_view(), name='qb_callback'),
]
Step 4: Sync Data with QuickBooks
After successful authentication, your Django app can now exchange data with QuickBooks, such as customers, invoices, or payments. This step involves creating a seamless flow between your app’s database and QuickBooks’ API. Start by defining Django models to represent the data you want to sync (e.g., a Customer or Invoice model). Then, build views to handle operations like pushing local data to QuickBooks or pulling updates from QuickBooks to your app. For example, you might create a view to send a new invoice when a user submits a form, or fetch a list of customers to display in your dashboard. The python-quickbooks library simplifies this by letting you work with QuickBooks objects directly, ensuring data consistency across both systems.
Step 5: Test and Deploy
Before launching your integration, rigorous testing is crucial. Use QuickBooks’ sandbox environment to simulate real-world scenarios without affecting live data—test creating, updating, and retrieving records to confirm everything works as expected. Pay special attention to edge cases, such as expired access tokens (which require refreshing) or hitting API rate limits (which need retry logic). Add error handling in your views to gracefully manage these issues, providing users with clear feedback if something fails. Once testing is complete and stable, deploy your app to production, ensuring your credentials and redirect URIs match the live QuickBooks app settings.
Conclusion
Integrating QuickBooks with Django opens up a world of possibilities for financial automation. By following these steps, you can create a seamless connection between your web app and QuickBooks, saving time and improving accuracy. Feel free to tweak the code to suit your specific use case!