Unable to RefunSale sale in PayPal using PHP SDk (undefined getApiContext) - php

I am trying to refund sale in PayPal using PHP SDK. However, it is showing error as
Call to undefined function App\Http\Payment\PayPal\getApiContext() I am trting to refund using PHP SDk of paypal.
use PayPal\Api\Amount;
use PayPal\Api\RefundRequest;
use PayPal\Api\Sale;
$amt = new Amount();
$amt->setTotal($amount)
->setCurrency('USD');
// ### Refund object
$refundRequest = new RefundRequest();
$refundRequest->setAmount($amt);
// ###Sale
$sale = new Sale();
$sale->setId($sale_id);
try {
// Create a new apiContext object so we send a new
// PayPal-Request-Id (idempotency) header for this resource
$apiContext = getApiContext(config('paypal.id'), config('paypal.secret'));
// Refund the sale
// (See bootstrap.php for more on `ApiContext`)
$refundedSale = $sale->refundSale($refundRequest, $apiContext);
} catch (\Exception $ex) {
echo $ex;
exit(1);
}
return $refundedSale;
update:
I am referring https://github.com/paypal/PayPal-PHP-SDK/blob/master/sample/sale/RefundSale.php

Related

PayPal Billing REST Api Php issue

I have an issue with Paypal REST Api billing (recurring payments).
I did exactly as in paypal documentation but when I click payment button it opens blank page (no errors in the error log).
Here is what I do:
Front End Button
<form action="WEBSITE/subscribe/paypal/paypal_agreement.php" method="POST">
<button type="submit" style="margin-top:10px;border: 0; background: transparent">
<img src="WEBSITE/wp-content/uploads/2017/05/paypal.png" style = "width:170px;" alt="submit" />
</button>
</form>
paypal_agreement.php (copy/paste from paypal docs)
<?php
require_once("../../paypal/vendor/autoload.php");
$createdPlan = require 'paypal_createplan.php';
use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\Plan;
use PayPal\Api\ShippingAddress;
$ppstartdate = date('c', time()+210);
$agreement = new Agreement();
$agreement->setName('Title Agreement')
->setDescription('Description Agreement')
->setStartDate($ppstartdate);
// Add Plan ID
// Please note that the plan Id should be only set in this case.
$plan = new Plan();
$plan->setId($createdPlan->getId());
$agreement->setPlan($plan);
// Add Payer
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$agreement->setPayer($payer);
// ### Create Agreement
try {
// Please note that as the agreement has not yet activated, we wont be receiving the ID just yet.
$agreement = $agreement->create($apiContext);
// ### Get redirect url
// The API response provides the url that you must redirect
// the buyer to. Retrieve the url from the $agreement->getApprovalLink()
// method
$approvalUrl = $agreement->getApprovalLink();
header("Location: ".$approvalUrl);
} catch (Exception $ex) {
exit(1);
}
return $agreement;
?>
paypal_createplan.php (copy/paste from paypal docs)
<?php
require_once("../../paypal/vendor/autoload.php");
use PayPal\Api\Currency;
use PayPal\Api\MerchantPreferences;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\Plan;
// Create a new instance of Plan object
$plan = new Plan();
// # Basic Information
// Fill up the basic information that is required for the plan
$plan->setName('Title Plan')
->setDescription('Description Subscription Plan')
->setType('fixed');
// # Payment definitions for this billing plan.
$paymentDefinition = new PaymentDefinition();
// The possible values for such setters are mentioned in the setter method documentation.
// Just open the class file. e.g. lib/PayPal/Api/PaymentDefinition.php and look for setFrequency method.
// You should be able to see the acceptable values in the comments.
$paymentDefinition->setName('Regular Payments')
->setType('REGULAR')
->setFrequency('Month')
->setFrequencyInterval("1")
->setCycles("6")
->setAmount(new Currency(array('value' => 94.99, 'currency' => 'USD')));
$merchantPreferences = new MerchantPreferences();
$baseUrl = "https://websitelink.com";
$merchantPreferences->setReturnUrl("$baseUrl/subscribe/paypal/execute.php?success=true")
->setCancelUrl("$baseUrl/subscribe/paypal/execute.php?success=false")
->setAutoBillAmount("yes")
->setInitialFailAmountAction("CONTINUE")
->setMaxFailAttempts("0")
->setSetupFee(new Currency(array('value' => 0, 'currency' => 'USD')));
// ### Create Plan
try {
$output = $plan->create($apiContext);
} catch (Exception $ex) {
exit(1);
}
return $output;
?>
execute.php (copy/paste from paypal docs)
<?php
// #Execute Agreement
// This is the second part of CreateAgreement Sample.
// Use this call to execute an agreement after the buyer approves it
require_once("../../paypal/vendor/autoload.php");
// ## Approval Status
// Determine if the user accepted or denied the request
if (isset($_GET['success']) && $_GET['success'] == 'true') {
$token = $_GET['token'];
$agreement = new \PayPal\Api\Agreement();
try {
// ## Execute Agreement
// Execute the agreement by passing in the token
$agreement->execute($token, $apiContext);
} catch (Exception $ex) {
exit(1);
}
// ## Get Agreement
// Make a get call to retrieve the executed agreement details
try {
$agreement = \PayPal\Api\Agreement::get($agreement->getId(), $apiContext);
//done
header('Location: https://websitelink.com/subscribe/subscribe.php');
} catch (Exception $ex) {
exit(1);
}
} else {
$_SESSION['pmsg'] = $_SESSION['pmsg'].'<h2>Subscription Failed</h2>';
}
But I couldn't find anything about authentication OAuth2 (as for example with express checkout), nothing in documentation. Maybe it doesn't work because of that?
Variable $apiContext should contain paypal app authentication & setConfig
Is this: "Variable $apiContext should contain paypal app authentication & setConfig"
the solution to this issue?: I have an issue with Paypal REST Api billing (recurring payments). I did exactly as in paypal documentation but when I click payment button it opens blank page (no errors in the error log).
I am having a similiar issue. Pls confirm. And how do we get the paypal app authentication & setConfig?

