Sunday, August 14, 2016

How to integrate Paypal payment API with Laravel 5.2?


Toady I will discuss about Paypal payment API to integrate with Laravel 5.2 . Paypal has an official payment SDK to work with PHP. Let's see how we can work with this SDK and make payment in Larvel.



  1. Install Paypal SDK via Composer
Open your Laravel composer.json file and add the following code require area:
"require": {

.....

"paypal/rest-api-sdk-php": "*"

},
====== You can also use this command:

composer require paypal/rest-api-sdk-php

Update your dependencies:
composer update

Now your Paypal SDK is ready to integrate in your project.

2. Configure Paypal
Add a config file for paypal: app/config/paypal.php

<?php
 return array(
 // set your paypal credential
 'client_id' => 'ASd9cKHWY_XiF-aaBKmbqI0woJgz6mzjDxkssKvrCNdSbX24oPlN0f0EaeTZ0Alw6YAeu_fjw',
 'secret' => 'EHsKdK-GLOI0PhIo2iXMqWepORHkCOVhgHkXniMY6JvlanQOSvyDeGPokZfwgKDpYMi0qRfZe',

/**
 * SDK configuration
 */
 'settings' => array(
 /**
 * Available option 'sandbox' or 'live'
 */
 'mode' => 'sandbox',

/**
 * Specify the max request time in seconds
 */
 'http.ConnectionTimeOut' => 300,

/**
 * 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'
 ),
 );

To get your client_id and secret key, login to your paypal/sandbox. Setup in app/controllers/PaypalController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
 use Config;
 use Session;
 use Redirect;

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 BaseController {

private $_api_context;

public function __construct()
 {

// setup 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']);
 }

}

3.Add two routes for processing Paypal checkout  

// Payment routes
Route::get('payment', array(
 'as' => 'payment',
 'uses' => 'PaypalController@postPayment',
 ));

// this is after make the payment, PayPal redirect back to your site
 Route::get('payment/status', array(
 'as' => 'payment.status',
 'uses' => 'PaypalController@getPaymentStatus',
 ));


Update the controller file and add this method for submitting the form or checkout shopping cart: app/controllers/PaypalController.php

public function postPayment()
 {

$payer = new Payer();
 $payer->setPaymentMethod('paypal');

$item_1 = new Item();
 $item_1->setName('Item 1') // item name
 ->setCurrency('AUD')
 ->setQuantity(1)
 ->setPrice('150'); // unit price

$item_2 = new Item();
 $item_2->setName('Item 2')
 ->setCurrency('AUD')
 ->setQuantity(2)
 ->setPrice('10');

// add item to list
 $item_list = new ItemList();
 $item_list->setItems(array($item_1, $item_2));

$amount = new Amount();
 $amount->setCurrency('AUD')
 ->setTotal(170);

$transaction = new Transaction();
 $transaction->setAmount($amount)
 ->setItemList($item_list)
 ->setDescription('description');

$redirect_urls = new RedirectUrls();
 $redirect_urls->setReturnUrl(route('payment.status')) // Specify return URL
 ->setCancelUrl(route('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::get('app.debug')) {
 echo "Exception: " . $ex->getMessage() . PHP_EOL;
 $err_data = json_decode($ex->getData(), true);
 exit;
 } else {
 die('Some error occur, sorry for inconvenient');
 }
 }

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);

}

return redirect()->route('home')
 ->with('error', 'Unknown error occurred');
 }


Add this Method for post checkout option with payment status


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'))){
 return redirect()->route('home')->with('info', 'Payment failed');
 }

$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);

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

dd($result);  // Use this data to work as you need

// return Redirect::route('home')
 // ->with('info', 'Payment success');
 }
 return Redirect::route('home')
 ->with('info', 'Payment failed');
 }

You can get this code on Github. Click here. If you have any question, please comment bellow.

No comments:

Post a Comment