Hello I have been working with the paypal php sdk.
I have been getting the following error when trying to create a Payment
PayPalConnectionException
Got Http response code 401 when accessing https://api.sandbox.paypal.com/v1/oauth2/token.
I am sure the $clientId and $clientSecret values are correct.
Running in sandbox mode - still in development phase.
Has anyone come across this?
My Code (with private info stripped)
use PayPal\Api\Amount;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\PayerInfo;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction as PayPalTransaction;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Rest\ApiContext;
//$transaction represents a Transaction object stored in database
//$product represents a Product object stored in database
$payer = (new Payer())
->setPaymentMethod('paypal')
;
$itemList = new ItemList();
$itemList->addItem(
(new Item)
->setName($product->getName())
->setDescription($product->getName())
->setSku($product->getSku())
);
$amount = (new Amount())
->setCurrency($transaction->getCurrency())
->setTotal($transaction->getTotal())
;
$ppTransaction = (new PayPalTransaction())
->setItemList($itemList)
->setAmount($amount)
->setReferenceId($transaction->getId())
;
$redirectUrls = (new RedirectUrls())
->setReturnUrl('http://.../S')
->setCancelUrl('http://.../F')
;
$apiContext = new ApiContext(
new OAuthTokenCredential(
$clientId,
$clientSecret
)
);
$payment = (new Payment())
->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$ppTransaction])
;
$payment->create($apiContext);
return $payment->getId();
A dump of the underlying paypal curl request is as follows:
[
"url" => "https://api.sandbox.paypal.com/v1/oauth2/token"
"method" => "POST"
"headers" => array:3 [
0 => "User-Agent: PayPalSDK/PayPal-PHP-SDK 1.11.0 (platform-ver=7.0.7; bit=64; os=Linux_4.4.57-18.3-default; machine=x86_64; crypto-lib-ver=1.0.2j-fips; curl=7.37.0)"
1 => "Authorization: Basic xxx="
2 => "Accept: */*"
]
"data" => "grant_type=client_credentials"
]
this issue could (probably) not be related to the SDK as such.
The 401 error code, indicates "authentication errors".
As this is hard to debug, can you please check the following:
Does your account have eligibility on specific feature - try to check your account status and Currency/Country support
Can you run a direct test via curl:
curl -v -u "client_id:secret" "https://api.sandbox.paypal.com/v1/oauth2/token" -X POST -d "response_type=token&grant_type=client_credentials"
Check the config files of your SDK, don't assume default configs are OK - check for any possible culprits in there
And are you guys sure, you have properly set the SDK to "sandbox" mode instead of live (which could be the default)? See: https://github.com/paypal/PayPal-PHP-SDK/wiki/Going-Live