繁体   English   中英

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

[英]PHP: how to make a GET request with HTTP-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 然后我想发送基本身份验证以获取我的 url 状态。 例子:

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;

您可以通过多种方式向 API 端点发出GET请求。 但开发人员更喜欢使用CURL发出请求。 我提供了一个代码片段,展示了如何使用 Basic Auth 授权设置Authorization标头,如何使用 php 的base64_encode()函数对用户名和密码进行编码(Basic Auth 授权支持base64编码),以及如何使用 php 准备用于发出请求的标头卷曲库。

哦! 不要忘记用你的替换用户名密码端点(api 端点)。

使用卷曲

<?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文档,了解如何使用file_get_contents()使用流上下文。

希望这会帮助你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM