首页 > 解决方案 > 如何在 Laravel 8 中使用基本身份验证编写 cURL 请求

问题描述

我有以下来自 PayPal Payout SDK 的代码,用于从 PayPal API 获取访问令牌。

curl -v POST https://api-m.sandbox.paypal.com/v1/oauth2/token \
  -H "Accept: application/json" \
  -H "Accept-Language: en_US" \
  -u "CLIENT_ID:SECRET" \
  -d "grant_type=client_credentials"

要获取访问令牌,我尝试了以下操作。

$client_id = "AWN5555";
$secret = "44444";
$url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
$data = ['grant_type:client_credentials'];

$response = Http::withHeaders([
    'Accept:application/json',
    'Accept-Language:en_US',
    "Content-Type: application/x-www-form-urlencoded"
])->withBasicAuth($client_id, $secret)
    ->post($url, $data);

// OR

$response = $client->request('POST', $url, [
    'headers' => [
        'Accept' => 'application/json',
        'Accept-Language' => 'en_US',
        'Authorization ' => ' Basic ' .
            base64_encode($client_id . ':' . $secret)
    ],
    'form_params' => [
        'grant_type' => 'client_credentials',
    ]
]);

标签: phpauthenticationcurlpaypallaravel-8

解决方案


laravel 7 或 8 解决方案:

$client_id = "AWN5555";
$secret = "44444";
$url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
$data = [
            'grant_type' => 'client_credentials',
        ];

        $response =  Http::asForm()
                            ->withBasicAuth($client_id, $secret)
                            ->post($url, $data);

php原生解决方案:

$client_id = "AWN5555";
$secret = "44444";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api-m.sandbox.paypal.com/v1/oauth2/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
CURLOPT_HTTPHEADER => [
    'Authorization: Basic '.base64_encode($client_id.':'.$secret)
  ],
]);

$response = curl_exec($curl);

curl_close($curl);

推荐阅读