我如何请求授权的 Http headers

How can i request Http with authorization headers

我对 Guzzle POST 请求

有疑问

这是我的代码

$req = $client->request('POST', $endpoint, [
      'headers' => [
          'Content-Type' => 'application/json',
          'Authorization' => 'Basic '.$this->api_credential
         ], $body);

它总是响应 401 "Please include your API key as an Authorization header"

我是否必须对凭据进行 base64 编码?

及其使用基本授权

使用 Bearer 而不是 Basic 授权。希望能解决问题

$req = $client->request('POST', $endpoint, [
      'headers' => [
          'Content-Type' => 'application/json',
          'Authorization' => 'Bearer '.$this->api_credential
         ], $body);

请确保您的服务器接受授权header。接受授权 header 的 .htaccess 代码如下

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

您可以使用以下 curl 请求检查服务器是否接受授权码

$ch = curl_init();  
curl_setopt( $ch,CURLOPT_URL,'https://yourendpoint.com/apiFile.php'  );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Basic ' .$api_credential
));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);    
$returnData = json_decode($result, true);

根据您尝试验证的 API,您将需要 base64_encode 用于 Basic 验证的凭据 (username:password)[其中 username 是您的 API 密钥,password 将为空白]:

授权header:

'Authorization' => 'Basic '. base64_encode($this->api_credential .':'),