Paypal PHP REST API - No Payment Value Shown At Checkout - php

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);

Related

Sandbox PayPal approval link leads to dashboard instead of payment after logging in

I am using PayPal REST API in sandbox mode to test payments.
I create the approval link, then redirect user to said link.
PayPal then asks for credentials which I insert as a sandbox test buyer. But after logging in, PayPal does not redirect me to complete the approval of payment, and instead straight to My Account summary from where I cannot approve the payment. However if the user was already logged in, the payment approval proceeds as expected.
Is it the problem with how was the link created or is it a bug?
This is the code used to create the link
<?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;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;
class PaypalFactory
{
private const CLIENT_ID = 'yyy';
private const CLIENT_SECRET = 'xxx';
private function __construct()
{
}
public static final function getContext()
{
return new ApiContext(
new OAuthTokenCredential(
self::CLIENT_ID,
self::CLIENT_SECRET
)
);
}
public static final function createPaymentLink(
int $orderId,
string $currency,
float $totalPrice,
float $deliveryPrice,
string $returnUrl,
string $cancelUrl): string
{
$payer = new Payer();
$payer
->setPaymentMethod("paypal");
$details = new Details();
$details
->setShipping($deliveryPrice)
->setSubtotal($totalPrice);
$item = new Item();
$item
->setName('products and shipping')
->setCurrency($currency)
->setPrice($totalPrice)
->setQuantity(1);
$itemList = new ItemList();
$itemList->setItems(array($item));
$amount = new Amount();
$amount
->setCurrency($currency)
->setTotal($totalPrice + $deliveryPrice)
->setDetails($details);
$transaction = new Transaction();
$transaction
->setItemList($itemList)
->setAmount($amount)
->setDescription("Products from ")
->setInvoiceNumber($orderId);
$redirectUrls = new RedirectUrls();
$redirectUrls
->setReturnUrl($returnUrl)
->setCancelUrl($cancelUrl);
$payment = new Payment();
$payment
->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
try {
$payment->create(PaypalFactory::getContext());
} catch (Exception $ex) {
print $ex;
}
return $payment->getApprovalLink();
}
}
Purging all browser cookies for paypal domains is good advice, and may help. The problem you're experiencing is probably a general sandbox issue (that won't happen in live mode), and not a problem with your code.
However, seeing your code/solution, I do have suggestions for trying some newer/better things:
Instead of the old PayPal-PHP-SDK for v1/payments, use the new Checkout-PHP-SDK for v2/orders
Instead of redirecting the buyer to the approval URL, give the approval token to the Javascript code of Smart Payment Buttons, which will display an in-context window that keeps your site loaded in the background. Here's a demo pattern

Getting "undefined variable" warning and "class not found" error when trying to use Paypal PHP SDK

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.

Multiple products in newest version of PayPal API

