簡體   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