Surfe.be - passive income

Easy way to integrate paypal payment gateway in laravel

Integrate PayPal payment gateway

If you are operative in the e-commerce circuit, then you must have known the importance of online transaction. As it is the most viable and fastest way to settle payments anywhere in the world. And because of evolving internet technology, today anyone can easily buy or sell products and can settle payments with online transaction all around the world.

But online transaction brings high risks of serious security threats also. Therefore robust security mechanism for online payments is required to avoid potential malicious attempts. That is where the importance of Laravel Paypal payment gateways comes into play. As these gateways helps businesses to focus and capitalize on the benefits of online transactions, while keeping their customers and systems secured from the external threats.

PayPal sign up

Visit Developer.paypal.com to create your business account, so that you can buy/sell products easily over the internet and transfer funds to your account. Next create a PayPal developer mode and create a sandbox account to get important credentials like client_key and secret_key, to test PayPal integration with your PayPal app.

Set up PayPal

We must follow those below step to complete our PayPal integration part in our Laravel application . These steps are

  • 1.Install Required Packages
  • 2.Configuration of paypal.php file
  • 3.Create Required Route
  • 4.Create Required Controller
  • 5.Finally Create View File

Look here we use packages to integrate PayPal payment gateway in our Laravel application .

Install Required Packages

We need following 2 packages for integrate paypal payment in our laravel application. add following two package in your composer.json file.

"guzzlehttp/guzzle": "~5.2",
"paypal/rest-api-sdk-php": "*",

then go to your project root directory and run following command

paypal command
php artisan vendore:publlish

after run this command, then automatically created paypal.php file in your config directory with following path config/paypal.php . Then now we have to configure paypal.php file . Paste your client_key and secret_key, to test PayPal integration with your PayPal app.

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
 
/**
* SDK configuration 
*/
'settings' => array(
/**
* Available option 'sandbox' or 'live'
*/
'mode' => 'sandbox',
/**
* Specify the max request time in seconds
*/
'http.ConnectionTimeOut' => 1000,
/**
* 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'
),
);

Create Required Route

In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route.

Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'PaypalController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'PaypalController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'PaypalController@getPaymentStatus',));

Create Required Controller

php artisan make:controller PaypalController

Now copy this following code and paste it into your PaypalController.php file.

namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;
/** All Paypal Details class **/
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 PaypalController extends HomeController
{
    private $_api_context;
  
    public function __construct()
    {
        parent::__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']);
    }
   
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }
   
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');
        $item_1 = new Item();
        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/
        $item_list = new ItemList();
        $item_list->setItems(array($item_1));
        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));
        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');
        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));
        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
               
            }
        }
        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)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }
        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }
    public function getPaymentStatus()
    {    
        $payment_id = Session::get('paypal_payment_id');
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $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::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');
        return Redirect::route('addmoney.paywithpaypal');
    }
  }

Create View File

Now we are in final step . Just we have to create our view file. So go to this following directory and create a blade file whose name will be paywithpaypal.blade.php. 

 <div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                @if ($message = Session::get('success'))
                <div class="custom-alerts alert alert-success fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('success');?>
                @endif
                @if ($message = Session::get('error'))
                <div class="custom-alerts alert alert-danger fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('error');?>
                @endif
                <div class="panel-heading">Paywith Paypal</div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('addmoney.paypal') !!}" >
                        {{ csrf_field() }}
                        <div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
                            <label for="amount" class="col-md-4 control-label">Amount</label>
                            <div class="col-md-6">
                                <input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus>
                                @if ($errors->has('amount'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('amount') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Paywith Paypal
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

That’s it. Hope this tutorial will help you. If you like this tutorial please leave a comment and don’t forget to share . 

Leave a comments

LET'S SOCIALITE

Recent Tweets

RECOMMENDED POST