Can I use $transaction->setReferenceId() with Paypal PHP REST API?

I'm trying to include a identifier in the transaction so I know which transaction is when it returns from Paypal. I've tried to use the reference_id as it's like the better option (because is a temporal identifier that I assign to the transaction).
The problem is that when I set it to the transaction, Paypal refuse to accept the json, it returns:
{
"name":"MALFORMED_REQUEST",
"message":"Incoming JSON request does not map to API request",
"information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST",
"debug_id":"6835f984b6735"
}
More or less I use the example code:
// Create new payer and method
$payer = new Payer();
$payer->setPaymentMethod("paypal");
// Set redirect urls
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl($urlRetorno)
->setCancelUrl($urlCancelar);
// Set payment amount
$amount = new Amount();
$amount->setCurrency($moneda)
->setTotal($total);
// Set transaction object
$transaction = new Transaction();
$transaction->setAmount($amount)
->setDescription($descripcion);
// If I comment this line it runs ok.
$transaction->setReferenceId($referenceId);
// Create the full payment object
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
echo $payment->toJSON();
// Create payment with valid API context
try {
$payment->create($apiContext);
// Get PayPal redirect URL and redirect user
$approvalUrl = $payment->getApprovalLink();
// Finalmente le redirigimos a PayPal para que apruebe el pago
//redirige($approvalUrl, 'Intentando redirigir a PayPal.');
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode();
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
And this is the result (calling toJSON()):
{
"intent":"sale",
"payer":{
"payment_method":"paypal"
},
"redirect_urls":{
"return_url":"https://example.com/return.php",
"cancel_url":"https://example.com/cancel.php"
},
"transactions":[
{
"amount":{
"currency":"MXN",
"total":"1515"
},
"description":"Suscripci\u00f3n c\u00f3digo PP-19119",
"reference_id":"304171757041"
}
]
}
I have found the reference_id in the API documentation so I supposed I could use it.
After posting on the GitHub repositories about it here is the conclusion.
reference_id is a read only value and you should use invoice_number to track it.
You can read about it in https://github.com/paypal/PayPal-PHP-SDK/issues/828 and currently tracked in https://github.com/paypal/PayPal-REST-API-issues/issues/69.

PHP Papal SDK - list of transactions

Just trying get list of all incoming transactions to our PayPal account with PayPal PHP SDK, but result from following example return me still just one record (and we have thousands of payments in our live environment). According PP documentation everything looks ok... Is there any different service for incoming payments?
<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
require __DIR__ . '/vendor/autoload.php';
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'...SUssUIJQ6zEOdQBI7nUG...', // ClientID
'...YHw3aCroq0mbqSdzimPq...' //Secret hash
)
);
$apiContext->setConfig(array('mode' => 'live'));
$payment = new \PayPal\Api\Payment();
try {
$params = array();
$payments = $payment->all($params, $apiContext);
echo $payments;
} catch (Exception $ex) {
print_r($ex);
}

