Paypal SDK with Laravel 5.1

Raul Mar
5 min readApr 18, 2016

--

First thing we need to do is install the official paypal-sdk in our application.

In our composer.json

"require”: {
“php”: “>=5.5.9”,
“laravel/framework”: “5.1.*”
},

We require the paypal-sdk

require”: {
“php”: “>=5.5.9”,
“laravel/framework”: “5.1.*”,
“paypal/rest-api-sdk-php”: “*”
},

Then we update our dependencies

$ php composer.phar update --no-dev

The next step will be to create a configuration file for paypal

Create a file in config/paypal.php

<?php
return array(
// set your paypal credential
'client_id' => '<YOUR-CLIENT-ID>',
'secret' => '<YOUR-SECRET-ID>',

/**
* SDK configuration
*/
'settings' => array(
/**
* Available option 'sandbox' or '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'
),
);

To get the client_id and secret credentials, you need to create an account in the developer paypal webpage.

After you create the account, you need to go to Dashboard

Create a new app

Give a name to our new app, in my case I'm going call my app Demo

Now I can see my Client ID credential

And to ge the secret credential, click in the “Show” button as shown above

And now wecan copy/paste the credentials into our config/paypal.php file.

<?php
return array(
// set your paypal credential
'client_id' => 'AetdnTzMTfNWXLkaE-BhIrQzDmVOz1f2TRvQHEFrhbuoEf55j_wJTkO66Qtb7lnkj1bek1Swzce30mta',
'secret' => 'ELPlpajTzIJ5m2qZ8W-oKrU8QO8CPUH0x-BXKRA_-DvhsZuO1Exh1m-jdGKRtGchSx8JcPrqwg82YxYm',

/**
* SDK configuration
*/
'settings' => array(
/**
* Available option 'sandbox' or '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'
),
);

We now have our paypal configuration file complete, the next step will be to create our controller where all the logic of paypal will be processed.

Create a file in app/Http/Controllers/PayPalController.php

<?php
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 CentralController 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']);
}
}

Then we need to add our routes for processing the PayPal checkout in our routes file located in: app/Http/routes.php

<?php
Route::post('payment', array(
'as' => 'payment',
'uses' => 'CentralController@postPayment',
));

// when the payment is done, this will redirect us to our page
Route::get('payment/status', array(
'as' => 'payment.status',
'uses' => 'CentralController@getPaymentStatus',
));

Now, we create our postPayment function in our CentralController

public function postPayment()
{

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

$item_1 = new Item();
$item_1->setName('Item 1')
->setCurrency('USD')
->setQuantity(2)
->setPrice('15');

$item_2 = new Item();
$item_2->setName('Item 2')
->setCurrency('USD')
->setQuantity(4)
->setPrice('7');

$item_3 = new Item();
$item_3->setName('Item 3')
->setCurrency('USD')
->setQuantity(1)
->setPrice('20');

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

$amount = new Amount();
$amount->setCurrency('USD')
->setTotal(78);

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

$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(URL::route('payment.status'))
->setCancelUrl(URL::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::away($redirect_url);
}

return Redirect::route('original.route')
->with('error', 'Unknown error occurred');
}

And then we add the function getPaymentStatus in our CentralController

public function getPaymentStatus()
{
// 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(Input::get('PayerID')) || empty(Input::get('token'))) {
return Redirect::route('original.route')
->with('error', '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(Input::get('PayerID'));

//Execute the payment
$result = $payment->execute($execution, $this->_api_context);

if ($result->getState() == 'approved') { // payment made
return Redirect::route('original.route')
->with('success', 'Payment success');
}
return Redirect::route('original.route')
->with('error', 'Payment failed');
}

And we are done, you can now test your payments and watch the transactions in you Dashboard in developer paypal, if you want to go to live mode you just need to change the Client_Id and Secret credentials to the ones that paypal gives you in live mode.

Thank you!

--

--