Intuit QuickBooks OAuth 2.0 - Complete Guide
Last Updated: October 11, 2025
Version: 1.0.0
Status: β
Production Ready
Table of Contentsβ
- Overview
- Quick Start (20 minutes)
- Detailed Setup
- Environment Variables
- OAuth Scopes Configuration
- Database Setup
- Implementation Details
- Admin Dashboard Guide
- Usage in Code
- Security Features
- Troubleshooting
- API Reference
- Production Deployment
Overviewβ
This guide covers the complete Intuit QuickBooks OAuth 2.0 integration for secure payment processing in your Gully Sports application.
What This Integration Providesβ
β Payment Processing
- Accept credit/debit card payments
- Process ACH payments
- Handle refunds and voids
- Real-time authorization
β Invoice Management
- Auto-generate invoices
- Send invoices to customers
- Track payment status
- Apply payments automatically
β Customer Sync
- Create customers in QuickBooks
- Sync customer data
- View payment history
- Track spending patterns
β Financial Reporting
- Real-time sales data
- Revenue tracking
- Tax reporting
- Financial analytics
β Automatic Token Management
- Tokens refresh automatically 5 minutes before expiration
- AES-256-CBC encryption for stored tokens
- Zero downtime payment processing
- Secure storage in CockroachDB
Key Featuresβ
- π Enterprise-grade security with AES-256-CBC encryption
- π Automatic token refresh prevents expiration issues
- π³ Full payment processing capability
- π Invoice generation and management
- π¨ Beautiful admin UI for easy management
- π Comprehensive documentation and examples
Quick Startβ
Total Time: ~20 minutes
1. Create Intuit App (15 minutes)β
- Go to Intuit Developer Portal
- Sign in and navigate to "My Apps"
- Click "Create App"
- Select "QuickBooks Online and Payments"
- Fill in app details:
- App Name: Your application name
- Description: Brief description
- Go to "Keys & OAuth" section
- Note your Client ID and Client Secret
- Add Redirect URI:
http://localhost:3000/api/admin/intuit/callback - Select Scopes:
- β
com.intuit.quickbooks.accounting - β
com.intuit.quickbooks.payment
- β
2. Configure Environment Variables (2 minutes)β
Add to your .env.local file:
# Intuit OAuth Configuration
INTUIT_CLIENT_ID="your_client_id_from_intuit"
INTUIT_CLIENT_SECRET="your_client_secret_from_intuit"
INTUIT_REDIRECT_URI="http://localhost:3000/api/admin/intuit/callback"
INTUIT_ENCRYPTION_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
# Optional: OAuth Scopes (defaults to accounting + payment)
INTUIT_OAUTH_SCOPE="com.intuit.quickbooks.accounting com.intuit.quickbooks.payment"
3. Run Database Migration (1 minute)β
npx prisma migrate deploy
npx prisma generate
4. Connect QuickBooks (2 minutes)β
- Start your dev server:
npm run dev - Log in as admin
- Go to Admin Dashboard at
http://localhost:3000/admin - Find "Intuit QuickBooks Integration" section
- Click "Connect to QuickBooks"
- Authorize on Intuit's page
- Done! β
Detailed Setupβ
Step 1: Intuit Developer Account Setupβ
Create Your Appβ
- Visit Intuit Developer Portal
- Sign in with your Intuit account (create one if needed)
- Click "My Apps" in the top navigation
- Click "Create an app" button
- Select "QuickBooks Online and Payments" as the platform
- Fill in the application details:
- App Display Name: "Gully Sports" (or your business name)
- App Description: "Sports facility booking and e-commerce platform"
- Industry: Sports & Recreation
- Contact Email: Your business email
Configure OAuth Settingsβ
- Once created, go to your app dashboard
- Navigate to "Keys & OAuth" section
- Copy your Client ID and Client Secret (keep these secure!)
- In the "Redirect URIs" section, add:
- Development:
http://localhost:3000/api/admin/intuit/callback - Production:
https://yourdomain.com/api/admin/intuit/callback
- Development:
- In the "Scopes" section, select:
- β
com.intuit.quickbooks.accounting- For invoicing and accounting - β
com.intuit.quickbooks.payment- For payment processing
- β
Sandbox vs Productionβ
Intuit provides two environments:
Sandbox (Development)
- Use for testing
- No real money processed
- Create test companies
- Toggle between sandbox/production in app settings
Production
- Live transactions
- Real customer data
- Requires app approval (for some features)
- Use production credentials
Environment Variablesβ
Required Variablesβ
# ============================================
# Intuit OAuth Configuration
# ============================================
# Your Intuit app Client ID (from Developer Portal)
INTUIT_CLIENT_ID="ABCxyz123example"
# Your Intuit app Client Secret (from Developer Portal)
INTUIT_CLIENT_SECRET="xYz789ExampleSecret"
# OAuth callback URL (must match Intuit app settings exactly)
INTUIT_REDIRECT_URI="http://localhost:3000/api/admin/intuit/callback"
# Encryption key for token storage (generate a random 32+ character string)
INTUIT_ENCRYPTION_KEY="your_secure_random_32_character_key_here"
Optional Variablesβ
# OAuth Scopes (defaults to both if not specified)
INTUIT_OAUTH_SCOPE="com.intuit.quickbooks.accounting com.intuit.quickbooks.payment"
Generating the Encryption Keyβ
The encryption key is critical for secure token storage. Generate one using:
Using Node.js:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Using OpenSSL:
openssl rand -hex 32
Example Output:
a7f8e9d2c4b6a1f3e5d7c9b8a6f4e2d1c8b7a5f3e1d9c7b5a3f1e9d7c5b3a1f
β οΈ Important:
- Never commit this key to version control
- Use different keys for development and production
- Store production keys in secure environment variables (Vercel, AWS, etc.)
Production Configurationβ
For production, update:
INTUIT_REDIRECT_URI="https://yourdomain.com/api/admin/intuit/callback"
INTUIT_ENCRYPTION_KEY="different_key_for_production"
And add this URI to your Intuit app settings in the Developer Portal.
OAuth Scopes Configurationβ
Overviewβ
The INTUIT_OAUTH_SCOPE environment variable controls what permissions your app requests from QuickBooks.
Default Configurationβ
By default, both scopes are requested for full functionality:
INTUIT_OAUTH_SCOPE="com.intuit.quickbooks.accounting com.intuit.quickbooks.payment"
If not set, this is the automatic default.
Available Scopesβ
1. QuickBooks Accounting (com.intuit.quickbooks.accounting)β
What it provides:
β Invoice Management
- Create, read, update invoices
- Send invoices to customers
- Track invoice status and payments
- Apply payments to invoices
β Customer Management
- Create and manage customer records
- Update customer information
- View customer details and history
- Customer payment tracking
β Sales & Receipts
- Record direct sales
- Create sales receipts
- Track cash transactions
β Products & Services
- Manage items catalog
- Product pricing
- Inventory tracking (read-only)
β Financial Data
- Access chart of accounts
- View financial reports
- Company information
- Tax information
β Estimates & Credit Memos
- Create estimates and quotes
- Issue refunds and credits
- Apply credits to invoices
Best for: Invoice generation, customer sync, financial reporting
2. QuickBooks Payments (com.intuit.quickbooks.payment)β
What it provides:
β Credit Card Processing
- Process credit/debit card payments
- Real-time authorization
- Payment capture
β Payment Tokenization
- Securely tokenize card details
- Store payment methods safely
- PCI compliance support
β Charge Management
- Create payment charges
- Capture authorized payments
- Process refunds
- Void transactions
β ACH Payments (if enabled)
- Bank account payments
- ACH debit processing
β Transaction Details
- Payment history
- Transaction status
- Settlement information
Best for: Direct payment processing, credit card charges, refunds
Configuration Examplesβ
Full Functionality (Default - Recommended)β
INTUIT_OAUTH_SCOPE="com.intuit.quickbooks.accounting com.intuit.quickbooks.payment"
Use when:
- Processing credit cards during checkout
- Generating invoices automatically
- Need complete QuickBooks integration
- Full payment and accounting features
Accounting Onlyβ
INTUIT_OAUTH_SCOPE="com.intuit.quickbooks.accounting"
Use when:
- Only generating invoices (customers pay later)
- Using separate payment processor (Stripe, etc.)
- Don't process credit cards directly
- Just need customer and invoice sync
Payment Only (Rare)β
INTUIT_OAUTH_SCOPE="com.intuit.quickbooks.payment"
Use when:
- Only need payment gateway functionality
- Have separate invoicing system
- Don't use QuickBooks for accounting
Scope Comparison Matrixβ
| Feature | Accounting Scope | Payment Scope | Both Scopes |
|---|---|---|---|
| Create Invoices | β Yes | β No | β Yes |
| Process Credit Cards | β No | β Yes | β Yes |
| Customer Management | β Yes | β No | β Yes |
| Payment Gateway | β No | β Yes | β Yes |
| Financial Reports | β Yes | β No | β Yes |
| Refund Processing | β οΈ Record only | β Process | β Both |
| Sales Receipts | β Yes | β No | β Yes |
| ACH Payments | β No | β Yes | β Yes |
Changing Scopesβ
Important: Changing scopes requires reconnection!
- Update
INTUIT_OAUTH_SCOPEin.env.local - Restart your application
- Go to Admin Dashboard
- Click "Reconnect" button
- Authorize with new permissions
Database Setupβ
Schema Overviewβ
The integration adds an IntuitOAuth table to securely store OAuth tokens:
model IntuitOAuth {
id String @id @default(cuid())
realmId String @unique // QuickBooks Company ID
accessToken String // Encrypted access token
refreshToken String // Encrypted refresh token
expiresAt DateTime // When the access token expires
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([realmId])
}
Running the Migrationβ
The migration file is already created at:
prisma/migrations/20251011002507_add_intuit_oauth/migration.sql
Apply the Migrationβ
# For development
npx prisma migrate deploy
# Regenerate Prisma Client
npx prisma generate
Verify Migrationβ
# Check migration status
npx prisma migrate status
# Should show: Database schema is up to date!
What Gets Createdβ
- IntuitOAuth table with encrypted token storage
- Unique index on realmId (company ID)
- Index on realmId for fast lookups
- Timestamp fields for tracking
Database Securityβ
- β Tokens encrypted with AES-256-CBC
- β Encryption key stored in environment variables
- β Only application can decrypt tokens
- β No tokens in API responses
- β Automatic cleanup of expired records (optional)
Implementation Detailsβ
Architecture Overviewβ
βββββββββββββββ ββββββββββββββββ βββββββββββββββ
β Admin ββββββββββΆβ OAuth Flow ββββββββββΆβ Intuit β
β Dashboard β β β β OAuth β
βββββββββββββββ ββββββββββββββββ βββββββββββββββ
β β
βΌ βΌ
ββββββββββββββββ βββββββββββββββ
β Database β β QuickBooks β
β (Tokens) β β API β
ββββββββββββββββ βββββββββββββββ
β β²
β β
βΌ β
ββββββββββββββββ β
β Auto Token ββββββββββββββββββ
β Refresh β
ββββββββββββββββ
Files Createdβ
Core Utilitiesβ
src/utils/intuitOAuth.ts - Token management
encrypt(text)- AES-256-CBC encryptiondecrypt(text)- Decrypt stored tokensstoreIntuitTokens()- Save/update tokensgetValidAccessToken()- Get valid token (auto-refreshes)isIntuitConnected()- Check connection statusgetIntuitOAuthStatus()- Get detailed status
src/utils/intuitPayments.ts - Payment processing
processIntuitPayment()- Process credit card paymentcreateIntuitCustomer()- Create customer in QuickBookscreateIntuitInvoice()- Generate invoice
API Routesβ
src/app/api/admin/intuit/auth/route.ts
- Initiates OAuth 2.0 flow
- Generates CSRF protection state
- Redirects to Intuit authorization
src/app/api/admin/intuit/callback/route.ts
- Handles OAuth callback
- Validates CSRF state
- Exchanges code for tokens
- Stores encrypted tokens
src/app/api/admin/intuit/status/route.ts
- Returns connection status
- Shows token expiration
- Company/realm ID info
src/app/api/admin/intuit/refresh/route.ts
- Manual token refresh endpoint
- For testing and troubleshooting
UI Componentsβ
src/components/IntuitOAuthSection.tsx
- Beautiful admin UI
- Connection status display
- Connect/Reconnect buttons
- Real-time token expiration
- Success/error messaging
OAuth Flow Sequenceβ
1. Admin clicks "Connect to QuickBooks"
β
2. App redirects to Intuit (with state for CSRF)
β
3. User logs in and authorizes on Intuit's page
β
4. Intuit redirects back with authorization code
β
5. App validates state (CSRF protection)
β
6. App exchanges code for access + refresh tokens
β
7. Tokens encrypted with AES-256-CBC
β
8. Stored in CockroachDB IntuitOAuth table
β
9. Admin dashboard shows "Connected" β
Automatic Token Refreshβ
During Checkout or API Call:
1. App calls getValidAccessToken()
β
2. Check if token expires in < 5 minutes
β
3. If expiring: Use refresh token to get new tokens
β
4. Encrypt and update database
β
5. Return valid access token
β
6. Payment/API call proceeds normally β
Benefits:
- Zero downtime
- No user intervention needed
- Automatic before expiration
- Transparent to checkout flow
Token Lifecycleβ
| Token Type | Lifetime | Refresh Strategy |
|---|---|---|
| Access Token | 1 hour | Auto-refresh at 55 minutes |
| Refresh Token | 100 days | Manual reconnection needed |
| CSRF State | 10 minutes | Single use, then deleted |
Admin Dashboard Guideβ
Accessing the Integrationβ
- Log in to your admin account
- Navigate to
/admin(Admin Dashboard) - Look for "Intuit QuickBooks Integration" section at the top
Before Connectingβ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π Intuit QuickBooks Integration β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Connect your Intuit QuickBooks account to enable payment β
β processing and automated invoicing. β
β β
β [β‘ Connect to QuickBooks] [βΉοΈ View Documentation] β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
After Successfully Connectingβ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π Intuit QuickBooks Integration β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β
Success! Successfully connected to Intuit QuickBooks! β
β β
β Status Company ID β
β π’ Connected 1234567890 β
β β
β Token Expires Connected Since β
β Oct 11, 2025, 3:45 PM Oct 10, 2025, 2:45 PM β
β β
β [π Refresh Token] [Reconnect] [βΉοΈ View Documentation] β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
How to Connectβ
- Click "Connect to QuickBooks" button
- You'll be redirected to Intuit's authorization page
- Log in to your Intuit account
- Select the QuickBooks company to connect
- Review the permissions requested
- Click "Authorize" to grant access
- You'll be automatically redirected back to admin dashboard
- Success message appears and status updates to "Connected"
Available Actionsβ
π Refresh Tokenβ
When to use:
- See "Expired" status
- Manually force a token refresh
- Testing purposes
How to use:
- Click "Refresh Token" button
- Wait for animation (1-2 seconds)
- Check for success message
- Status updates to "Connected"
π Reconnectβ
When to use:
- Refresh token expired (after 100 days)
- Connect different QuickBooks company
- Update permissions/scopes
- Fix connection issues
How to use:
- Click "Reconnect" button
- Complete OAuth flow again
- Old connection replaced with new one
βΉοΈ View Documentationβ
Opens official Intuit OAuth 2.0 documentation in new tab.
Status Indicatorsβ
| Indicator | Meaning | Action Required |
|---|---|---|
| π’ Connected | Everything working | None |
| π΄ Expired | Token needs refresh | Click "Refresh Token" or "Reconnect" |
Information Displayedβ
- Status: Current connection state (Connected/Expired)
- Company ID: Your QuickBooks company/realm ID
- Token Expires: When current access token expires
- Connected Since: When you first connected
What This Enablesβ
Once connected, your application can:
β Process Payments
- Accept credit card payments
- Process transactions securely
- Handle refunds
β Manage Invoices
- Create invoices automatically
- Send invoices to customers
- Track invoice status
β Sync Customers
- Create customer records in QuickBooks
- Keep customer data synchronized
- Access customer payment history
β Financial Reporting
- Track sales and revenue
- Generate financial reports
- Monitor business performance
Usage in Codeβ
Getting a Valid Access Tokenβ
The system automatically handles token refresh. Use this in your payment/API code:
import { getValidAccessToken } from "@/utils/intuitOAuth";
// This function automatically refreshes expired tokens
const accessToken = await getValidAccessToken();
if (!accessToken) {
throw new Error("Intuit OAuth not configured");
}
// Use the access token for API calls
Processing Paymentsβ
Example: Checkout Flowβ
import { processIntuitPayment } from "@/utils/intuitPayments";
export async function handleCheckout(orderData) {
try {
// Token refresh happens automatically inside this function
const result = await processIntuitPayment({
amount: orderData.total,
currency: "USD",
card: {
number: orderData.cardNumber,
expMonth: orderData.expMonth,
expYear: orderData.expYear,
cvc: orderData.cvc,
name: orderData.cardholderName,
address: {
streetAddress: orderData.address,
city: orderData.city,
region: orderData.state,
country: "US",
postalCode: orderData.zip,
},
},
});
if (result.success) {
return {
success: true,
transactionId: result.transactionId,
};
} else {
return {
success: false,
error: result.error,
};
}
} catch (error) {
console.error("Checkout failed:", error);
return {
success: false,
error: "Payment processing failed",
};
}
}
Creating Customersβ
import { createIntuitCustomer } from "@/utils/intuitPayments";
const customer = await createIntuitCustomer({
displayName: "John Doe",
givenName: "John",
familyName: "Doe",
primaryEmailAddr: { address: "john@example.com" },
primaryPhone: { freeFormNumber: "(555) 123-4567" },
});
if (customer.success) {
console.log("Customer created:", customer.customerId);
}
Creating Invoicesβ
import { createIntuitInvoice } from "@/utils/intuitPayments";
const invoice = await createIntuitInvoice({
customerRef: { value: "123" }, // QuickBooks customer ID
line: [
{
amount: 99.99,
detailType: "SalesItemLineDetail",
salesItemLineDetail: {
itemRef: { value: "1", name: "Cricket Lane Rental" },
qty: 2,
unitPrice: 49.99,
},
},
],
});
if (invoice.success) {
console.log("Invoice created:", invoice.invoiceId);
}
Checking Connection Statusβ
import { isIntuitConnected, getIntuitOAuthStatus } from "@/utils/intuitOAuth";
// Simple check
const connected = await isIntuitConnected();
if (!connected) {
// Redirect to admin to connect
}
// Detailed status
const status = await getIntuitOAuthStatus();
if (status && !status.isExpired) {
// Process payment
}
Security Featuresβ
Encryptionβ
AES-256-CBC Encryption
- Access tokens encrypted at rest
- Refresh tokens encrypted at rest
- Encryption key stored in environment variables
- Tokens never exposed in API responses
// Encryption implementation
const ALGORITHM = "aes-256-cbc";
const key = crypto.createHash("sha256").update(ENCRYPTION_KEY).digest();
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
CSRF Protectionβ
- State parameter generated for each OAuth flow
- Stored in secure HTTP-only cookie
- Validated on callback
- Single-use (deleted after validation)
- 10-minute expiration
Automatic Token Refreshβ
- Tokens refresh 5 minutes before expiration
- Uses refresh token automatically
- Transparent to application code
- No user intervention needed
- Zero downtime
Access Controlβ
- All OAuth endpoints require admin authentication
- Regular users cannot access OAuth settings
- Admin-only routes protected by middleware
- Database access restricted to application
Secure Storageβ
- Tokens stored in CockroachDB
- Database connection encrypted (SSL/TLS)
- Environment variables for sensitive data
- No hardcoded credentials
- Production-grade security
HTTPS Enforcementβ
- Required in production
- Secure cookie settings
- SSL/TLS for all API calls
- Man-in-the-middle prevention
PCI Complianceβ
- No card data stored in database
- Tokens used for QuickBooks API only
- PCI-compliant payment processing
- Secure tokenization support
Troubleshootingβ
Common Issuesβ
"Intuit OAuth not configured"β
Cause: Missing or incorrect environment variables
Solution:
- Check all 4 required environment variables are set:
INTUIT_CLIENT_IDINTUIT_CLIENT_SECRETINTUIT_REDIRECT_URIINTUIT_ENCRYPTION_KEY
- Verify values are correct (no typos)
- Restart your application after adding variables
- Check
.env.localfile is in project root
"invalid_state" Errorβ
Cause: CSRF protection working (good!) but state mismatch
Solution:
- Clear browser cookies
- Try OAuth flow again
- Ensure cookies are enabled in browser
- Check cookie settings if behind proxy
"Token exchange failed"β
Cause: Problem exchanging authorization code for tokens
Solution:
- Verify
INTUIT_CLIENT_SECRETis correct - Ensure
INTUIT_REDIRECT_URImatches exactly in Intuit app settings - Check authorization code hasn't expired (they're short-lived)
- Try connecting again
"Token refresh failed"β
Cause: Refresh token expired or invalid
Solution:
- Refresh tokens expire after 100 days
- Click "Reconnect" button in admin dashboard
- Complete OAuth flow again
- New tokens will be stored
"Can't reach database server"β
Cause: Database connection issue
Solution:
- Check
DATABASE_URLis correct - Verify database is running
- Check network/firewall settings
- Ensure SSL is configured if required
Connection Shows "Expired"β
Expected behavior if:
- Access tokens expire after 1 hour
- System should auto-refresh
If it stays expired:
- Click "Refresh Token" button
- Check application logs for errors
- If refresh fails, click "Reconnect"
- Verify refresh token hasn't expired (100 days)
Payments Fail After Scope Changeβ
Cause: Changed scopes but didn't reconnect
Solution:
- Any scope change requires reconnection
- Go to admin dashboard
- Click "Reconnect"
- Authorize with new scopes
- Test payment processing
Testing in Sandboxβ
Intuit provides sandbox environment for testing:
- In Intuit Developer Portal, toggle to "Sandbox"
- Create test company
- Use sandbox credentials in
.env.local - Test all features without real money
- When ready, switch to "Production" toggle
- Update to production credentials
Logging and Debuggingβ
Enable detailed logging:
// In your API routes or utilities
console.log("OAuth status:", await getIntuitOAuthStatus());
console.log("Access token valid:", !!(await getValidAccessToken()));
Check token expiration:
-- In your database
SELECT id, realmId, expiresAt, createdAt, updatedAt
FROM IntuitOAuth
ORDER BY updatedAt DESC
LIMIT 1;
Tokens appear encrypted (this is correct):
accessToken: "a1b2c3:d4e5f6g7h8i9..." (encrypted)
refreshToken: "x1y2z3:a4b5c6d7e8f9..." (encrypted)
API Referenceβ
OAuth Endpointsβ
GET /api/admin/intuit/authβ
Description: Initiates OAuth 2.0 flow
Authentication: Admin required
Response: Redirects to Intuit authorization page
Query Parameters: None
Example:
// User clicks "Connect to QuickBooks"
window.location.href = "/api/admin/intuit/auth";
GET /api/admin/intuit/callbackβ
Description: Handles OAuth callback from Intuit
Authentication: Admin required
Query Parameters:
code- Authorization code from Intuitstate- CSRF protection staterealmId- QuickBooks company IDerror- Error message if authorization failed
Response: Redirects to admin dashboard with status
Example:
https://yourapp.com/api/admin/intuit/callback?
code=L123456789...&
realmId=9876543210...&
state=abc123...
GET /api/admin/intuit/statusβ
Description: Gets current OAuth connection status
Authentication: Admin required
Response:
{
"connected": true,
"realmId": "9876543210",
"expiresAt": "2025-10-11T15:45:00.000Z",
"isExpired": false,
"connectedAt": "2025-10-10T14:45:00.000Z",
"lastUpdated": "2025-10-11T14:45:00.000Z"
}
Example:
const response = await fetch("/api/admin/intuit/status");
const status = await response.json();
console.log("Connected:", status.connected);
POST /api/admin/intuit/refreshβ
Description: Manually triggers token refresh
Authentication: Admin required
Response:
{
"success": true,
"message": "Token refreshed successfully"
}
Example:
const response = await fetch("/api/admin/intuit/refresh", {
method: "POST",
});
const result = await response.json();
Utility Functionsβ
getValidAccessToken()β
Returns: Promise<string | null>
Description: Gets valid access token, auto-refreshing if needed
Example:
const token = await getValidAccessToken();
if (token) {
// Use token for API call
}
storeIntuitTokens(realmId, accessToken, refreshToken, expiresIn)β
Parameters:
realmId(string) - QuickBooks company IDaccessToken(string) - Access token from IntuitrefreshToken(string) - Refresh token from IntuitexpiresIn(number) - Seconds until expiration
Returns: Promise<void>
Description: Stores or updates encrypted OAuth tokens
isIntuitConnected()β
Returns: Promise<boolean>
Description: Checks if OAuth is configured and connected
getIntuitOAuthStatus()β
Returns: Promise<object | null>
Description: Gets detailed OAuth status information
processIntuitPayment(paymentRequest)β
Parameters:
paymentRequest(object)amount(number) - Payment amountcurrency(string) - Currency code (default: "USD")card(object) - Card detailsnumber,expMonth,expYear,cvc,nameaddress(optional)
Returns: Promise<PaymentResponse>
Description: Processes payment through QuickBooks Payments API
createIntuitCustomer(customer)β
Parameters:
customer(object)displayName(string)givenName,familyName(optional)primaryEmailAddr,primaryPhone(optional)
Returns: Promise<{success, customerId?, error?}>
Description: Creates customer in QuickBooks
createIntuitInvoice(invoice)β
Parameters:
invoice(object)customerRef(object) -{value: customerId}line(array) - Invoice line items
Returns: Promise<{success, invoiceId?, error?}>
Description: Creates invoice in QuickBooks
Production Deploymentβ
Pre-Deployment Checklistβ
Intuit Configurationβ
- Create production app in Intuit Developer Portal
- Add production redirect URI
- Enable required scopes
- Note production Client ID and Secret
- Submit for production approval (if needed)
Environment Variablesβ
- Set
INTUIT_CLIENT_ID(production) - Set
INTUIT_CLIENT_SECRET(production) - Set
INTUIT_REDIRECT_URI(production domain) - Generate new
INTUIT_ENCRYPTION_KEY(different from dev) - Verify
INTUIT_OAUTH_SCOPEis correct
Databaseβ
- Run migrations in production
- Verify IntuitOAuth table created
- Test database connectivity
- Set up database backups
Securityβ
- HTTPS enabled and enforced
- Environment variables secured
- Database connections encrypted
- Admin access restricted
- Logs don't expose secrets
Testingβ
- Test OAuth flow in production
- Verify token refresh works
- Test payment processing
- Test error handling
- Monitor for issues
Production Environment Variablesβ
# Production values (example)
INTUIT_CLIENT_ID="prod_abc123..."
INTUIT_CLIENT_SECRET="prod_secret_xyz..."
INTUIT_REDIRECT_URI="https://gullysports.com/api/admin/intuit/callback"
INTUIT_ENCRYPTION_KEY="<unique-production-key-64-chars>"
INTUIT_OAUTH_SCOPE="com.intuit.quickbooks.accounting com.intuit.quickbooks.payment"
Deployment Platformsβ
Vercelβ
Add environment variables in Vercel dashboard:
- Go to Project Settings
- Navigate to Environment Variables
- Add each variable
- Deploy
AWS / Other Platformsβ
Use platform-specific secret management:
- AWS Systems Manager Parameter Store
- AWS Secrets Manager
- Kubernetes Secrets
- Platform environment variables
Monitoringβ
Track these metrics:
- OAuth connection status
- Token refresh success rate
- Payment processing errors
- API response times
- Failed authorization attempts
Set up alerts for:
- Token refresh failures
- Payment processing errors
- Database connectivity issues
- High error rates
Maintenanceβ
Regular Tasksβ
Weekly:
- Review error logs
- Check token refresh logs
- Monitor payment success rates
Monthly:
- Review connection status
- Update dependencies
- Check for Intuit API updates
Quarterly:
- Audit OAuth scopes (least privilege)
- Review security settings
- Update documentation
- Performance optimization
Token Lifecycle Managementβ
Refresh tokens expire after 100 days:
- Set up reminder 80 days after connection
- Notify admin to reconnect
- Schedule reconnection before expiration
- Monitor for expired connections
Backup and Recoveryβ
Backup OAuth Configuration:
- Export IntuitOAuth table regularly
- Store encrypted backups securely
- Document recovery procedures
Recovery Process:
- Restore database from backup
- Verify environment variables
- Test OAuth connection
- Refresh tokens if needed
- Validate payment processing
Additional Resourcesβ
Intuit Documentationβ
OAuth 2.0 Standardsβ
Security Resourcesβ
Supportβ
Need Help?β
- Check this guide - Most questions are answered here
- Review Intuit's documentation - Official API docs
- Check application logs - Look for error messages
- Test in sandbox - Before production troubleshooting
Found a Bug?β
- Check if it's in the logs
- Verify environment variables
- Test in isolation
- Document steps to reproduce
- Check if known issue
For Intuit API Issuesβ
Summaryβ
What You Getβ
β
Complete OAuth 2.0 integration with Intuit QuickBooks
β
Automatic token management with refresh
β
Secure encrypted storage with AES-256-CBC
β
Beautiful admin interface for easy management
β
Payment processing capability
β
Invoice generation and management
β
Customer sync functionality
β
Production-ready code with error handling
β
Comprehensive documentation and examples
Implementation Statusβ
Status: β
Complete and Production Ready
Security Level: Enterprise-grade
Documentation: Comprehensive
Code Quality: Production-ready
Testing: Sandbox and production ready
Next Stepsβ
- β Complete Intuit Developer Portal setup
- β Add environment variables
- β Run database migration
- β Connect QuickBooks in admin dashboard
- β Test in sandbox mode
- β Integrate with checkout flow
- β Deploy to production
Estimated Setup Time: 20 minutes
Support: This comprehensive guide + Intuit docs
π You're ready to process payments with QuickBooks!
For questions or issues, refer to the Troubleshooting section or Intuit's support resources.