【问题标题】:How to write cURL request with basic auth in Laravel 8如何在 Laravel 8 中使用基本身份验证编写 cURL 请求
【发布时间】:2021-04-03 10:15:44
【问题描述】:

我有以下来自 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',
    ]
]);

【问题讨论】:

    标签: php authentication curl paypal laravel-8


    【解决方案1】:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      相关资源
      最近更新 更多