Integrate paypal to your laravel project

719 0 0 0

Last Updated : 2024-04-25 10:08:35

This snippet will teach you how to integrate paypal to your laravel project

Hello every one, 


Here in this snippet code I will explain in details how to integrate paypal to your laravel project, so let's get started 


there are alot of procedures you have to do in two places 


************ PAYPAL WEBSITE ************


1- go to https://developer.paypal.com/


2- create a developer account .


3- login to the dashboard of your developer ccount .


4- from sidebar -> choose My Apps & Credentials -> when open choose REST API apps -> create app ->  provide your app name & type and business account if needed (prefered to choose foreign country that paypal available in) .


5- after completing the last step -> from sidebar -> choose Accounts -> when open you can start adding any accounts you want (this will help you to test over transactions).


6- at this stage you have done with developer account for now but the only thing you have to do is go to choose My Apps & Credentials from sidebar -> when open choose the new app you created and copy client id and secret number .


************ YOUR LARAVEL PROJECT ************


here is the second place we will work at (your laravel project)


1- we will use a package for integrating paypal to laravel called laravelPaypal (https://srmklive.github.io/laravel-paypal/docs) .


2- start installing the package to your laravel project with composer


// For Laravel 5.1 to 5.8								
composer require srmklive/paypal:~2.0

//For Laravel 6, 7, & 8
composer require srmklive/paypal:~3.0

3- then publish assets to your project


php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"

4- after publishing the assets, add the following to your .env files


#PayPal API Mode
# Values: sandbox or live (Default: live)
PAYPAL_MODE=

#PayPal Setting & API Credentials - sandbox
PAYPAL_SANDBOX_CLIENT_ID=
PAYPAL_SANDBOX_CLIENT_SECRET=

#PayPal Setting & API Credentials - live
PAYPAL_LIVE_CLIENT_ID=
PAYPAL_LIVE_CLIENT_SECRET=

the configuration file paypal.php is located in the config folder will contain this code at this stage


return [
'mode' => env('PAYPAL_MODE', 'sandbox'), // Can only be 'sandbox' Or 'live'. If empty or invalid, 'live' will be used.
'sandbox' => [
'client_id' => env('PAYPAL_SANDBOX_CLIENT_ID', ''),
'client_secret' => env('PAYPAL_SANDBOX_CLIENT_SECRET', ''),
'app_id' => 'APP-80W284485P519543T',
],
'live' => [
'client_id' => env('PAYPAL_LIVE_CLIENT_ID', ''),
'client_secret' => env('PAYPAL_LIVE_CLIENT_SECRET', ''),
'app_id' => '',
],

'payment_action' => env('PAYPAL_PAYMENT_ACTION', 'Sale'), // Can only be 'Sale', 'Authorization' or 'Order'
'currency' => env('PAYPAL_CURRENCY', 'USD'),
'notify_url' => env('PAYPAL_NOTIFY_URL', ''), // Change this accordingly for your application.
'locale' => env('PAYPAL_LOCALE', 'en_US'), // force gateway language i.e. it_IT, es_ES, en_US ... (for express checkout only)
'validate_ssl' => env('PAYPAL_VALIDATE_SSL', true), // Validate SSL when creating api client.
];

5- after installing the package, we will have to go to our view (blade) where we want to paypal buttons to appear and working and provide this div


<div id="paypal-button-container"></div>

6- after this add this script with your client id in the same page


<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
// change test with your actual client id from your developer dashboard on developer.paypal.com

7- add this script to your page which is resposible for creating paypal orders and make transactions


// Render the PayPal button into #paypal-button-container
paypal.Buttons({

// Call your server to set up the transaction
createOrder: function(data, actions) {
return fetch("{{ url('/api/paypal/order/create/') }}", {
method: 'post',
body: JSON.stringify({
'value':12.11, // change the value as you want
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},

// Call your server to finalize the transaction
onApprove: function(data, actions) {
return fetch("{{ url('/api/paypal/order/capture/') }}", {
method: 'post' ,
body: JSON.stringify({
'orderId': data.orderID ,
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
// Three cases to handle:
// (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
// (2) Other non-recoverable errors -> Show a failure message
// (3) Successful transaction -> Show confirmation or thank you

// This example reads a v2/checkout/orders capture response, propagated from the server
// You could use a different API or structure for your 'orderData'
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];

if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart(); // Recoverable state, per:
// https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
}

if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
if (errorDetail.description) msg += '\n\n' + errorDetail.description;
if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}

// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');

// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}

}).render('#paypal-button-container');

8- at this stage we have provided the script wich will use the API url to start testing paypal transactions, the paypal transactions will work with two APIs one of them will gather the value you want to pay and login to your account and choose best payment method you want and the other method will handle the transaction process itself, but for now we haven't created our api routes to use, and we want a new controller for this process, so start adding new controller like this


php artisan make:controller PaypalController

9- go to routes folder in your project -> api.php file and this code


<?php

use App\Http\Controllers\PaypalController ; // Don't forget to include your controller here
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});

Route::prefix('/paypal')->group(function () {
Route::post("/order/create", ['uses'=>'PaypalController@create', 'as'=>'paypal.create']);
Route::post("/order/capture", ['uses'=>'PaypalController@capture', 'as'=>'paypal.capture']);
});

10- in paypal controller you have to provide 2 methods (one for handle the value, login to your account and payment method and the other to handle the transaction process itself) like this


<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\PayPal as PayPalClient; //Don't forget to include this line from the package we installed previously

class PaypalController extends Controller
{
public function create(Request $request) {
$data = json_decode($request->getContent(), true);

// INITIALIZE PAYPAL
$provider = new PayPalClient;
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);

$price = $data['value'] ;

$order = $provider->createOrder([
"intent"=> "CAPTURE",
"purchase_units"=> [
[
"amount"=> [
"currency_code"=> "USD",
"value"=> $price
]
]
],
]);

return response()->json($order);
}


public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderId'] ;

// INITIALIZE PAYPAL
$provider = new PayPalClient;
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);

$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}

}

and here we are, all things about paypal integration is ok for now 


the last thing I will teach you is that testing your paypal integration 


************ TESTING PAYPAL TRANSACTIONS ************


at this stage all you have to do is to test your paypal transactions, to test your integration you will need the accounts you created earlier in the developer dashboard at developer.paypal.com .


you will need at least 2 account :
1- business account and relate this account with your previously created app from developer dashboard .
2- personal account to transfer money (value) from .


you can test all these fake accounts from paypal sandbox (https://www.sandbox.paypal.com/)


if you want to test with credit card all you have to do is from developer dashboard -> from sidebar -> choose Credit Card Generator -> and copy all of credit card details (type, number, expiration date and cvv) and go to the account you want to link this credit card (for example personal account) and from banks and cards section in the account -> link the new card with all details provided


Good Luck

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.