PayPal has released an official SDK (https://github.com/paypal/rest-api-sdk-php) to simplify our work. Here we will learn how to integrate into Laravel 5.x.
Requirement: We will be using laracast flash notification system https://github.com/laracasts/flash.
Edit File composer.json and add/update:
"require": {
"laracasts/flash": "^2.0",
"paypal/rest-api-sdk-php": "*"
}
Now, update the composer with below command:-
composer update
You can now use the PayPal package and laracast flash notification in the project.
Now, include the service provider within config/app.php
'providers' => [
Laracasts\Flash\FlashServiceProvider::class,
];
And, for convenience, add a facade alias to this same file at the bottom:
'aliases' => [
'Flash' => Laracasts\Flash\Flash:class,
];
Now, add below code in your master view file on top, where you feel error message will be displayed.
@include('flash::message')
create PayPal config file in config directory with name PayPal, "config/paypal.php"
<?php
return array(
// set your paypal credential
// Below credentials are different for sandbox mode and live mode.
'client_id' => 'Your Paypal Client ID will be here',
'secret' => 'Your Paypal secret key will be here',
/**
* SDK configuration
*/
'settings' => array(
/**
* Available option 'sandbox' or 'live'
* Remember sandbox id and secret will be different than live
*/
'mode' => 'sandbox',
/**
* Specify the max request time in seconds
*/
'http.ConnectionTimeOut' => 30,
/**
* Whether want to log to a file
*/
'log.LogEnabled' => true,
/**
* Specify the file that want to write on
*/
'log.FileName' => storage_path() . '/logs/paypal.log',
/**
* Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
*
* Logging is most verbose in the 'FINE' level and decreases as you
* proceed towards ERROR
*/
'log.LogLevel' => 'FINE'
),
);
Now, Let's Create our controller in app/Http/Controller/PaypalpayController.php
<?php
namespace App\Http\Controllers;
use Laracasts\Flash\Flash;
use Session;
use Illuminate\Http\Request;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
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\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;
class PaypalpayController extends Controller {
private $_api_context;
public function __construct() {
// setup PayPal api context
$paypal_conf = config('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
$this->_api_context->setConfig($paypal_conf['settings']);
}
public function postPayment() {
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item_1 = new Item();
$item_1->setName('Item 1') // item name
->setCurrency('USD')
->setQuantity(2)
->setPrice('15'); // unit price
// add item to list
$item_list = new ItemList();
$item_list->setItems(array($item_1));
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal(30);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Your transaction description');
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(url('payment/status'))
->setCancelUrl(url('payment/status'));
$payment = new Payment();
$payment->setIntent('Sale')
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
try {
$payment->create($this->_api_context);
} catch (\PayPal\Exception\PPConnectionException $ex) {
if (\config('app.debug')) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
exit;
} else {
Flash::error('Something went wrong, Sorry for inconvenience');
return redirect('/');
}
}
foreach($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
// add payment ID to session
Session::put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
// redirect to paypal
return redirect($redirect_url);
}
Flash::error('Unknown error occurred');
return redirect('/');
}
public function getPaymentStatus(Request $request)
{
// Get the payment ID before session clear
$payment_id = Session::get('paypal_payment_id');
// clear the session payment ID
Session::forget('paypal_payment_id');
if (empty($request->input('PayerID')) || empty($request->input('token'))) {
Flash::error('Payment Failed');
return redirect('/');
}
$payment = Payment::get($payment_id, $this->_api_context);
// PaymentExecution object includes information necessary
// to execute a PayPal account payment.
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayerId($request->input('PayerID'));
//Execute the payment
$result = $payment->execute($execution, $this->_api_context);
/*
* Get the ID with : $result->id
* Get the State with $result->state
* Get the Payer State with $result->payer->payment_method
* Get The Shipping Address and More Detail like below :- $result->payer->payer_info->shipping_address
* Get More detail about shipping address like city country name
*/
echo '<pre>';print_r($result->payer->payer_info->shipping_address);echo '</pre>';exit; // DEBUG RESULT.
if ($result->getState() == 'approved') { // payment made
Flash::success('Payment Successful');
return redirect('home');
}
Flash::error('Payment Failed');
return redirect('/');
}
}
In-Line no. 131, I am printing the error and exiting, you can remove the code and do the processing as you want afterward.
Now, add below route to our app/Http/route.php file
// You can use "get" or "post" method below for payment..
Route::get('payment', 'PaypalpayController@postPayment');
// This must be get method.
Route::get('payment/status', 'PaypalpayController@getPaymentStatus');
Now, you can need to add your own client id and secret key
For that follow below steps:-
1. Signup or Login to PayPal developer portal
2. Click on Dashboard link
3. Create your app by clicking "create an app" and following process.
4. In My apps, click on the app you created to use in your project
5. Scroll down after the Add webhook button, click on the Show link
You will get two key and id, One for "sandbox" mode and another for "live" mode. Use your choice one.
Now, understanding postPayment function first, From Line no:- 38 to 55 in controller file inside postPayment It deals with item and price and total.
If you want to add more item, you can simply create them like below:-
$item_2 = new Item();
$item_2->setName('Item 1') // item name
->setCurrency('USD')
->setQuantity(2)
->setPrice('15'); // unit price
And Do not forget to add in Item List and change total, To do so, Check code from Line no. 45 to 50.
Once $item_2 has been created.
// add item to list in line no. 46
$item_list = new ItemList();
$item_list->setItems(array($item_1, $item_2));
and then increase the Total amount
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal(30); // Increase amount here as per the new item price.
And you are done, You can check more code inside the function to understand more like description etc.,
This deals with after payment has processed, it will give you complete PayPal result, which you can use in your application to store.
I will discuss the only line no: 130 which is below:-
echo '<pre>';print_r($result);echo '</pre>';exit;
Above $result data can be used to fetch user's result, I will pull down all data that you can use and store:-
To get the Transaction ID
$result->id
To get Whether payment is approved
$result->getState();
or
$result->state;
To Check the Payer status of verified nature
$result->payer->status
To get Payer Information like- Name, Email, Address, etc.,
// Email
$result->payer->payer_info->email
// First and Last Name
$result->payer->payer_info->first_name
$result->payer->payer_info->last_name
// To get Payer ID
$result->payer->payer_info->payer_id
// To get Shipping Address details
// Recipient Name
$result->payer->payer_info->shipping_address->recipient_name
//Address line 1:-
$result->payer->payer_info->shipping_address->line1
// City, State, Postal Code, Country Code
$result->payer->payer_info->shipping_address->city
$result->payer->payer_info->shipping_address->state
$result->payer->payer_info->shipping_address->postal_code
$result->payer->payer_info->shipping_address->country_code
or
$result->payer->payer_info->country_code
// Same way Billing Address can be fetch as above, Just replace shipping_address above with billing_address
$result->payer->payer_info->billing_address->recipient_name
//Address :-
$result->payer->payer_info->billing_address->line1
$result->payer->payer_info->billing_address->line2
// City, State, Postal Code, Country Code
$result->payer->payer_info->billing_address->city
$result->payer->payer_info->billing_address->state
$result->payer->payer_info->billing_address->postal_code
$result->payer->payer_info->billing_address->country_code
Let's Get Transaction details in same nature :-
$result->transactions[0]->amount->total
$result->transactions[0]->amount->currency
// Get The Item list
$result->transactions[0]->item_list->items[0]->price
$result->transactions[0]->item_list->items[0]->name
$result->transactions[0]->item_list->items[0]->quantity
$result->transactions[0]->item_list->items[0]->currency
// Similarly if you have added more than 1 item, you can change items[1], items[2] and so on and so forth
I hope, you have understood the flow, if not. Ask below.
Cheers
Tags: laravel laravel paypal payment gateway paypal rest api paypal
I am Full Stack Programmer and Engineer. I develop web apps, mobile apps at the best price. My skills are listed at below section. I also write sometimes blog about various tech stacks. Feel free to follow me on my social media channels listed below.
From: Jaipur, Rajasthan India - Last Login: 10 months ago.
PHP programming langauge Laravel Codeigniter MySQL Twitter Bootstrap Material Design HTML5 CSS Javascript language jQuery