Create redirect code programmatically


Hello, I am trying to create an OAuth connection inside of a .NET application and wanted to make sure I have the correct process down. Are these the correct steps?

      0. Authorize the Developer Application to reach the other HubSpot Application

  1. Get the "code" from the redirect_uri by making the call to with the correct query parameters
  2. Generate a token by making a call to with the correct x-www-form-urlencoded parameters.

However, since the "code" value expires every 10 minuntes, I need to programmatically generate it but am unable to get the redirect url after making an API call. Do you all any same code that's not in Node I can use for reference for completely step 1? 


Is this also the correct route or should I be authentication via the API Key? 



3 Replies 3
Top Contributor | Gold Partner

Hey there,


so the way I do it in a PHP app I created:


  1. Get the code like you explained
    (in the developers area where you have your app, once you enter the redirect uri and chosen the scope(s), you'll get a url to visit & that url will ask you to choose your account & also to grand access to that scope. After that you'll be redirected to your uri with the code paramater attached.

  2. Using that code, you can create an access token & refresh token. this token will stay valid 6 hours.

  3. I then created a cron job that will run every 5 hours & uses the client id, client secret, redirect uri and access token, to generate a new token


Hope this helps?



Thanks for the response. 


So I can't do the first part of obtaining the code programatically? I think your solution is pretty good, but I'm nervous if the jobs fails in the middle of night (for whatever reason) then our HubSpot Integration would break completely. Has this happened to you at all? 


Do you then* store your new token somewhere? Maybe a secure, encyrpted storage, where your web application retrieves it before making an api call?


HubSpot Employee

Thanks for jumping in, @benvanlooy!


@bmicucci, to add additional context, it is not possible to generate the code programmatically because the OAuth 2.0 Authorization Code grant type, which HubSpot applications use, requires a user to grant access.


Once a user grants access and lands on your redirect_uri, however, your app can programmatically grab it and pass it to your function which calls this endpoint.


You will usually only have to collect the code once per connection (which is per account), because once you use the code to generate your first access_token and refresh_token, you can store the refresh_tokenand use it to refresh the access token, as @benvanlooy does in "Step 3."


Yes, refresh_token values should be stored securely.


Hope that helps clarify!

Isaac Takushi

Associate Certification Manager