2

I am trying to send a POST request in order to receive an Access Token in return.

The documentation is as follows:

Client Credentials

This is your first route to obtain an access_token to communicate with the API.

Route : POST https://api.helloasso.com/oauth2/token

Headers

Content-Type = application/x-www-form-urlencoded

Body

client_id = Your Client Id

client_secret = Your Client Secret

grant_type = client_credentials

Solution I tried

Based on this post, I tried the following code:

function qwe()
{
  
  const url = 'https://api.helloasso.com/oauth2/token';

  const headers = { 
      "client_id": "Your Client Id",
      "client_secret": "Your Client Secret",
      "grant_type": "client_credentials"
    };

  const options = { 
    'method' : 'post',
    'contentType': 'application/x-www-form-urlencoded',
    'headers': headers
  };

  const response = UrlFetchApp.fetch(url, options);
  var data = JSON.parse(response);

  Logger.log(data);
  
}

Upon running this, I get an error "Exception: Request failed for https://api.helloasso.com returned code 400. Truncated server response: {"error":"unauthorized_client","error_description":"client_id is not set"}".

I am a beginner, and would appreciate any help on this! Thank you in advance

lexiconkatu
  • 43
  • 1
  • 5
  • Can you provide the documentation for `https://api.helloasso.com` because this looks like it needs the Client ID to complete the authorization – Century Tuna Mar 10 '22 at 22:33

2 Answers2

3

Modification points:

  • In the case of UrlFetchApp, the default content type is application/x-www-form-urlencoded.
  • From your question and situation, I guessed that your Body might be required to be sent as form data.

If those points are reflected in your script, it becomes as follows.

Modified script:

function qwe() {
  const url = 'https://api.helloasso.com/oauth2/token';
  const data = {
    "client_id": "Your Client Id",
    "client_secret": "Your Client Secret",
    "grant_type": "client_credentials"
  };
  const options = {
    'method': 'post',
    'payload': data
  };
  const response = UrlFetchApp.fetch(url, options);
  console.log(response.getContentText())
}

Note:

  • If you tested this modified script, when an error occurs, please show the detailed error message and provide the official document. By this, I would like to confirm it.

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • @lexiconkatu Thank you for replying and testing it. I'm glad your issue was resolved. Thank you, too. – Tanaike Mar 20 '22 at 00:55
1

Need to make it stringify first

'payload' : JSON.stringify(data)
Neo
  • 525
  • 3
  • 17
Someone
  • 11
  • 1