0

I am implementing PayPal Checkout (https://developer.paypal.com/docs/checkout/standard/integrate/) in a Symfony 5.4 project.

I am kind of stuck retrieving an access token by sending clientId and clientSecret to the PayPal REST API (https://developer.paypal.com/api/rest/authentication/) using Symfony HttpClient.

PayPal defines a curl request to get the token:

curl -v -X POST "https://api-m.sandbox.paypal.com/v1/oauth2/token" \
    -u "<CLIENT_ID>:<CLIENT_SECRET>" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "grant_type=client_credentials"

I was trying to do that using HttpClient from Symfony. Without any success unfortunately as I can't figure out how to pass the options.

I tried passing the options with extra.curl using CURLOPT_VERBOSE, CURLOPT_USERNAME, CURLOPT_HEADER (couldn't find a define for the grant_type option). It seems that setting header and verbose mode is not allowed in extra.curl so I tried setting that in the 'body' part instead. That led to 401 then.

Here is what I tried:

$response = $this->httpClient->request('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', [
    'extra' => [
        'curl'=> [
            CURLOPT_VERBOSE => 1,
            CURLOPT_USERNAME => $clientId.':'.$clientSecret,
            CURLOPT_HEADER => "Content-Type: application/x-www-form-urlencoded"
        ]
    ]
]);

And alternatively:

$response = $this->httpClient->request('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', [
    'body' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'grant_type' => 'client_credentials'
    ],
    'extra' => [
        'curl'=> [
            CURLOPT_USERNAME => $clientId.':'.$clientSecret,
        ]
    ]
]);

I couldn't find any proper HttpClient curl usage examples. So basicaly I am trying to understand how to realize the PayPal Auth request using HttpClient. Any hints on that would be most welcome.

user3440145
  • 793
  • 10
  • 34

1 Answers1

1

Use 'auth_basic'...

$response = $this->httpClient->request('POST', 'https://api-m.sandbox.paypal.com/v1/oauth2/token', [
    'auth_basic' => [$clientId, $clientSecret],

    // ...
]);
Preston PHX
  • 27,642
  • 4
  • 24
  • 44
  • Thanks! That works. For anyone who wants to use it: The body-part in my questions last code sample is needed too - so one needs to set Content-Type and grant_type like shown in the 'body' => ... part. There is no need to set anything in 'extra'.'curl' though. – user3440145 Sep 12 '22 at 00:20
  • is your solution actualy using curl though? How would I construct further calls to the API which are shown in curl style examples? – user3440145 Sep 12 '22 at 00:24
  • Enabling curl is done when you initialize the httpClient https://symfony.com/doc/current/http_client.html#enabling-curl-support – Preston PHX Sep 12 '22 at 00:32