LinkedIn API OAUTH 返回 "grant_type" 错误

LinkedIn API OAUTH returning "grant_type" error

我对编码还很陌生,但我正在尝试使用 LinkedIn 的 API 编写一个简单的脚本,将组织的关注者数量拉入 google 应用程序脚本。在我什至可以查询 API 之前,我必须使用 LinkedIn API here.

中解释的誓言进行身份验证

这个函数returns有一个错误响应

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)

  }

当我尝试发送 headers 时,我收到此错误作为响应

{"error":"invalid_request","error_description":"A required parameter \"grant_type\" is missing"}

grant_typeclient_idclient_secret不要进入请求的header。相反,请尝试将它们放入内容类型为 x-www-form-urlencoded 的 POST 请求的 body 中,就像您在发布的代码的 header 中已经拥有的那样。

例如:

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))
  })

使用 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)

}