【问题标题】:PHP: how to make a GET request with HTTP-Basic authenticationPHP:如何使用 HTTP-Basic 身份验证发出 GET 请求
【发布时间】:2020-02-12 07:41:44
【问题描述】:

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

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;

【问题讨论】:

标签: php api basic-authentication


【解决方案1】:

您可以通过多种方式向 API 端点发出 GET 请求。但开发人员更喜欢使用CURL 发出请求。我提供了一个代码 sn-p,它显示了如何使用基本身份验证授权设置Authorization 标头,如何使用 php 的base64_encode() 函数对用户名和密码进行编码(基本身份验证授权支持base64 编码),以及如何准备标头用于使用 php 的 CURL 库发出请求。

哦! 不要忘记用户名密码endpoint(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() 来使用流上下文。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2011-09-17
    • 2017-07-23
    • 2015-10-07
    相关资源
    最近更新 更多