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

5

我想从这个端点获取交易状态。

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,我想使用基本身份验证发送请求以获取我的URL的状态。例如:

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

我该如何制作这个?

我也尝试使用postman,并使用基本身份验证进行操作,它可以正常工作并显示正确结果。

当我在网上搜索时,它会显示像CURL、基本身份验证等内容,但由于我的英语限制和对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;

Postman可以为您提供任何语言的请求:https://learning.postman.com/docs/postman/sending-api-requests/generate-code-snippets/ - GrenierJ
这个回答解决了你的问题吗?如何使用PHP curl进行HTTP基本身份验证请求? - Nico Haase
1个回答

10
有几种方法可以向API端点发出GET请求。但开发人员更喜欢使用CURL进行请求。我提供了一个代码片段,展示如何使用php的base64_encode()函数编码用户名和密码(Basic Auth授权支持base64编码),以及如何为使用php的CURL库进行请求准备标头并设置带有Basic Auth授权的Authorization标头。请注意替换您自己的用户名密码端点(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);

你可以参考这篇 PHP doc,了解如何使用 file_get_contents() 函数的流上下文。希望对你有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接