DEV Community

Cover image for Intuit OAuth 2.0 for SvelteKit
Aditya Raj
Aditya Raj

Posted on

Intuit OAuth 2.0 for SvelteKit

Learn how to authenticate QuickBooks Online users in your Intuit app using OAuth 2.0 with this straightforward tutorial. This guide is compatible with Express, Next.js, and SvelteKit.

Steps to Integrate QuickBooks API in SvelteKit

  1. OAuthClient Initialization:
    Initialize OAuthClient with the correct environment variables:

    import OAuthClient from 'intuit-oauth';
    import { CLIENT_ID, CLIENT_SECRET, ENVIRONMENT, REDIRECT_URI } from '$env/static/private';
    
    const oauthClient = new OAuthClient({
        clientId: CLIENT_ID,
        clientSecret: CLIENT_SECRET,
        environment: ENVIRONMENT,
        redirectUri: REDIRECT_URI
    });
    
    
  2. Generate Authentication URI:
    Redirect users to this URI for QuickBooks authorization:

    const authUri = oauthClient.authorizeUri({
        scope: [OAuthClient.scopes.Accounting, OAuthClient.scopes.OpenId],
        state: 'Init'
    });
    
    // Use this URI to redirect users
    return { authUri };
    
    
  3. Redirect Users:
    Provide a link for users to start the OAuth flow:

    <a href={$authUri}>Connect to QuickBooks</a>
    
    
  4. Handle Callback and Token Exchange:
    Create a route to handle the QuickBooks redirect and exchange the authorization code for a token:

    import { json } from '@sveltejs/kit';
    
    export async function GET({ url }) {
        const authCode = url.searchParams.get('code');
        const tokenResponse = await oauthClient.createToken(authCode);
    
        // Log and store the token securely
        console.log('Token:', tokenResponse);
        return json({ status: 200 });
    }
    
    
  5. Use Access Token for API Requests:
    With the access token, make authenticated requests to QuickBooks API:

    export async function GET({ locals }) {
        oauthClient.setToken(locals.token);
    
        try {
            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 });
        }
    }
    
    

Additional Notes

  • Token Storage: Store tokens securely; avoid client-side exposure.
  • Environment Variables: Verify variable names and values.
  • OAuth Flow: Remember, the OAuth process involves user redirection for authorization.

This concise guide simplifies integrating QuickBooks Online with SvelteKit using OAuth 2.0. You can read more of these guides that I'll be launching int he coming month on my own website, Lazy Lync.

Top comments (0)