Hubspot OAuth & AWS Lambda - a serverless story

By the end of this blog, you will know enough about how to integrate Hubspot with your web application and query hubspot apis using the Hubspot OAuth in Nodejs on AWS Lambda.

Prerequisites

You may need some exposure & access to the following in order to understand the intent of this blog.

  • Access to some Hubspot Instance
  • NodeJs
  • AWS Lambda

Let’s get started

Create an app using Hubspot Developer Account

To do OAuth, you must create a hubspot app. We do this to get the client Id and client secret to initiate the oauth flow and integrate with the hubspot apis upon successful authentication and receive the access token.

  1. Login into your Hubspot developer account
  2. Create app by providing all the necessary details Create Hubspot App
  3. Select the created app -> Basic info –> Auth. Note down the client Id and client secret Client Id & Client Secret
  4. Set the Callback URL to: https://localhost/token. This is the URL Hubspot will redirect to upon successful validation of user credentials, along with the authorization code. You would need authorization code to get the access token. Don’t worry about the details yet, it is explained in detail as we go along

Interaction sequence of various components involved

Hubspot oauth with aws lambda api

Dissection of sequence diagram

Connect to Hubspot OAuth2.0 endpoint

1) When you open your browser to http://localhost:3000/, the application will invoke the /login api(in aws lambda) which redirects(as a result of 302 response from api) the user to the authentication page on HubSpot’s server.

2) User will choose the appropriate signin method and login into the hubspot account.

3) After successful login, hubspot will take the user to the page to choose the account the user would like to install the app(in hubspot) in and give consent for it to act on your behalf.

4a) When the user grants access to the app with the listed permissions, HubSpot will redirect the user back to the application. This is decided based on the redirectUrl configured while creating the app(in hubspot)

4b) When the user denies the consent, hubspot will take the user to the hubspot home page

Retrieve the authorization code

5) When hubspot redirects the user back to the application, it supplies the authorization code in the query parameters(decided based on the redirectUrl configured while creating the app in hubspot)

Retrieve the access token

Once you’re back in the application, invoke /token api(in aws lambda) which will retrieve the access token and refresh token from HubSpot’s server(by calling hubspot client library nodejs api - https://developers.hubspot.com/docs/api/client-libraries), using an authorization code that was supplied by HubSpot when you granted access to the app.

Going further with the code

/login Endpoint

const hubspot = require('@hubspot/api-client');

module.exports.login = async (event) => {
    const hubspotClient = new hubspot.Client();
    const authUrl = hubspotClient.oauth.getAuthorizationUrl(
            //clientId and clientSecret will be provided when you create
            //an app in your hubspot developer account. Replace it with your details
            CLIENT_ID,
            // Should match your redirecturl in the configuration of the app setup
            REDIRECT_URI,
            // Scopes based on your requirement
            'crm.objects.contacts.read', 
            undefined,
            undefined
    );

    //Redirect to Hubspot login page
    return {
        statusCode: 302,
        headers: {
            location: authUrl,
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            Pragma: 'no-cache',
            Expires: '0',
        },
    };

};

/token Endpoint

const hubspot = require('@hubspot/api-client');

module.exports.login = async (event) => {
    const code = req.query.code;

    const hubspotClient = new hubspot.Client();
    try {
        const getTokensResponse = await hubspotClient.oauth.tokensApi.createToken(
            GRANT_TYPES.AUTHORIZATION_CODE,
            code,
            // Should match your redirecturl in the configuration of the app setup
            REDIRECT_URI,
            //clientId and clientSecret will be provided when you create
            //an app in your hubspot developer account. Replace it with your details
            CLIENT_ID,
            CLIENT_SECRET
        );

        var response = getTokensResponse.body;
        response.expiryTimestamp = Date.now() + response.expiresIn * 1000;

        // Set token for the
        // https://www.npmjs.com/package/@hubspot/api-client
        hubspotClient.setAccessToken(returnValue.accessToken);
        response.connection = hubspotClient;
    } catch (err) {
            console.log(err.toString());
    }

    // Do whatever you want with the access & refresh token from the server. 
    // Pass the token and the other required details from here to the UI 

    return {
        statusCode: 302,
        success: true
    }
}

We hope you found it useful!

Subscribe to Notesally Newsletter