Getting Started

Summary: This post refers to integrating a payment gateway in laravel using PayPal. The most commonly used payment method universally accepted across the globe is now available to take payments from your laravel application, just ahead.

Integrating a paypal payment gateway with laravel application

Prerequisites

  1. Make sure laravel healthy distribution is already installed.
  2. Database is configured i.e. database credentials are added to the .env file

Install PayPal SDK

composer require paypal/rest-api-sdk-php

And Create a developer account or buyer account on Paypal by visiting here

https://developer.paypal.com/developer/accounts/

the credential obtained from here must be included in the .env file for security.

Create a new file paypal.php at the \config directory and place the underneath there.


<?php
return [
   'client_id' => env('PAYPAL_CLIENT_ID',''),
   'secret' => env('PAYPAL_SECRET',''),
   'settings' => array(
       'mode' => env('PAYPAL_MODE','sandbox'),
       'http.ConnectionTimeOut' => 30,
       'log.LogEnabled' => true,
       'log.FileName' => storage_path() . '/logs/paypal.log',
       'log.LogLevel' => 'ERROR'
   ),
];

Create a simple Pay with PayPal dialogue box which can take amount to be paid as input from the user.

Create a new controller to manage PayPal operations as

php artisan make:controller PaymentController

Initialize the constructor as

public function __construct()
   {

/** PayPal api context **/
       $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']);

}

Finally, all setup of payment with PayPal is completed and this underneath code will execute when a new payer starts its payment.

public function payWithpaypal(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('status')) /** Specify return URL **/
           ->setCancelUrl(URL::route('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('paywithpaypal');

} else {

\Session::put('error', 'Some error occur, sorry for inconvenient');
               return Redirect::route('paywithpaypal');

}

}

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::away($redirect_url);

}

\Session::put('error', 'Unknown error occurred');
       return Redirect::route('paywithpaypal');

}

This completes the Payment with PayPal in laravel application integrated.

The approved status of the payment is thus saved in session as

if ($result->getState() == 'approved') {

\Session::put('success', 'Payment success');
       return Redirect::route('/');

}

\Session::put('error', 'Payment failed');
   return Redirect::route('/');

 

Comments

Sign in to publish a comment

0 comments

Be the first to comment on this post.