Fir*_*mer 4 php api basic-authentication
我想从这个端点获取交易状态
https://api.sandbox.midtrans.com/v2/[orderid]/status
Run Code Online (Sandbox Code Playgroud)
但它需要一个基本的身份验证,当我将它发布到 URL 上时,我得到的结果是:
{
"status_code": "401",
"status_message": "Operation is not allowed due to unauthorized payload.",
"id": "e722750a-a400-4826-986c-ebe679e5fd94"
}
Run Code Online (Sandbox Code Playgroud)
我有一个网站 ayokngaji.com 然后我想发送基本身份验证以获取我的 url 状态。例子:
ayokngaji.com/v2/[orderid]/status = (BASIC AUTH INCLUDED)
Run Code Online (Sandbox Code Playgroud)
我怎么做这个?
我还尝试使用邮递员,并使用基本身份验证它可以工作,并显示正确的结果
当我在网上搜索它时,它显示我喜欢 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;
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式GET向 API 端点发出请求。但开发人员更喜欢使用CURL. 我提供了一个代码片段,展示了如何Authorization使用基本身份验证授权设置标头、如何使用 php 的base64_encode()函数对用户名和密码进行编码(基本base64身份验证授权支持编码),以及如何使用 php 的 CURL 库准备用于发出请求的标头。
哦!不要忘记用你的替换用户名、密码和端点(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);
Run Code Online (Sandbox Code Playgroud)
使用流上下文
<?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);
Run Code Online (Sandbox Code Playgroud)
您可以参考这个 php文档,了解如何使用file_get_contents().
希望这会帮助你!