【问题标题】:LinkedIn API OAUTH returning "grant_type" errorLinkedIn API OAUTH 返回“grant_type”错误
【发布时间】:2021-09-01 22:12:15
【问题描述】:
我对编码很陌生,但尝试使用 LinkedIn 的 API 编写一个简单的脚本,将组织的关注者计数拉入谷歌应用脚本。在我什至可以查询 API 之前,我必须使用 LinkedIn API here 中解释的誓言进行身份验证。
这个函数返回一个错误响应
function callLinkedAPI () {
var headers = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
"headers": headers,
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}
当我尝试通过发送标头时,我收到此错误作为响应
{"error":"invalid_request","error_description":"A required parameter \"grant_type\" is missing"}
【问题讨论】:
标签:
google-apps-script
oauth-2.0
linkedin
linkedin-api
【解决方案1】:
grant_type, client_id, client_secret 不要进入请求的头部。相反,请尝试将它们放在 POST 请求的正文中,内容类型为 x-www-form-urlencoded,就像您在发布的代码的标头中已有的那样。
例如:
fetch('https://www.linkedin.com/oauth/v2/accessToken/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: '78ciob33iuqepo',
client_secret: 'deCgAOhZaCrvweLs'
})
})
.then(response => response.json())
.then(responseData => {
console.log(JSON.stringify(responseData))
})
【解决方案2】:
使用 Apps 脚本,您应该像这样发送有效负载:
示例:
function callLinkedAPI() {
var payload = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true,
"payload":payload
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}