APIs & Integrations

appu_mistri
Member

How to update oAuth access-token on the fly?

Hello,
I'm building a HubSpot public app that should bring all contacts from HubSpot to our system, for the customer to access and interact with the contacts.

The problem statement:
Fetching all the contacts in an account is a time taking process and the access token I've generated (using the auth code or refresh token) expires in that time. I've tried setting the access token using the HubSpot NPM package, but that doesn't seem to work. Any help/suggestion in this regard is appreciated.

 

@hubspot/api-client version: 8.8.1 

Here is what I've been trying:

 

 

hubspotClient.oauth.tokensApi
    .createToken('refresh_token', undefined, undefined, YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REFRESH_TOKEN).then((results) => {
        hubspotClient.setAccessToken(results.accessToken)
})

 

 



0 Upvotes
2 Replies 2
appu_mistri
Member

How to update oAuth access-token on the fly?

Hi @himanshurauthan 
Thanks for your response, I'm already following this but this isn't helping.
Here is what I'm doing.

  1. I have this same token refresh mechanism running in an interval of (1800 - 30) seconds. i.e. 30 seconds before the token expires.
  2. For the first time it does set the access-token and I'm able to make API calls
  3. After (1800 - 30) seconds, the refresh token logic runs, gets the new access-token and set it to the client
  4. Even after this, the client throws an unauthorized error after 1800 seconds

    Not sure if I'm going wrong somewhere. Can you please share an example of the  if you have one?
0 Upvotes
himanshurauthan
Thought Leader | Elite Partner
Thought Leader | Elite Partner

How to update oAuth access-token on the fly?

Hello @appu_mistri 

You have to Generate a new access token, Use the @hubspot/api-client package, and Call the createToken method. you can use the createToken method from the tokensApi object of the hubspotClient instance. Pass the appropriate parameters, including your client ID, client secret, and refresh token.

Here's an example

hubspotClient.oauth.tokensApi.createToken(
  'refresh_token',
  undefined,
  undefined,
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REFRESH_TOKEN
).then((results) => {
  hubspotClient.setAccessToken(results.accessToken);
});


Set the new access token.

After all this, u will be able to update the access token on the fly and continue making API requests without interruption. Remember to handle any errors that may occur during the token refreshing process and implement appropriate error handling and retry mechanisms if needed.

Digital Marketing & Inbound Expert In Growth Hacking Technology
0 Upvotes