使用cURL在api中拒绝承载授权

时间:2019-01-18 23:39:06

标签: php curl post bearer-token

我想向API服务器发出一个简单的发布请求。我知道,网络上有很多有关cURL的信息,但是我不知道为什么会得到:

[message] => Authorization has been denied for this request.

因此,API使用标准的承载令牌(在标头Authorization: Bearer {tokenID}中)

我的php代码:

$body = array(
        "id" => $uuid,
        "userAccountId" => $userAccountId,
        "email" => $email,
        "first_name" => $first_name,
        "last_name" => $last_name,
        "phone" => $phone,
      );

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_HTTPHEADER, http_build_query(array(
        'Authorization' => $token,
      )));
      curl_setopt($ch, CURLOPT_URL, $myurl);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($body));
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      $result = curl_exec($ch);
      curl_close($ch);
      $result = json_decode($result);

最有趣和奇怪的是,当我使用邮递员向具有相同正文和相同标头(相同令牌)的相同url发送Post请求时,它可以工作,但是不适用于php cURL 。另外,我尝试使用https://www.codepunker.com/tools/http-requests并得到了相同的授权错误。有谁能提供帮助吗?

1 个答案:

答案 0 :(得分:0)

我发现了问题:我应该以以下方式使用json_encode($body)http_build_query($body)和标题:

      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer .....',
        'accept: application/json',
        'content-type: application/json',
      ));