Paypal/Laravel can't make a Live payment - php

I've followed this tutorial to implement payment using Paypal services on my website: https://www.youtube.com/watch?v=q5Xb5r4MUB8
But when i want to flip from SandBox mode to Live mode (which is the real payment) all my transactions goes to the SandBox history (you can check it in your Paypal account).
Here is the code of the function "store()" that do the payment:
public function store(Request $request)
{
// ### CreditCard
$card = Paypalpayment::creditCard();
$card->setType("visa")
->setNumber("Some_Numbers")
->setExpireMonth("05")
->setExpireYear("2017")
->setCvv2("smth")
->setFirstName("MyName")
->setLastName("MyLastName");
$fi = Paypalpayment::fundingInstrument();
$fi->setCreditCard($card);
$payer = Paypalpayment::payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
//Payment Amount
$amount = Paypalpayment::amount();
$amount->setCurrency("EUR")
->setTotal("3");
$transaction = Paypalpayment::transaction();
$transaction->setAmount($amount)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
// ### Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
$payment = Paypalpayment::payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
try {
$payment->create($this->_apiContext);
} catch (\PPConnectionException $ex) {
return "Exception: " . $ex->getMessage() . PHP_EOL;
exit(1);
}
dd($payment);
}

Look what $this->_apiContext contains. There is a mode that needs to be set to live to make it work.
If not found, you can create apiContext object as shown here:
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'Live ClientId', // ClientID
'Live Client Secret' // ClientSecret
)
);
$apiContext->setConfig(
array(
'mode' => 'live',
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
)
);
and use $apiContext instead when you call $payment->create();

Related

PayPal payment gateway integration with live credentials in REST Api issue

I am using PayPal rest api payment gateway method for payment, when I was using demo details this is working fine but when I used the live details it is returning error, Like
'We aren't able to process your payment using your PayPal account at this time. Please go back to the merchant and try using a different payment method.'
some time I also got the message of invalid details,
{"error":"invalid_client","error_description":"Client Authentication failed"}
I am using 'REST API SDK for PHP' got from the GitHub.
I have updated all the necessary information in the developer PayPal for live mode, but still getting issue.
This is my code what I tried
require __DIR__ . '/vendor/autoload.php';
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
// ClientID
// ClientSecret
)
);
$apiContext->setConfig(
array(
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE',
'mode' => 'live',
)
);
$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod('paypal');
$amount = new \PayPal\Api\Amount();
$amount->setTotal($_SESSION['partner_payment'][1]);
$amount->setCurrency('USD');
$transaction = new \PayPal\Api\Transaction();
$transaction->setAmount($amount);
$redirectUrls = new \PayPal\Api\RedirectUrls();
$redirectUrls->setReturnUrl("https://mydomain/paypal/success.php")
->setCancelUrl("https://mydomain/paypal/cancel.php");
$payment = new \PayPal\Api\Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setTransactions(array($transaction))
->setRedirectUrls($redirectUrls);
try {
$payment->create($apiContext);
//echo $payment;
//echo "\n\nRedirect user to approval_url: " . $payment-
>getApprovalLink() . "\n";
header("Location:".$payment->getApprovalLink());
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getData();
}
----Output:----
We aren't able to process your payment using your PayPal account at this time. Please go back to the merchant and try using a different payment method.

Why paypal sandbox account amount does not updating?

My code is successfully processing payments to paypal and then return to success page, buy business account amount does not updating.
I am trying paypal sdk in laravel and below is my script which I am using it, but on front side it is successfully going to paypal page where I login using buyer account then pay and then paypal return to success page. But in seller account the amount does not showing and nor deducting from buyer account.
public function createpayment(){
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'Ac.................asd', // ClientID
'Ac.................sdf' // ClientSecret
)
);
$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());
/* $baseUrl = getBaseUrl(); */
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl(route('success'))
->setCancelUrl(route('cancel'));
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
/* $payment->create($apiContext);
return redirect($payment->getApprovalLink()); */
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();
echo $payment, $approvalUrl;
}
public function success(){
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'Ac.................asd', // ClientID
'Ac.................sdf' // ClientSecret // ClientSecret
)
);
return request();
}
I want this code to be transfer money from buyer to seller account and then return success page with response. Can someone kindly guide me about I would like to appreciate.
On the success page you need to execute the payment in order to actually finish the transaction.
https://github.com/paypal/PayPal-PHP-SDK/blob/master/sample/payments/ExecutePayment.php

