Lazy Lync

Implement Intuit OAuth 2.0 with Nextjs and Sveltekit

Learn how to authenticate QuickBooks Online users in your Intuit App using OAuth 2.0 with this simple tutorial. Works with Express, Nextjs and Sveltekit.

Author: Adi

intuit oauth nodejs nextjs sveltekit

Integrating QuickBooks Online API in a SvelteKit app involves several steps, including setting up OAuth for authentication, obtaining an access token, and using it to interact with the QuickBooks API. Let’s break down the code and address potential issues and necessary steps to get it working.

Key Points and Steps:

  1. OAuthClient Initialization: Ensure the OAuthClient is being initialized with the correct environment and credentials.
  2. Authentication URI Generation: You need to redirect the user to this authUri to get authorization from QuickBooks.
  3. Token Exchange: Once the user authorizes, QuickBooks will redirect to your REDIRECT_URI with a code. You need to exchange this code for an access token.
  4. Persistent Storage: Store tokens securely for subsequent API requests.
  5. API Requests: Use the access token to make authenticated requests to QuickBooks API.

Implementation Details:

  1. Environment Configuration: Ensure that your CLIENT_ID, CLIENT_SECRET, ENVIRONMENT, and REDIRECT_URI are correctly set in your environment variables.
  2. Server-side Code: Use SvelteKit’s server-side load function to handle OAuth and API calls securely.

1. Initialize OAuthClient and Generate Auth URI

You have this part set up correctly. Ensure your environment variables are properly set.

import type { LayoutServerLoad } from './$types';
import OAuthClient from 'intuit-oauth';
import { CLIENT_ID, CLIENT_SECRET, ENVIRONMENT, REDIRECT_URI } from '$env/static/private';

export const load = (async ({ locals }) => {
    // Initialize OAuthClient
    const oauthClient = new OAuthClient({
        clientId: CLIENT_ID,
        clientSecret: CLIENT_SECRET,
        environment: ENVIRONMENT,
        redirectUri: REDIRECT_URI
    });

    // Generate the auth URI
    const authUri = oauthClient.authorizeUri({
        scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.OpenId],
        state: 'Init'
    });

    return { authUri };  // Return the authUri for redirection
}) satisfies LayoutServerLoad;

2. Redirect User to Auth URI

Redirect users to authUri to start the OAuth flow:

<a href={$authUri}>Connect to QuickBooks</a>

3. Handle Callback and Exchange Code for Token

You need to create a route to handle the QuickBooks redirect:

// src/routes/api/callback/+server.ts
import { json } from '@sveltejs/kit';
import OAuthClient from 'intuit-oauth';
import { CLIENT_ID, CLIENT_SECRET, ENVIRONMENT, REDIRECT_URI } from '$env/static/private';

/**
 * Retrieves an authorization token from the OAuthClient and returns a JSON response with the name 'Aditya'.
 *
 * @param {Object} param - An object containing the URL parameter.
 * @param {URL} param.url - The URL object containing the query parameters.
 * @return {Promise<Object>} A Promise that resolves to a JSON object with the name 'Aditya'.
 */

export async function GET({ url }) {
	const oauthClient = new OAuthClient({
		clientId: CLIENT_ID,
		clientSecret: CLIENT_SECRET,
		environment: ENVIRONMENT,
		redirectUri: REDIRECT_URI
	});
	// Get the authorization code from query parameters
	const authCode = url.toString();
	console.log('authCode', authCode);
	const tokenExchange = await oauthClient.createToken(authCode);

	console.log('exchange res', tokenExchange);

	return json({ status: 200 });
}

4. Use Access Token for API Requests

With the access token, you can now make requests to QuickBooks API:

// src/routes/api/data/+server.ts
import { json } from '@sveltejs/kit';
import OAuthClient from 'intuit-oauth';
import { CLIENT_ID, CLIENT_SECRET, ENVIRONMENT, REDIRECT_URI } from '$env/static/private';

// Assuming you have stored the token securely
// const token = getStoredToken();

export async function GET({ locals }) {
    const oauthClient = new OAuthClient({
        clientId: CLIENT_ID,
        clientSecret: CLIENT_SECRET,
        environment: ENVIRONMENT,
        redirectUri: REDIRECT_URI
    });

    // Set token in oauthClient
    oauthClient.setToken(locals.token);

    try {
        // Example API request to get company info
        const companyInfo = await oauthClient.makeApiCall({
            url: `${oauthClient.environment === 'sandbox' ? 'https://sandbox-quickbooks.api.intuit.com' : 'https://quickbooks.api.intuit.com'}/v3/company/YOUR_COMPANY_ID/companyinfo`
        });

        return json(companyInfo.getJson());
    } catch (error) {
        console.error('API call error:', error);
        return json({ error: 'API call failed' }, { status: 500 });
    }
}

Further implementation

  • Secure Token Storage: Always ensure tokens are stored securely. Never expose them in client-side code.
  • Environment Variables: Double-check your environment variable names and values.
  • OAuth Flow: Remember that OAuth flow involves redirecting users to QuickBooks and then handling their redirect back to your app.

FAQs on Intuit OAuth for QuickBooks App Development

What is OAuth 2.0?

OAuth 2.0 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service. It works by delegating user authentication to the service that hosts the user account and authorizing third-party applications to access the user account.

How do I set up OAuth 2.0 with Intuit on a Node.js server?

To set up OAuth 2.0 with Intuit on a Node.js server, you need to install the `intuit-oauth` package, initialize the OAuth client with your credentials, generate the authorization URL, and handle the token exchange upon user redirection.

Can I use OAuth 2.0 with Next.js and SvelteKit?

Yes, you can use OAuth 2.0 with both Next.js and SvelteKit. For Next.js, you can set up API routes to handle the OAuth flow. For SvelteKit, you can use server-side load functions and API routes to manage authentication and token exchange.

What environment variables are needed for OAuth 2.0 integration with Intuit?

For OAuth 2.0 integration with Intuit, you need the following environment variables: `CLIENT_ID`, `CLIENT_SECRET`, `ENVIRONMENT`, and `REDIRECT_URI`. These should be securely stored and not exposed in client-side code.

What are the key steps to implement OAuth 2.0 with Intuit?

The key steps include: initializing the OAuth client, generating the authorization URL, redirecting users to QuickBooks for authorization, handling the callback to exchange the authorization code for an access token, and using the access token to make authenticated API requests.