我一直在试图弄清楚如何从Google Apps 脚本中的Reddit API获取访问令牌。到目前为止,我编写了以下代码:
function main() {
var username = 'myredditusername';
var pwd = 'myredditpassword';
var client_id = 'myredditclientid';
var client_secret = 'myredditclientsecret';
var access_token_url = 'https://www.reddit.com/api/v1/access_token';
var api_url = 'https://oauth.reddit.com/';
var user_agent = 'MySideProjectUserAgent';
var data = {
'grant_type': 'password',
'username': username,
'password': pwd
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data),
'headers': {'User-Agent': user_agent},
// what do I enter here to pass my client_id and client_secret?
};
var resp = UrlFetchApp.fetch(access_token_url, options);
console.log(resp.getContentText());
}
运行上面的代码会收到如下错误(这并不奇怪,因为我仍然需要弄清楚如何传入我的client_id
and client_secret
):
Exception: Request failed for https://www.reddit.com returned code 401. Truncated server response: {"message": "Unauthorized", "error": 401} (use muteHttpExceptions option to examine full response)
使用时curl
,我能够使用以下命令成功获取令牌:
curl -X POST -A 'KeywordTrackAgent' -d "grant_type=password&username=myredditusername&password=myredditpassword" --user 'client_id:client_secret' https://www.reddit.com/api/v1/access_token
从到达(示例帖子)开始,我想如果我要将此curl
请求转换为POST
请求,我需要使用如下格式Authorization
向我的参数添加字段:headers
function main() {
var username = 'myredditusername';
var pwd = 'myredditpassword';
var client_id = 'myredditclientid';
var client_secret = 'myredditclientsecret';
var access_token_url = 'https://www.reddit.com/api/v1/access_token';
var api_url = 'https://oauth.reddit.com/';
var user_agent = 'MySideProjectUserAgent';
var data = {
'grant_type': 'password',
'username': username,
'password': pwd
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data),
'headers': {
'User-Agent': user_agent,
// Below, I decided to encode my client_id and client_secret in base64 with the prefix 'Basic '
'Authorization': 'Basic clientIdAndClientSecretInBase64',
},
};
var resp = UrlFetchApp.fetch(access_token_url, options);
console.log(JSON.parse(resp.getContentText()));
}
我仍然收到{错误:'unsupported_grant_type'}。
任何人——已经使用 JavaScript 并且最好是使用 Google Apps 脚本成功获取 Reddit 访问令牌的人——可以分享一些建议/见解吗?预先感谢您的回答!