paypal sandbox is not executing payment

It's for couple of days, I'm using php sdk. It was working before, but now they are not executing my subscription and charge payment. I only get PAYMENT.SALE.PENDING event whenever a payment has made.
Please help, this is driving me crazy.
I get the payment status "approved", but I'm not getting the 'PAYMENT.SALE.COMPLETED' webhook, I don't know what's wrong.
Here is my code:
create:
public function doPayPalCharge($returnUrl, $cancelUrl)
{
$apiContext = $this->apiContext;
$money = $this->getAmount();
$customData = $this->getMetadata();
// Create new payer and method
$payer = new Payer();
$payer->setPaymentMethod("paypal");
// Set redirect urls
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl($returnUrl)
->setCancelUrl($cancelUrl);
// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal($money);
// Set transaction object
$transaction = new Transaction();
$transaction->setAmount($amount)
//can not use json_encode here, because can not decode data from web hook
->setCustom(base64_encode(serialize($customData->all)))
->setDescription("Payment description");
// Create the full payment object
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$request = clone $payment;
// Create payment with valid API context
try
{
$payment->create($apiContext);
$token = $this->getPayPalTokenFromUrl($payment->getApprovalLink());
} catch (PayPalConnectionException $e)
{
self::payPalLog($e, '[PayPalConnectionException]', (array)$request);
} catch (\Exception $e)
{
self::payPalLog($e, '[Create Payment Failed]', (array)$request);
}
return isset($token) ? $token : '';
}
execute:
public function confirmPayPalCharge($payment_id, $payer_id)
{
$apiContext = $this->apiContext;
// Get payment object by passing paymentId
$payment = Payment::get($payment_id, $apiContext);
// Execute payment with payer id
$execution = new PaymentExecution();
$execution->setPayerId($payer_id);
try
{
// Execute payment
$payment = $payment->execute($execution, $apiContext);
} catch (PayPalConnectionException $e)
{
self::payPalLog($e, '[PayPalConnectionException]');
} catch (\Exception $e)
{
self::payPalLog($e);
}
return isset($payment) ? $payment : null;
}

Has anyone implemented the PayPal PHP SDK with an openssl certificate?

I read the documentation about security and concerns, but I can see any example with how use a .pem file to autenticate to PayPal API V2, the classic version has this feature. I want to send payments but using this method.
Has anyone share some code to see?
this is my code
require __DIR__ . '/PayPal-PHP-SDK/autoload.php';
class PaymentPayPal
{
public static function SendPayment($member)
{
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'ClientID','ClientSecret'
)
);
$apiContext->setConfig(
array(
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
)
);
$payouts = new \PayPal\Api\Payout();
$senderBatchHeader = new \PayPal\Api\PayoutSenderBatchHeader();
$senderBatchHeader->setSenderBatchId(uniqid())
->setEmailSubject("You have a payment");
$payouts->setSenderBatchHeader($senderBatchHeader);
$senderItem1 = new \PayPal\Api\PayoutItem();
$senderItem1->setRecipientType('Email')
->setNote('Thanks you.')
->setReceiver($member['email'])
->setSenderItemId(uniqid())
->setAmount(new \PayPal\Api\Currency('{
"value":"'.$member['amount'].'",
"currency":"USD"
}'));
$payouts->addItem($senderItem1);
try {
$output = $payouts->create(null, $apiContext);
var_dump($output);
$status = \PayPal\Api\Payout::get($output->batch_header->payout_batch_id, $apiContext);
var_dump($status);
} catch (Exception $ex) {
}
}
}

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;

Categories