I'm using apps script to create an interaction between a spreadsheet and a website using its API. I must first authenticate with Oauth 2.0, here is the documentation:
Authentication - OAuth 2.0
Authentication is required before any other API call.
POST
/oauth/token
Body :
grant_type=client_credentials
Header :
Champ | Type | Description |
---|---|---|
Authorization | String | Autorization method "Basic" followed by your public_key and private_key in your settings > developer > API combined into a string "public_key:private_key" and encoded using Base64 |
Content-Type | String | Must be : application/x-www-form-urlencoded |
Header (example) :
```
Authorization: Basic dGVzdGNsaWVudDp0ZXN0cGFzcw==
Content-Type: application/x-www-form-urlencoded
```
I'm completely new to API requests, and I don't understand how to format the request, I found this post:
Send POST request in Google Apps Script with Headers and Body
And as I understand, application/x-www-form-urlencoded is by default with UrlFetchApp, so I tried:
function authentication() {
const ENDPOINT = 'api url'
const CLIENT_ID = 'public key'
const CLIENT_SECRET = 'secret key'
const TOKEN_URL = ENDPOINT + '/oauth/token'
const HEADERS = {
'Authorization' : 'Basic ' + CLIENT_ID + ':' + CLIENT_SECRET
}
const BODY = 'grant_type=client_credentials'
const OPTIONS = {
'method' : 'post',
'headers' : HEADERS
}
let response = UrlFetchApp.fetch(TOKEN_URL + "?" + BODY,OPTIONS)
Logger.log(response.getContentText());
}
But I get a 404 error and know an unknown error.
I guess I'm doing something wrong at least with the body but I don't understand how to format properly the request.
Can someone help me?
Thanks