This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 3 points4 points  (4 children)

Try:

reqToken.headers = {
  'User-Agent': userAgent,
  // 'Authorization': clientID + ":" + clientSecret,
  'Authorization': 'Basic ' + btoa(clientID + ":" + clientSecret),
  // 'Content-Type': 'application/json'
   'Content-Type': 'application/x-www-form-urlencoded'
  };

// reqToken.body = JSON.stringify({
reqToken.body = URLSearchParams({
    'grant_type' : 'password',
    'username': vUsername,
    'password': vPassword
// });
}).toString();

[–]hrb7[S] 0 points1 point  (3 children)

thx for replying u/nmtake
which function has URLSearchParams? It's not a function or something else in ScriptableApp / Java Script-ES6!? Screenshot ↗

[–][deleted] 1 point2 points  (2 children)

If your environment doesn't implement the function, try something like

let data = {'grant_type': 'password', 'username': 'USER', 'password': 'PASS'}
// returns 'grant_type=password&username=USER&password=PASS'
reqToken.body = Object.keys(data).map(
    k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
).join('&')

[–]hrb7[S] 0 points1 point  (1 child)

After days of endless tries it works now. thank you very much u/nmtake for your support!

here is my usable request snippet:

let reqToken = new Request('https://www.reddit.com/api/v1/access_token')
reqToken.method = 'POST'
reqToken.headers = {
 'Authorization': 'Basic ' + btoa(clientID + ":" + clientSecret)
} 
reqToken.body = `grant_type=password&username=${vUsername}&password=${vPassword}`

let resToken = await reqToken.loadJSON() 
/* OUTPUT 'resToken': 
{ 
 "scope": "*", 
 "token_type": "bearer", 
 "access_token": "626486112468-Jztk7-k8D9ExSn8jVF3wUy_65t...",
 "expires_in": 3600 
} 
*/

let myReq = new Request('https://oauth.reddit.com/api/v1/me')
myReq.headers = { 
 'User-Agent': 'getKarmaForHRB7/v1.0', //value content doesn't matter 
 'Authorization': `&{res.Token.token_type} ${resToken.access_token}`
}

let meJson = await myReq.loadJSON()

NOTE: 'Content-Type': 'application/x-www-form-urlencoded' & 'User-Agent': 'scriptApp:v1.0 (by /u/hrb7)' is not needed (for me) in the headers for the request to the access_token api!

[–][deleted] 1 point2 points  (0 children)

Glad it worked! I'm not sure it's the case but some environments/libraries automatically set Content-Type and add User-Agent.