Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform paypal curl get access token request into guzzle

i'm needing some help with paypal rest api.

I'm using guzzle as http client to consume paypal api

When i try paypal example in command line with curl, it does works

but when i want reproduce it with guzzle i always get Internal 500 ERROR from paypal..

Here's paypal curl example from official docs ( check here 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"

Here's my guzzle code :

/**
 * 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();

I've tried with auth basic, digest but none worked so far.

Thanks for any help on this !

like image 471
mkmuss Avatar asked Dec 11 '22 04:12

mkmuss


2 Answers

This is using 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'];
like image 122
Pranay Aryal Avatar answered Mar 15 '23 21:03

Pranay Aryal


Your issue is on the first line.

    $authResponse = $client->get

It should be a post.

     $authResponse = $client->post

I had a similar issue for a little bit.

EDIT: I also fond that if you want to use JSON for the body of a request either use json_encode or replace body with json, guzzle will handle the rest. In your previous code...

$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' 
    ]

]);

like image 38
Andrew Avatar answered Mar 15 '23 22:03

Andrew