What is the correct way of passing in multiple products into a php paypal payment?
Currect working testcode for single product:
$api = new ApiContext(
new OAuthTokenCredential(
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
)
);
$api->setConfig([
'mode' => 'sandbox',
'log.LogEnabled' => false,
'log.FileName' => '',
'log.LogLevel' => 'FINE',
'validation.level' => 'log'
]);
$payer = new Payer();
$details = new Details();
$amount = new Amount();
$transaction = new Transaction();
$payment = new Payment();
$redirecturls = new RedirectUrls();
$payer->setPaymentMethod('paypal');
$details->setShipping('2.00')
->setTax('0.00')
->setSubtotal('20.00');
$amount->setCurrency('EUR')
->setTotal('22.00')
->setDetails($details);
$transaction->setAmount($amount)
->setDescription('Test');
$payment->setIntent('sale')
->setPayer($payer)
->setTransactions([$transaction]);
$redirecturls->setReturnUrl('RETURN URL')
->setCancelUrl('CANCEL URL');
$payment->setRedirectUrls($redirecturls);
try {
$payment->create($api);
} catch (PPConnectionException $e) {
header('Location: ERROR URL');
}
header('Location: '.$payment->getApprovalLink());
Keep in mind, this is not how I will implement it, this is just proof of concept!
I made a little CodeIgniter library with which I can easily call a payment!
If anyone is interested, don't hesitate to message me!
$this->load->library('Paypal');
$this->load->model('Config_model');
$ClientID = $this->Config_model->get('paypal.ClientID');
$Secret = $this->Config_model->get('paypal.Secret');
$defaultCurrency = $this->Config_model->get('transactions.currency');
$this->paypal->setSandbox(true);
$this->paypal->setMerchant($ClientID, $Secret);
$this->paypal->setDefaultCurrency($defaultCurrency);
$this->paypal->addItem('test', 5.3, 2);
$this->paypal->addItem('test2', 3.3, 5);
$this->paypal->setShipping(2);
$this->paypal->setTax(3);
$this->paypal->setDescription("Betalingetje");
$this->paypal->setCancelUrl('CANCEL URL HERE');
$this->paypal->setReturnUrl('RETURN URL HERE');
$this->paypal->execute();
PS: It works in conjunction with another tiny 'library' which is autoloaded. This library only includes the composer autoload.php like this:
class MyComposer
{
function __construct()
{
include("application/composer/vendor/autoload.php");
}
}
You can find the source code here: http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html
There are so many more samples that comes packaged with the SDK itself. You can follow the instructions provided here at https://github.com/paypal/PayPal-PHP-SDK/wiki/Samples to execute samples in your local machine.
Let me know if I could be of any more help.
Here is the sample code snippet:
<?php
// # Create Payment using PayPal as payment method
// This sample code demonstrates how you can process a
// PayPal Account based Payment.
// API used: /v1/payments/payment
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
// A resource representing a Payer that funds a payment
// For paypal account payments, set payment method
// to 'paypal'.
$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(7.5);
$item2 = new Item();
$item2->setName('Granola bars')
->setCurrency('USD')
->setQuantity(5)
->setPrice(2);
$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));
// ### Additional payment details
// Use this optional field to set additional
// payment information such as tax, shipping
// charges etc.
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(17.50);
// ### Amount
// Lets you specify a payment amount.
// You can also specify additional details
// such as shipping, tax.
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(20)
->setDetails($details);
// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it.
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
// ### Redirect urls
// Set the urls that the buyer must be redirected to after
// payment approval/ cancellation.
$baseUrl = getBaseUrl();
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
// ### Payment
// A Payment Resource; create one using
// the above types and intent set to 'sale'
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
// For Sample Purposes Only.
$request = clone $payment;
// ### Create Payment
// Create a payment by calling the 'create' method
// passing it a valid apiContext.
// (See bootstrap.php for more on `ApiContext`)
// The return object contains the state and the
// url to which the buyer must be redirected to
// for payment approval
try {
$payment->create($apiContext);
} catch (Exception $ex) {
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);
exit(1);
}
// ### 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 Using PayPal. Please visit the URL to Approve.", "Payment", "<a href='$approvalUrl' >$approvalUrl</a>", $request, $payment);
return $payment;

PayPal Payments - HTTP Response code 400

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

How do I integrate paypal adaptive payment with cake php 1.3 version?

I have a application in Cakephp 1.3 where I need to integrate latest paypal adaptive payment system. I get code sample from paypal web site for adaptive payment. I get code here https://www.x.com/developers/paypal/products/adaptive-payments after login. It provide me a rest API SDK where I get code for pay with credit card.
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Address;
use PayPal\Api\Amount;
use PayPal\Api\CreditCard;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\FundingInstrument;
use PayPal\Api\Transaction;
$addr = new Address();
$addr->setLine1("3909 Witmer Road");
$addr->setLine2("Niagara Falls");
$addr->setCity("Niagara Falls");
$addr->setState("NY");
$addr->setPostal_code("14305");
$addr->setCountry_code("US");
$addr->setPhone("716-298-1822");
$card = new CreditCard();
$card->setType("visa");
$card->setNumber("4417119669820331");
$card->setExpire_month("11");
$card->setExpire_year("2019");
$card->setCvv2("012");
$card->setFirst_name("Joe");
$card->setLast_name("Shopper");
$card->setBilling_address($addr);
$fi = new FundingInstrument();
$fi->setCredit_card($card);
$payer = new Payer();
$payer->setPayment_method("credit_card");
$payer->setFunding_instruments(array($fi));
$amount = new Amount();
$amount->setCurrency("USD");
$amount->setTotal("1.00");
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription("This is the payment description.");
$payment = new Payment();
$payment->setIntent("sale");
$payment->setPayer($payer);
$payment->setTransactions(array($transaction));
try {
$payment->create($apiContext);
}
catch (\PPConnectionException $ex)
{ echo "Exception: " . $ex->getMessage() . PHP_EOL; var_dump($ex->getData());
exit(1); }
Is there any other easy way do implement adaptive payment with paypal in Cakephp?
Is the code sample you provided from the REST SDK? You shouldn't be using that if you're trying to use Adaptive Payments. Adaptive Payments doesn't have a direct credit card payment option and that is what the code sample you provided is trying to do.
Here is a direct link to the PHP SDK for Adaptive Payments:
https://github.com/paypal/adaptivepayments-sdk-php

Categories