Intuit OAuth Node.js Client

repository·master·Indexed 40 days ago

https://github.com/intuit/oauth-jsclient

A Node.js client for Intuit's OAuth 2.0 and OpenID Connect implementations. Version 4.2.5 simplifies authentication flows, token management, and API request handling with built-in error parsing and retry logic. It provides tools for the Authorization Code flow, token refreshing, ID token validation, and migrating OAuth 1.0 tokens to OAuth 2.0.

Tokens
10.1K
Snippets
36
Records
42
Agent score
42%

What's inside Intuit OAuth

  1. Handle OAuth2 and API errors

    master

    The client uses custom error types to allow for programmatic error handling. All errors are thrown and never returned as successful responses.

    Error Types:

    • OAuthError: Base class for all OAuth and API errors. Includes error code, description, and intuit_tid (Transaction ID).
    • TokenError: For token-related issues (expired, invalid, etc.).
    • ValidationError: For input validation errors.
    • NetworkError: For network connectivity issues.

    Handling OAuth2 specific errors (e.g., from createToken() or refresh()): You can inspect the error property for specific OAuth2 error strings like invalid_grant or invalid_client.

    try {
      const authResponse = await oauthClient.createToken(code);
      const token = authResponse.getToken();
    } catch (error) {
      // Access detailed OAuth2 error information
      console.error('OAuth Error:', error.error); // e.g., "invalid_grant"
      console.error('Description:', error.error_description);
      console.error('Transaction ID:', error.intuit_tid);
      console.error('Full response:', error.authResponse.json);
      
      if (error.error === 'invalid_grant') {
        // Handle expired/invalid authorization code
      }
    }
  2. Understand the AuthResponse object

    master

    Methods that perform authentication (like createToken or refresh) return an AuthResponse object. This is a wrapper containing the raw HTTP response and the parsed token data.

    Key properties and methods:

    • token: An instance of the Token object.
    • json: The parsed JSON body from the response.
    • response: The raw HTTP response object.
    • intuit_tid: The intuit-tid from the response headers.
    • status(): Returns the HTTP status code.
    • text(): Returns the response body as text.
    • get_intuit_tid(): Helper to retrieve the Intuit Transaction ID.
    oauthClient.createToken(parseRedirect).then(function (authResponse) {
      console.log('The Token in JSON is  ' + JSON.stringify(authResponse.json));
      let status = authResponse.status();
      let body = authResponse.text();
      let jsonResponse = authResponse.json;
      let intuit_tid = authResponse.get_intuit_tid();
    });
  3. Use relative or absolute URLs in makeApiCall

    master

    The makeApiCall method supports both absolute and relative URLs:

    • Absolute URL: Provides the full endpoint (e.g., https://sandbox-quickbooks.api.intuit.com/v3/company/123/item).
    • Relative URL: Provides the path starting from the root (e.g., /v3/company/123/item). The client automatically prepends the correct base URL based on your configured environment.
  4. Handle token expiration and refresh

    master

    Access tokens expire after 1 hour (3600 seconds). Use isAccessTokenValid() to check the current token's status and refresh() to obtain a new one if it has expired.

    if (!oauthClient.isAccessTokenValid()) {
      await oauthClient.refresh();
    }
  5. Initialize the OAuthClient

    master

    To use the library, require intuit-oauth and instantiate a new OAuthClient with your application credentials.

    Required Options:

    • clientId: Your application's client ID.
    • clientSecret: Your application's client secret.
    • environment: Either 'sandbox' or 'production'.
    • redirectUri: The callback URL on your application. This must match the redirect URI configured in your Intuit Developer Portal under the Keys & OAuth tab.

    Optional Options:

    • logging: Set to true to enable logging (defaults to false).
    const OAuthClient = require('intuit-oauth');
    
    const oauthClient = new OAuthClient({
      clientId: '<Enter your clientId>',
      clientSecret: '<Enter your clientSecret>',
      environment: 'sandbox' || 'production',
      redirectUri: '<Enter your callback URL>',
    });
  6. Check and refresh the access token

    master

    Access tokens are valid for 3600 seconds (one hour). You can use isAccessTokenValid() to check if the current token is expired. If it is invalid, use the refresh() method to obtain a new access token using the most recent refresh_token.

    Note: Always use the refresh_token returned in the most recent token_endpoint response. Previous refresh tokens expire 24 hours after a new one is issued.

    if (oauthClient.isAccessTokenValid()) {
      console.log('The access_token is valid');
    } else {
      oauthClient
        .refresh()
        .then(function (authResponse) {
          console.log('Tokens refreshed : ' + JSON.stringify(authResponse.getToken()));
        })
        .catch(function (e) {
          console.error('The error message is :' + e.originalMessage);
          console.error(e.intuit_tid);
        });
    }
  7. Handle OAuth2 errors and exceptions

    master

    The createToken() method always throws errors on failure rather than returning them. When an error occurs, catch the exception to access specific OAuth2 error details such as error (e.g., invalid_grant), error_description, and intuit_tid (Transaction ID) for support.

    try {
      const authResponse = await oauthClient.createToken(code);
      const token = authResponse.getToken(); // Access token data on success
    } catch (error) {
      console.log('Error:', error.error); // e.g., "invalid_grant"
      console.log('Description:', error.error_description); // e.g., "Token invalid"
      console.log('Transaction ID:', error.intuit_tid); // For support
      
      if (error.error === 'invalid_grant') {
        // Handle specific error, e.g., redirect user to re-authorize
      }
    }
  8. Run the Intuit OAuth2.0 Sample App

    master

    To start the application, run:

    npm start

    Depending on your NGROK_ENABLED configuration, follow the specific steps provided in the terminal output to complete the OAuth flow:

    Scenario A: Using Localhost (NGROK_ENABLED=false)

    1. Open the provided http://localhost:[PORT] URL in your browser.
    2. Copy your clientId and clientSecret from the Intuit Developer Portal.
    3. Use http://localhost:[PORT]/callback as your redirectURI.
    4. Crucial: Ensure http://localhost:[PORT]/callback is added to the 'Redirect URIs' list in your app settings on the Intuit Developer Portal.

    Scenario B: Using ngrok (NGROK_ENABLED=true)

    1. Open the provided https://[ngrok-id].ngrok.io URL in your browser.
    2. Copy your clientId and clientSecret from the Intuit Developer Portal.
    3. Use https://[ngrok-id].ngrok.io/callback as your redirectURI.
    4. Crucial: Ensure https://[ngrok-id].ngrok.io/callback is added to the 'Redirect URIs' list in your app settings on the Intuit Developer Portal.
  9. Configure the Sample App environment variables

    master

    Edit the .env file in the sample directory to configure the application behavior. Key variables include:

    • PORT: (Optional) The port number on which the application will be served.
    • NGROK_ENABLED: (Optional) Set to true if you want to serve the app over HTTPS via ngrok. This is mandatory if you are testing with Production Credentials. Defaults to false.

    If NGROK_ENABLED is set to true, the application will attempt to use ngrok to expose your local endpoint to the internet automatically.

  10. Enable logging in OAuthClient

    master

    To enable logging for debugging purposes, pass logging: true in the configuration object when instantiating the OAuthClient. Logs are written to /logs/oAuthClient-log.log.

    const oauthClient = new OAuthClient({
      clientId: 'your_client_id',
      clientSecret: 'your_client_secret',
      environment: 'sandbox',
      redirectUri: 'http://localhost:8000/callback',
      logging: true // Enable logging
    });
  11. Install intuit-oauth via npm

    master

    To use the Intuit OAuth 2.0 client in your Node.js project, install the intuit-oauth package using npm.

    npm install intuit-oauth