I'm coming to desperatly try to find help about a error that even the paypal technical support still didn't achieve to understand...
This is the error returned : "Attempted to load class "ApiContext" from namespace "PayPal\Rest".
Did you forget a "use" statement for another namespace?"
I installed the paypal api via composer, and here is the code using this api. I followed the documentation steps by steps, so I really don't understand this error... the use statements are all there... :
<?php
namespace PlatformBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;
class PaypalController extends Controller
{
private function paypalKeys()
{
return new ApiContext(
new OAuthTokenCredential(
'AUWLQ9xMRA54XpqgX_Bbd0koHkIzfAFnZSPXipGbIZAqVnJCaWj5B4hga5dbd2UE0diElegudMDR9dj0',
'EPStewzop-DjMhdyvw51TJBnpZUHt6hGahwmRSDljIhYmDVGMPXsAV0oWoMiCcQpVdXsyOdnZJN1yRZC'
)
);
}
public function chargeAction()
{
$this->paypalKeys();
$price = 10;
$total = $price;
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item->setName('transfer')
->setCurrency('eur')
->setQuantity(1)
->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details->setShipping(0)
->setSubtotal($price);
$amount = new Amount();
$amount->setCurrency('eur')
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription('Description')
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl('http://localhost/dublin/web/app_dev.php/admin')
->setCancelUrl('http://localhost/dublin/web/app_dev.php/cancel');
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
// try {
$payment->create($this->paypalKeys());
// } catch (Exception $e) {
// die($e);
// }
//
// return new Response('true');
// echo $approvalUrl = $payment->getApprovalLink();
}
}
Thanks for your help...
Related
I am implementing a functionality where admin pays the sellers on their PAYPAL email accounts. but for some reason I am getting this error while implementing the following code.
I believe the error comes when the function processPaymentInvoiceViaCheckout returns redirect($approvalUrl)
Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in
Routes
//create payment object
Route::get('/invoices/process-payment','PaypalController#processPaymentInvoiceViaCheckout');
//when payment object is created then get its details and execute payment to send money.
Route::get('/invoices/response-success','PaypalController#paypalResponseSuccess');
//when cancel to pay
Route::get('/invoices/response-cancel','PaypalController#paypalResponseCancel');
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payee;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Rest\ApiContext;
use PHPUnit\TextUI\ResultPrinter;
class PaypalController extends Controller
{
private $api_context;
public function __construct()
{
$this->api_context = new ApiContext(
new OAuthTokenCredential(config('paypal.client_id'), config('paypal.secret'))
);
$this->api_context->setConfig(config('paypal.settings'));
}
public function processPaymentInvoiceViaCheckout(){
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
// ->setSku("123123") // Similar to `item_number` in Classic API
->setPrice(7.5);
$item2 = new Item();
$item2->setName('Granola bars')
->setCurrency('USD')
->setQuantity(5)
// ->setSku("321321") // Similar to `item_number` in Classic API
->setPrice(2);
$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(17.50);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(20)
->setDetails($details);
$payee = new Payee();
//this is the email id of the seller who will receive this amount
$payee->setEmail("seller-paypal-businness-account-email#business.example.com");
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setPayee($payee)
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl(url('/invoices/response-success'))
->setCancelUrl(url('/invoices/response-cancel'));
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
$request = clone $payment;
try {
//create payment object
$createdPayment = $payment->create($this->api_context);
//get payment details to get payer id so that payment can be executed and transferred to seller.
$paymentDetails = Payment::get($createdPayment->getId(), $this->api_context);
$execution = new PaymentExecution();
$execution->setPayerId($paymentDetails->getPayer());
$paymentResult = $paymentDetails->execute($execution,$this->api_context);
} catch (\Exception $ex) {
//handle exception here
}
//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();
return redirect($approvalUrl);
}
public function paypalResponseCancel(Request $request)
{
//normally you will just redirect back customer to platform
return redirect('invoices')->with('error','You can cancelled payment');
}
public function paypalResponseSuccess(Request $request)
{
if (empty($request->query('paymentId')) || empty($request->query('PayerID')) || empty($request->query('token'))){
//payment was unsuccessful
//send failure response to customer
}
$payment = Payment::get($request->query('paymentId'), $this->api_context);
$execution = new PaymentExecution();
$execution->setPayerId($request->query('PayerID'));
// Then we execute the payment.
$result = $payment->execute($execution, $this->api_context);
dd($request->all(),$result);
//payment is received, send response to customer that payment is made.
}
}
I followed some dudes tutorial on how to Charge People with PayPal using the PHP SDK. It all works like a charm as long as I'm in Testmode, but if I cange my API Keys to the "live" ones, I only get an HTTP Error 401.
I understand that this is because I have to set the Application to "Live".
I followed the Guide on PayPals GitHub Page.
(https://github.com/paypal/PayPal-PHP-SDK/wiki/Going-Live)
Dont worry, I dont do this for the acutal Web, I just want to get back into PHP and it drives me nuts that I am not able to configure this script.
I have the following "charge.php":
require 'app/start.php';
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
if(!isset($_POST['product'])){
echo $_POST['product'];
die("Nope");
}
$product="Premium";
$price="1.00";
$shipping="0.00";
$total = $price+$shipping;
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item->setName($product)
->setCurrency('EUR')
->setQuantity(1)
->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details->setShipping($shipping)
->setSubtotal($price);
$amount = new Amount();
$amount->setCurrency('EUR')
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription($product)
//UserID
->setInvoiceNumber(rand());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl('/paid.php?sucess=true')
->setCancelUrl('/paid.php?sucess=false');
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
try{
$payment->create($paypal);
} catch (Exception $e){
die($e);
}
$approvalUrl=$payment->getApprovalLink();
header("Location: {$approvalUrl}");
And the following "start.php" with my API Credentials in it:
require 'vendor/autoload.php';
define('SITE_URL', '/charge.php');
$paypal = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'xx',
'xx'
)
);
Can someone give me a hint, where I need to confige the App to use PayPals Live API? I tried it in the carge.php, but I only get the PHP Error, that I use an undefined variable.
Im talking about the following Snipit from PayPals Github:
$apiContext->setConfig(
array(
...
'mode' => 'live',
...
)
);
Any help would be much appreciated.
Cheers, Flo
Okay, I figured it out.
For anyone who has the same issue:
For the config array to work, you also have to put the Nameclass in there.
So the correct "start.php" should look like this:
<?php
use \PayPal\Rest\ApiContext;
use \PayPal\Auth\OAuthTokenCredential;
require 'vendor/autoload.php';
define('SITE_URL', 'charge_paypal.php');
$paypal = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'x',
'x'
)
);
$paypal->setConfig([
'mode' => 'live',
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
]);
?>
I want to integrate paypal payments to my site.
I tried integrating the paypal button form straight from paypal but there is a problem with it. The price of the product can be changed by easily inspecting the element and changing the price input.
I found out about the Paypal PHP SDK so I installed it via composer. The problem I'm having is when I want the user to pay for the product.
I copied and pasted the Create Payment method found here. But I'm getting an error:
Notice: Undefined variable: apiContext in C:\xampp\htdocs\paypal\index.php on line 62
Fatal error: Class 'ResultPrinter' not found in C:\xampp\htdocs\paypal\index.php on line 64
I know I'm getting this error because I haven't initialized this variable. I don't know where to create it and what this variable it must contain. How can I fully integrate this?
This is my full PHP code:
<?php
require 'vendor/autoload.php';
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;
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setSku("123123") // Similar to `item_number` in Classic API
->setPrice(7.5);
$item2 = new Item();
$item2->setName('Granola bars')
->setCurrency('USD')
->setQuantity(5)
->setSku("321321") // Similar to `item_number` in Classic API
->setPrice(2);
$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(17.50);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(20)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
//I changed the base url and the return url's to mine.
$baseUrl = "http://www.localhost/paypal";
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
$request = clone $payment;
try {
$payment->create($apiContext);
} catch (Exception $ex) {
ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
exit(1);
}
$approvalUrl = $payment->getApprovalLink();
ResultPrinter::printResult("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment);
return $payment;
It looks like you've not defined $apiContext. I'm not totally familiar with this SDK but it looks like you can create one like so:
$apiContext = new \Paypal\Rest\ApiContext(
new \PayPal\Auth\AuthTokenCredential(
$clientId,
$clientSecret
)
);
reference
You will need to pass in your $clientId and $clientSecret that you have obtained from PayPal.
I am very new to the PayPal API and REST request/responses. As such, I have been trying to follow along with online samples (mostly from GitHub) about how to use PayPal's REST Api to process payments.
However, I have encountered a problem. When I click on the link that is generated, I am successfully redirected to PayPal's site. However, at the checkout page, there is nothing that indicates the amount of the purchase. What might the issue be? Thanks!
<?php
require __DIR__ . '/bootstrap.php';
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;
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal('5.55');
$transaction = new Transaction();
$transaction->setAmount($amount)->setDescription("Purchase from Leisurely Diversion")->setInvoiceNumber(uniqid());
$redirectURLs = new RedirectUrls();
$redirectURLs->setReturnUrl("http://localhost/leisurelydiversion/confirmation.php")->setCancelUrl("http://localhost/leisurelydiversion/confirmation.php");
$payment = new Payment();
$payment->setIntent("sale")->setPayer($payer)->setTransactions(array($transaction))->setRedirectUrls($redirectURLs);
try {
$payment->create($apiContext);
} catch(Exception $e) {
echo "<h2> Error Sending Payment! $e</h2>";
}
$url = $payment->getApprovalLink();
echo $url;
?>
You have to add an item list to the payment:
http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/OrderCreateUsingPayPal.html
You can also change the action by appending &useraction=commit to the approval url:
Does PayPal Rest API have the classic useraction equivalent
Hope this will help
$item = new Item();
$item->setSku('Product Id');
$item->setName('Product Name');
$item->setPrice('5.55');
$item->setCurrency('USD');
$item->setQuantity(1);
$itemList = new ItemList();
$itemList->setItems(array($item));
$transaction = new Transaction();
$transaction->setItemList($itemList);
$transaction->setAmount($amount);
I'm workin on PayPal Payments in PHP. Everything was fine until i got this error:
Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.
It's thrown when I try to create method for my payment: $payment->create($api);
<?php
use PayPal\Api\Payer;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Exception\PayPalConnectionException;
require '../src/start.php';
$payer = new Payer();
$details = new Details();
$amount = new Amount();
$transaction = new Transaction();
$payment = new Payment();
$redirectUrls = new RedirectUrls();
// Payer
$payer->setPaymentMethod('paypal');
// Details
$details->setShipping('2.00')
->setTax('0.00')
->setSubtotal('20.00');
// Amount
$amount->setCurrency('GBP')
->setTotal('22.00')
->setDetails($details);
// Transaction
$transaction->setAmount($amount)
->setDescription('Membership');
// Payment
$payment->setIntent('sale')
->setPayer($payer)
->setTransactions($transaction);
// Redirect urls
$redirectUrls->setReturnUrl($myReturnUrl)
->setCancelUrl($myCancelUrl);
$payment->setRedirectUrls($redirectUrls);
try {
$payment->create($api);
} catch (Exception $e) {
echo $e->getMessage();
}
Why this is happening? How can I fix that? How eventually I can get more detailed exception message?
// Amount
$amount->setCurrency('GBP')
->setTotal('22.00')
->setDetails($details);
And make sure also your paypal business account whats your primary currency in my case it worked fine with changing the value from 'GBP' to 'USA'
// Amount
$amount->setCurrency('USA')
->setTotal('22.00')
->setDetails($details);
$api = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential('Your Client ID',' Secret')
);
Make sure you have provided that right values