PHP:如何使用HTTP基本身份验证发出GET请求

时间:2020-02-12 07:41:44

标签: php api basic-authentication

我想从该端点获取交易状态

https://api.sandbox.midtrans.com/v2/[orderid]/status

但是它需要基本的身份验证,当我将其发布到URL上时,得到的结果是:

{
    "status_code": "401",
    "status_message": "Operation is not allowed due to unauthorized payload.",
    "id": "e722750a-a400-4826-986c-ebe679e5fd94"
}

,我有一个网站ayokngaji.com,然后我想发送基本身份验证以获取我的网址的状态。示例:

ayokngaji.com/v2/[orderid]/status = (BASIC AUTH INCLUDED)

我该怎么做?

我还尝试使用邮递员,并使用基本身份验证功能,并显示正确的结果

当我在线搜索时 它向我显示了CURL,BASIC AUTH,但是我对这些教程都不了解,因为我对英语的了解有限,并且对php的了解很少

已解决:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.sandbox.midtrans.com/v2/order-101c-1581491105/status",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Accept: application/json",
    "Content-Type: application/json",
    "Authorization: Basic U0ItTWlkLXNl"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

1 个答案:

答案 0 :(得分:4)

有几种方法可以向API端点发出GET请求。但是开发人员更喜欢使用CURL发出请求。我提供的代码段显示如何使用基本身份验证授权设置Authorization标头,如何使用php的base64_encode()函数编码用户名和密码(基本身份验证支持base64编码),以及如何使用php的CURL库准备用于发出请求的标头。

哦! 别忘了,将用户名密码端点(API端点)替换为您的用户名。

使用CURL

<?php

$username = 'your-username';
$password = 'your-password'
$endpoint = 'your-api-endpoint';

$credentials = base64_encode("$username:$password");

$headers = [];
$headers[] = "Authorization: Basic {$credentials}";
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Cache-Control: no-cache';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);

// Debug the result
var_dump($result); 

使用流上下文

<?php

// Create a stream
$opts = array(
    'http' => array(
        'method' => "GET",
        'header' => "Authorization: Basic " . base64_encode("$username:$password")
    )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$result = file_get_contents($endpoint, false, $context);

echo '<pre>';
print_r($result);

有关如何使用file_get_contents()使用流上下文的信息,您可以参考此PHP doc

希望这对您有帮助!