Laravel PayPal payment return 400

I am using PayPal paypal/rest-api-sdk-php for payment gateway for my laravel application.
But when the link is click for confirmation, I get Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.
Following is my method of implementation in Laravel 5.1 and AngularJS:
angular.module('MyApp')
.factory('Account', function($http){
return {
buyNow: function(pid){
console.log(pid)
return $http.put('/api/buynow',pid);
}
}
});
public function buyNowAPI(Request $request)
{
$pid = $request->input('pid');
$product = Product::find($pid);
$baseUrl = url().'/#/app/product?orderId=$pid';
$payment = $this->makePaymentUsingPayPal($product->price,'MYR',$product->title,"$baseUrl&success=true", "$baseUrl&success=false");
dd($payment->getLinks());
return response()->json($pid);
}
public function makePaymentUsingPayPal($total, $currency, $paymentDesc, $returnUrl, $cancelUrl)
{
$payer = new Payer();
$payer->setPaymentMethod("paypal");
// Specify the payment amount.
$amount = new Amount();
$amount->setCurrency($currency);
$amount->setTotal($total);
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription($paymentDesc);
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl($returnUrl);
$redirectUrls->setCancelUrl($cancelUrl);
$payment = new Payment();
$payment->setRedirectUrls($redirectUrls);
$payment->setIntent("sale");
$payment->setPayer($payer);
$payment->setTransactions(array($transaction));
$payment->create($this->getApiContext());
return $payment;
}
The laravel code implementation is based on example that available in git for paypal/rest-api-sdk-php based example called The Pizza App rest-api-sample-app .
Thanks!!
You need to follow the instructions mentioned here:
https://github.com/paypal/PayPal-PHP-SDK/wiki/exception-%27PayPal%5CException%5CPayPalConnectionException%27-with-message-%27Got-Http-response-code-400-when-accessing
try {
$payment->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
die($ex);
} catch (Exception $ex) {
die($ex);
}

PayPal PHP SDK - cancel invoice function does nothing

I am using the PayPal SDK for PHP, I am trying to cancel an invoice, the result returned is "true", there isn't exception returned, but the invoice is not canceled. Please could you tell me if there is an error in my code?
$Invoice = new Invoice();
try {
$invoice = $Invoice->get($id_invoice, $apiContext);
$notify = new CancelNotification();
$notify->setSubject("Past due")
->setNote("Canceling invoice")
->setSendToMerchant(true)
->setSendToPayer(true);
$result = $Invoice->cancel($notify, $apiContext);
} catch (Exception $ex) {
$result = self::getException($ex);
}
return $result;
First get an invoice object like this:
$invoice = Invoice::get($invoiceId, $apiContext);
Then, you could do the following to cancel it.
// ### Cancel Notification Object
// This would send a notification to both merchant as well
// the payer about the cancellation. The information of
// merchant and payer is retrieved from the invoice details
$notify = new CancelNotification();
$notify
->setSubject("Past due")
->setNote("Canceling invoice")
->setSendToMerchant(true)
->setSendToPayer(true);
// ### Cancel Invoice
// Cancel invoice object by calling the
// static `cancel` method
// on the Invoice class by passing a valid
// notification object
// (See bootstrap.php for more on `ApiContext`)
$cancelStatus = $invoice->cancel($notify, $apiContext);
Also, to test the code, you could always run the samples, and test it out yourself, by just clicking a button.
I ran the sample to cancel an invoice, and then use the similar information provided back on get response of invoice:
"metadata": {
"created_date": "2015-02-04 13:12:33 PST",
"first_sent_date": "2015-02-04 13:12:34 PST",
"last_sent_date": "2015-02-04 13:12:34 PST",
"payer_view_url": "https://www.sandbox.paypal.com/cgi_bin/webscr?cmd=_pay-inv&viewtype=altview&id=INV2-6S46-MLLN-3FEA-VLZE"
}
Opening the URL showed me that the invoice was cancelled as shown below:

Categories