Search code examples
phppaypalpaypal-sandboxguzzlepaypal-connect

Can not send POST request to Paypal Connect from inside Laravel app


I have an app that connects to Paypal Connect. Upon Paypal connect button click I am taken to Paypal website and I do receive a code they send after authentication. But then I can't send the POST request to paypal with authorization_code to require user info I am receiving an error. I am getting this error: Authentication failed due to invalid authentication credentials or a missing.. And I am pretty sure that my credentials are good. Am I missing something?

This is what Paypal gives me:

curl -X POST https://api.sandbox.paypal.com/v1/oauth2/token \
-H 'Authorization: Basic {Your Base64-encoded ClientID:Secret}=' \
-d 'grant_type=refresh_token&refresh_token={refresh token}'

I am using Guzzle to send post request. Please see code below

$client = new \GuzzleHttp\Client();
$headers = [
    'Authorization' => 'Basic clientID:clientSecret'
];

$response = $client->request('POST',
'https://api.sandbox.paypal.com/v1/oauth2/token',
[
    'grant_type ' => 'authorization_code',
    'code' => $data['code']
], 
$headers);

Solution

  • Looking at the paypal api documentation, it appears as though your authorization header is incorrect.

    Authorization request header: The Base64-encoded client ID and secret credentials separated by a colon (:). Use the partner's credentials.

    You can use php's base64_encode() function to do this.

    $client = new \GuzzleHttp\Client();
    
    $authorizationString = base64_encode($clientId . ':' . $clientSecret);
    
    $client->request(
        'POST', 
        'https://api.sandbox.paypal.com/v1/oauth2/token', 
        [
            'headers' => [
                'Authorization' => 'Basic ' . $authorizationString
            ], 
            'form_params' => [
                'grant_type ' => 'authorization_code',
                'code' => $data['code']
            ]
        ]
    );