将 paypal curl 获取访问令牌请求转换为 guzzle

mkm*_*uss 4 curl paypal internal guzzle

我需要一些有关 paypal rest api 的帮助。

我使用 guzzle 作为 http 客户端来使用 paypal api

当我在命令行中使用 curl 尝试 paypal 示例时,它确实有效

但是当我想用 guzzle 重现它时,我总是从贝宝收到内部 500 错误..

这是来自官方文档的 paypal curl 示例(请在此处查看https://developer.paypal.com/webapps/developer/docs/integration/direct/make-your-first-call/):

curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
  -H "Accept: application/json" \
  -H "Accept-Language: en_US" \
  -u "clientId:clientSecret" \
  -d "grant_type=client_credentials"
Run Code Online (Sandbox Code Playgroud)

这是我的狂饮代码:

/**
 * Etape 1 récuperer un access token
 */
$authResponse = $client->get("https://api.sandbox.paypal.com/v1/oauth2/token", [
    'auth' =>  [$apiClientId, $apiClientSecret, 'basic'],
    'body' => ['grant_type' => 'client_credentials'],
    'headers' => [
    'Accept-Language' => 'en_US',
    'Accept'     => 'application/json' 
    ]
]);

echo $authResponse->getBody();
Run Code Online (Sandbox Code Playgroud)

我已经尝试过 auth basic、digest,但到目前为止都没有奏效。

感谢您对此的任何帮助!

Pra*_*yal 7

这是使用guzzlehttp

$uri = 'https://api.sandbox.paypal.com/v1/oauth2/token';
$clientId = \\Your client_id which you got on sign up;
$secret = \\Your secret which you got on sign up;

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $uri, [
        'headers' =>
            [
                'Accept' => 'application/json',
                'Accept-Language' => 'en_US',
               'Content-Type' => 'application/x-www-form-urlencoded',
            ],
        'body' => 'grant_type=client_credentials',

        'auth' => [$clientId, $secret, 'basic']
    ]
);

$data = json_decode($response->getBody(), true);

$access_token = $data['access_token'];
Run Code Online (Sandbox Code Playgroud)


And*_*rew 2

你的问题在第一行。

    $authResponse = $client->get
Run Code Online (Sandbox Code Playgroud)

应该是一个帖子。

     $authResponse = $client->post
Run Code Online (Sandbox Code Playgroud)

我也遇到过类似的问题。

编辑:我也喜欢如果你想使用 JSON 作为请求的正文,可以使用 json_encode 或用 json 替换正文,guzzle 将处理其余的事情。在你之前的代码中...

$authResponse = $client->post("https://api.sandbox.paypal.com/v1/oauth2/token", [
    'auth' =>  [$apiClientId, $apiClientSecret, 'basic'],
    'json' => ['grant_type' => 'client_credentials'],
    'headers' => [
        'Accept-Language' => 'en_US',
        'Accept' => 'application/json' 
    ]
Run Code Online (Sandbox Code Playgroud)

]);