Using the following code, I can get the accessToken variable, but I’m not able to get the paymentDetails, it just returns a null value. So in other words the API portion of code is not working. The PayPal API to get the paymentDetails based on the paymentId is not working. Is there a cURL option that is missing?
Of course I have removed the clientId, clientSecret and paymentId values in the code below.
<?php
// replace with your actual live PayPal credentials
$clientId = '';
$clientSecret = '';
// get accessTokenUrl
$accessTokenUrl = 'https://api.paypal.com/v1/oauth2/token';
// replace with the payment ID retrieved from webhook or API response
$paymentId = '';
// access token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $accessTokenUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_USERPWD => $clientId . ':' . $clientSecret,
CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Accept-Language: en_US'
),
));
// get accessToken
$result = curl_exec($curl);
$array = json_decode($result, true);
$accessToken = $array['access_token'];
// get paymentDetailsUrl
$paymentDetailsUrl = 'https://api.paypal.com/v1/payments/' . $paymentId;
$curl = curl_init($paymentDetailsUrl);
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
)
));
// get paymentDetailsResponse
$paymentDetailsResponse = curl_exec($curl);
$curlError = curl_error($curl);
curl_close($curl);
// check condition
if ($curlError) {
echo 'Error retrieving payment details: ' . $curlError;
exit;
}
// get paymentDetails
$paymentDetails = json_decode($paymentDetailsResponse, true);
// check condition
if (isset($paymentDetails['error'])) {
echo 'Error retrieving payment details: ' . $paymentDetails['error_description'];
exit;
}
// get variables
$payerId = $paymentDetails['payer']['payer_info']['payer_id'];
$amount = $paymentDetails['transactions'][0]['amount']['value'];
$currency = $paymentDetails['transactions'][0]['amount']['currency'];
$state = $paymentDetails['state']; // e.g., "approved"
// echo output
echo 'Payer ID: ' . $payerId . '<br />';
echo 'Payment Amount: ' . $amount . ' ' . $currency . '<br />';
echo 'Payment State: ' . $state . '<br />';