Integrating Paypal With LaraveI5.2
I am going to write something about how we can integrate paypal with laravel5.2 . I am sure you know paypal payment gateway and Laravel Framework , ok then lets start the work. For this article i am using products table which will show some real scenarios for e-commerce site.
Step 1 :- Download the laravel project using composer and setup laravelcollective/html service Provider, Create database and setup the database credentials in composer.json file.
Step 2 :- Create the Product model by using the command php artisan make:model Product -m Which will create the Product model and migration file for products table. Them make Following changes in Product Model.

And make changes in products migration file too…

I am not going to make CRUD of Product that’s why Let’s make ProductTableSeeder and add some data in run method and call ProductTableSeeder from DatabaseSeeder. Data Seeder file is something like this.

Now run migration file and database seed command respectively php artisan migrate and php artisan db:seed . These commands create tables and add seed data for the products table.
Step 3 :- Run command php artisan make:auth this command will generate auth scaffold I am here using it’s views only.
Step 4 :- Create ProductController using php artisan make:controller ProductController, Now make changes to the ProductController which is seems something like this.

And make Some changes to the routes file too, which is seems to be something like this.

Step 5 :- Let’s Create the views file in resources/views/products index.blade.php and order.blade.php And make the following changes in these files.


In Order file just extends the master file layouts.app and write the following above code inside the content section. Ok, This is finished the our products index page and products order page. Now Let’s begin to integrate with Paypal.
Step 6 :- Add the paypal/rest-api-sdk-php inside the composer.json file of require section like this, and run composer update command

Now, make your sandbox account for the paypal and get some credentials like client_id, secret etc. Then create the paypal.php file inside config folder and make following changes, You should use your own client_id and secret key.

Step 7 :- This is the last step, Now create the PaypalController and make changes something like this,
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
use PayPal\Api\Amount;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
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\Rest\ApiContext;
/**
* Class PaypalController
* @package App\Http\Controllers
*/
class PaypalController extends Controller
{
/**
* @var ApiContext
*/
private $_api_context;
/**
* PaypalController constructor.
*/
public function __construct()
{
$paypal_conf = Config::get('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
$this->_api_context->setConfig($paypal_conf['settings']);
}
/**
* @return mixed
*/
public function Payment(Request $request)
{
$sessionId = $request['id'];
Session::put('cartid', $sessionId);
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item->setName($request['product_id'])
->setCurrency('EUR')
->setQuantity($request['quantity'])
->setPrice($request['price']);
$items[] = $item;
$itemlist = new ItemList();
$itemlist->setItems($items);
$amount = new Amount();
$amount->setCurrency('EUR')->setTotal($request['quantity'] * $request['price']);
$transaction = new Transaction();
$transaction->setAmount($amount)->setItemList($itemlist)->setDescription('THis is Demo Transaction');
$redirect_url = new RedirectUrls();
$redirect_url->setReturnUrl(URL::route('payment.status'))->setCancelurl(URL::route('payment.status'));
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirect_url)
->setTransactions(array($transaction));
try {
$payment->create($this->_api_context);
} catch (\PayPal\Exception\PPConnectionException $ex) {
if (\Config::get('app.debug')) {
echo "Exception: " . $ex->getMessage() . PHP_EQL;
} else {
return redirect()->to(route('products.index'))->with('message', 'Some Error !');
}
}
foreach ($payment->getLinks() as $link) {
if ($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
Session::put('paypal_payment_id', $payment->getId());
if (isset($redirect_url)) {
return Redirect::away($redirect_url);
}
return redirect()->to('products')->with('error', 'Unknown Error occured');
}
/**
* @return mixed
*/
public function getPaymentStatus()
{
$payment_id = Session::get('paypal_payment_id');
Session::forget('paypal_payment_id');
if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
return redirect()->to('products.index')->with('error', 'Payment failed');
}
$payment = Payment::get($payment_id, $this->_api_context);
$execution = new PaymentExecution();
$execution->setPayerId(Input::get('PayerID'));
$result = $payment->execute($execution, $this->_api_context);
if ($result->getState() == 'approved') {
session()->flash('message','Hey, You have a message to read');
return redirect()->to(route('products.index'));
}
return redirect()->to(route('products.index'))->with('error', 'Payment failed');
}
}
Now you can check your application, you can buy the products using paypal payment gateway. Then you can see your paypal sandbox account for the transaction, Source Code for the demo you can get from here https://github.com/madhusudhan1234/laravel-paypal-ebay
Conclusion :- Nowadays Buying or selling products are easy due to the online shopping and e-commerce applications. And Using Laravel we can easily integrate different kind of payment gateway and paypal is one of the gateway which is easy to implement when using Laravel.