我正在尝试使用Google Apps脚本中的OAuth访问StackExchange API。我正在使用this library。
当我拨打以下电话时,我一开始没有访问权限(这是预期的)。我登录的授权URL是:
https://stackoverflow.com/oauth?client_id=14205&response_type=code&redirect_uri={URI}&state={STATE}&scope=read_inbox
将autorizationURL粘贴到浏览器中,我得到的页面显示为:
"Error: Token response not valid JSON: SyntaxError: Unexpected token: a (line 532, file "Service", project "OAuth2")"
我从Apps脚本运行的内容:
function getMentions() {
var service = getStackExchangeService_();
Logger.log(service.hasAccess());
if (service.hasAccess()) {
//get token and call API
}
else {
Logger.log("App has no access yet.");
// open this url to gain authorization from Stack Exchange
var authorizationUrl = service.getAuthorizationUrl();
Logger.log("Open the following URL and re-run the script: %s",
authorizationUrl);
}
}
我的Oauth.gs页面:
function getStackExchangeService_() {
var CLIENT_ID = PropertiesService.getScriptProperties().getProperty('SE_CLIENT_ID');
var CLIENT_SECRET = PropertiesService.getScriptProperties().getProperty('SE_CLIENT_SECRET');
return OAuth2.createService('StackExchange')
.setAuthorizationBaseUrl('https://stackoverflow.com/oauth')
.setTokenUrl('https://stackoverflow.com/oauth/access_token')
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setCallbackFunction('authCallbackSE')
.setPropertyStore(PropertiesService.getUserProperties())
.setRedirectUri('https://script.google.com/macros/d/{SCRIPT ID}/usercallback')
.setScope('read_inbox');
}
function authCallbackSE(request) {
var SEService = getStackExchangeService_();
var isAuthorized = SEService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
不清楚我要去哪里,但是我认为当我输入authorizationURL时,应该将我重定向到授权页面。谢谢!
答案 0 :(得分:1)
Stackexchange API,默认情况下以application/x-www-form-urlencoded
的形式发送访问令牌,默认情况下,OAuth2库的tokenFormat需要JSON。
通过将tokenUrl设置为https://stackoverflow.com/oauth/access_token/json
或
在OAuth2库中明确设置tokenFormat以形成使用setTokenFormat(TOKEN_FORMAT.FORM_URL_ENCODED)