i'm working on Laravel 5.2 with Paypal-SDK sandbox
I get this error during call mainly paypal class
Exception: Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.
this is my code:
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$inputs = (object) $request->all();
$items = [];
for ($i = 1; $i <= $request->input('items_number'); $i++)
{
$item_name = $request->input("item_name_$i");
$item_quantity = $request->input("item_quantity_$i");
$item_price = $request->input("item_price_$i");
if(empty($item_price) || $item_price == 0){
return redirect('/');
}
$item = new Item();
$item->setName($item_name)
->setQuantity($item_quantity)
->setPrice($item_price)
->setCurrency('USD');
$items[] = $item;
}
// add item to list
$item_list = new ItemList();
$item_list->setItems($items);
// price of all items together
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal($request->input('total_price'));
// transaction
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('This is just a demo transaction.');
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(URL::to('/paypal-payment/done'))
->setCancelUrl(URL::to('/paypal-payment/cancel'));
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
try {
$payment->create($this->_api_context);
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
if (config('app.debug')) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
exit;
} else {
die('Some error occur, Sorry for inconvenient');
}
}
foreach($payment->getLinks() as $link)
{
if($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
/* here you could already add a database entry that a person started buying stuff (not finished of course) */
Session::put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
// redirect to paypal
return redirect()->away($redirect_url);
}
return 'This is some error';
How can i solve this?
There may be two major reason for such kind of issues on paypal please check below:-
1) Check your subTotal, tax, shipping in case of single item and multiple items and its sum should be equal to total i.e subTotal + tax + shipping = total
2) Check your returnUrl and cancelUrl there should be no space and special character use urlencode for this.
Below code work for me it can help you i have also wasted lots of time for this:-
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
// use these at the top of the class
/**
* Function : paypalPay()
* Description : Used to pay the payment using paypal
* Author : kantsverma
* Parameters :
*/
public function paypalPay()
{
require_once(ROOT . DS . 'vendor' . DS . "autoload.php");
// integrate paypal
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'YOUR APPLICATION CLIENT ID',
'YOUR APPLICATION CLIENT SECRET'
)
);
$payer = new Payer();
$payer->setPaymentMethod("paypal");
//Itemized information (Optional) Lets you specify item wise information
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setPrice(17);
$itemList = new ItemList();
$itemList->setItems(array($item1));
$details = new Details();
$details->setShipping(1)
->setTax(2)
->setSubtotal(17);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(20)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$baseUrl = $this->getBaseUrl();
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl")
->setCancelUrl("$baseUrl");
$payment = new Payment();
$payment->setIntent("order")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
//For Sample Purposes Only.
$request = clone $payment;
try {
$paymentdetail = $payment->create($apiContext);
echo '<pre>';
print_r($paymentdetail);
echo '</pre>';
die('inside try ');
} catch (Exception $ex) {
//NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printError("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
die('Inside catch');
}
//Get redirect url
//The API response provides the url that you must redirect the buyer to. Retrieve the url from the $payment->getApprovalLink() method
$approvalUrl = $payment->getApprovalLink();
//NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment);
return $payment;
}
I have created above functions and called the functions you can remove the die and print_r() inside the try it works for me.