How to integrate Paypal Payment Gateway in Laravel? If you want to know, then you are in the right place. In this tutorial, we are about to use a srmklive/laravel-paypal plugin to handle laravel payment gateway integration. It offers a robust solution for making flawless payments in PHP based applications.
Laravel PayPal Integration is the essential feature, especially when developing an e-commerce app or enabling sell features. Paypal payment gateway is a more popular gateway in web development almost client prefer to use paypal payment gateway for money transfer in his website. Paypal is a user friendly gateway to transfer word wide.
Paypal Payment Gateway Integration in Laravel Example
Laravel Paypal Payment Gateway Integration tutorial will follows below steps:
- Step 1: Create new Laravel application
- Step 2: Connect Database to App
- Step 3: Install Laravel-Paypal package
- Step 4: Create Paypal account and credentials
- Step 5: Configure package
- Step 6: Create application routes
- Step 7: Create PayPalController controller
- Step 8: Create blade view for payment button
- Step 9: Create a test transaction
Install Laravel application
First at all, we start by installing a fresh new laravel application. You need to execute the below command to manifest the new laravel application.
composer create-project laravel/laravel laravel-paypal-app --prefer-dist
Go inside the app.
cd laravel-paypal-app
Connect Database to App
As you open the .env file and update the database credential according your hosts.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Install Laravel Paypal package
Now we will install Laravel-Paypal package for paypal payment gateway in laravel app. Using this package, you can also handle refund, payment notification or Rest API. Run the following command to install package.
composer require srmklive/paypal:~3.0
Get inside the config/app.php and register the required PayPal service in providers
and aliases
arrays.
....
....
providers' => [
....
Srmklive\PayPal\Providers\PayPalServiceProvider::class
]
....
....
providers' => [
....
'PayPal' => Srmklive\PayPal\Facades\PayPal::class
]
Get PayPal Details & Configure package
Here we are going to use Sandbox credentials to create test transaction. To generate REST API credentials for the sandbox and live environments, Log in to the Developer Dashboard with your PayPal account. You need to register App and create API credentials. Under the DASHBOARD menu, select My Apps & Credentials option.
Create new app
This will generate new App, Now click on App and get Client ID and Secret. We will need these details to add into Laravel .env file something like below.
#sandbox or live
PAYPAL_MODE=sandbox
#Paypal sandbox credential
PAYPAL_SANDBOX_CLIENT_ID=AeExqObFcW0X........tjVEuZm
PAYPAL_SANDBOX_CLIENT_SECRET=EOvIUjNQj.......gDTnkhNd
#Paypal live credential
PAYPAL_LIVE_CLIENT_ID=Jjac8ad......f2sd2faww
PAYPAL_LIVE_CLIENT_SECRET=cak8nd0Pq3mQf2f......jawd2z2d6
If you want to customize package default configuration options, run the below vendor:publish command.
php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"
This will create config/paypal.php
configuration file with below details, that you can change it.
<?php
return [
'mode' => env('PAYPAL_MODE', 'sandbox'),
'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'),
'currency' => env('PAYPAL_CURRENCY', 'USD'),
'notify_url' => env('PAYPAL_NOTIFY_URL', ''),
'locale' => env('PAYPAL_LOCALE', 'en_US'),
'validate_ssl' => env('PAYPAL_VALIDATE_SSL', true),
];
Add routes
Here in this step you need to update some routes for integrating paypal payment gateway in laravel application. You need to open your routes/web.php and update the below routes on it;
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PayPalController;
Route::get('create-transaction', [PayPalController::class, 'createTransaction'])->name('createTransaction');
Route::get('process-transaction', [PayPalController::class, 'processTransaction'])->name('processTransaction');
Route::get('success-transaction', [PayPalController::class, 'successTransaction'])->name('successTransaction');
Route::get('cancel-transaction', [PayPalController::class, 'cancelTransaction'])->name('cancelTransaction');
Create controller
Here you need to create a new controller named as PayPalController using the following command;
php artisan make:controller PayPalController
Now open app/Http/Controllers/PayPalController.php controller file and add below code into it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\PayPal as PayPalClient;
class PayPalController extends Controller
{
/**
* create transaction.
*
* @return \Illuminate\Http\Response
*/
public function createTransaction()
{
return view('transaction');
}
/**
* process transaction.
*
* @return \Illuminate\Http\Response
*/
public function processTransaction(Request $request)
{
$provider = new PayPalClient;
$provider->setApiCredentials(config('paypal'));
$paypalToken = $provider->getAccessToken();
$response = $provider->createOrder([
"intent" => "CAPTURE",
"application_context" => [
"return_url" => route('successTransaction'),
"cancel_url" => route('cancelTransaction'),
],
"purchase_units" => [
0 => [
"amount" => [
"currency_code" => "USD",
"value" => "1000.00"
]
]
]
]);
if (isset($response['id']) && $response['id'] != null) {
// redirect to approve href
foreach ($response['links'] as $links) {
if ($links['rel'] == 'approve') {
return redirect()->away($links['href']);
}
}
return redirect()
->route('createTransaction')
->with('error', 'Something went wrong.');
} else {
return redirect()
->route('createTransaction')
->with('error', $response['message'] ?? 'Something went wrong.');
}
}
/**
* success transaction.
*
* @return \Illuminate\Http\Response
*/
public function successTransaction(Request $request)
{
$provider = new PayPalClient;
$provider->setApiCredentials(config('paypal'));
$provider->getAccessToken();
$response = $provider->capturePaymentOrder($request['token']);
if (isset($response['status']) && $response['status'] == 'COMPLETED') {
return redirect()
->route('createTransaction')
->with('success', 'Transaction complete.');
} else {
return redirect()
->route('createTransaction')
->with('error', $response['message'] ?? 'Something went wrong.');
}
}
/**
* cancel transaction.
*
* @return \Illuminate\Http\Response
*/
public function cancelTransaction(Request $request)
{
return redirect()
->route('createTransaction')
->with('error', $response['message'] ?? 'You have canceled the transaction.');
}
}
Create blade file for payment button
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Pay $1000</title>
<script src="https://www.paypal.com/sdk/js?client-id={{ env('PAYPAL_SANDBOX_CLIENT_ID') }}"></script>
</head>
<body>
<a class="btn btn-primary m-3" href="{{ route('processTransaction') }}">Pay $1000</a>
@if(\Session::has('error'))
<div class="alert alert-danger">{{ \Session::get('error') }}</div>
{{ \Session::forget('error') }}
@endif
@if(\Session::has('success'))
<div class="alert alert-success">{{ \Session::get('success') }}</div>
{{ \Session::forget('success') }}
@endif
</body>
</html>
Run development server and test
Now Run the Laravel server using below Artisan command.
php artisan serve
Open the browser and run the url http://localhost:8000/create-transaction and process the transaction.
You can browse all API call history at PayPal dashboard.
Finally the laravel paypal payment integration is over now. I hope this tutorial will help you on your development.