php - 如何在 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',
]
]);
解决方案
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);
推荐阅读
- amazon-web-services - 如何将 AWS Amplify Admin Queries API 限制为多个用户池组?
- python - Call Of Duty API - 如何仅通过输入用户名来获取所有用户平台的列表?
- java - Kafka 和 zookeeper docker 容器在主机上与我的 api 对话
- java - JPARepository 中的自定义查询创建正确的 WHERE 子句
- css - 覆盖角度材料 css - 为什么 !important 有效
- c# - 如何在 Blazor 中根据条件将项目添加到表中
- xamarin.forms - Xamarin Forms:如何在 Plugin.MediaManager.Forms 中播放音频时更改背景颜色?
- python - tensorlfow 什么时候提出“不要通过 `graph_parents`。”?
- javascript - 在 Flutter Web 中从 JS 调用 Dart 方法
- python - Dash 中的回调列表函数