As a Laravel 10 developer, I understand the importance of providing a secure and user-friendly payment experience for online businesses. That's why integrating a reliable payment gateway like PayPal into your Laravel 10 application can be a game-changer. If you're looking to integrate PayPal into your Laravel 10 project, you're in the right place.
In this comprehensive guide, I will walk you through the step-by-step process of integrating the PayPal payment gateway into your Laravel 10 application. Together, we'll cover all the necessary steps, from setting up a PayPal Business account to implementing the payment functionality within your Laravel codebase.
By the end of this tutorial, you'll have a solid understanding of how to harness the power of Laravel's features and seamlessly integrate PayPal's API for secure and efficient payment processing in your application.
PayPal is an American company operating a worldwide online payments system that supports online money transfers and serves as an electronic alternative to traditional paper methods like checks and money orders.
So, let's dive right in and discover the incredible potential of PayPal integration in Laravel 10.
Ensure you have a Laravel 10 project set up and ready for integration. If you haven't created a Laravel project yet, you can use the following command to create one.
composer create-project --prefer-dist laravel/laravel paypal_payment_integration
To integrate PayPal payment gateway in Laravel 10, you'll need to configure your database settings. Follow these steps.
Open the .env
file located in the root directory of your Laravel project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Open the terminal, navigate to your Laravel project directory, and run the following command to install the PayPal SDK package.
composer require paypal/rest-api-sdk-php
After installing the PayPal package for integration, the next step is to obtain the client_id
and secret_key
required for PayPal integration. To obtain these credentials, you will need to log in to the PayPal developer mode and create a new sandbox account. Here's a step-by-step guide:
-
Visit the PayPal developer website (https://developer.paypal.com/) and log in to your PayPal account.
-
Once logged in, navigate to the developer dashboard.
-
In the dashboard, click on "My Apps & Credentials" or a similar option, depending on the layout of the developer dashboard.
-
Next, click on the "Create App" button to create a new application for your PayPal integration.
-
Provide a suitable name for your application and select the sandbox environment.
-
After creating the application, you will be redirected to the application details page. Here, you will find the
client_id
andsecret_key
under the "Credentials" section. -
Take note of the
client_id
andsecret_key
values, as you will need them to configure the PayPal integration in your Laravel application.
To configure the PayPal integration in Laravel 10, you will need to create a paypal.php
configuration file. This file will contain the necessary settings for your PayPal integration. Follow these steps to create and configure the paypal.php
file:
-
Open your Laravel project in your preferred code editor.
-
Navigate to the
config
directory located in the root of your project. -
Inside the
config
directory, create a new file namedpaypal.php
. -
Open the
paypal.php
file and add the following code:
<?php
return [
'client_id' => 'XXXXXX',
'secret' => 'XXXXXX',
'settings' => array(
'mode' => 'sandbox',
'http.ConnectionTimeOut' => 1000,
'log.LogEnabled' => true,
'log.FileName' => storage_path() . '/logs/paypal.log',
'log.LogLevel' => 'FINE'
),
];
Create a route and corresponding controller method for initiating the PayPal payment. In your routes/web.php
file, add the following route.
<?php
use Illuminate\Support\Facades\Route;
Route::get('paywithpaypal', array('as' => 'paywithpaypal','uses' => 'PaypalController@payWithPaypal',));
Route::post('paypal', array('as' => 'paypal','uses' => 'PaypalController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'status','uses' => 'PaypalController@getPaymentStatus',));
Then, create a new controller using the command.
php artisan make:controller PaypalController
In the PaypalController
, add the payWithPayPal
and postPaymentWithpaypal
method.
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;
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 Controller
{
private $_api_context;
public function __construct()
{
$paypal_configuration = \Config::get('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_configuration['client_id'], $paypal_configuration['secret']));
$this->_api_context->setConfig($paypal_configuration['settings']);
}
public function payWithPaypal()
{
return view('paywithpaypal');
}
public function postPaymentWithpaypal(Request $request)
{
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item_1 = new Item();
$item_1->setName('Product 1')
->setCurrency('USD')
->setQuantity(1)
->setPrice($request->get('amount'));
$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('Enter Your transaction description');
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(URL::route('status'))
->setCancelUrl(URL::route('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')) {
\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;
}
}
Session::put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
return Redirect::away($redirect_url);
}
\Session::put('error','Unknown error occurred');
return Redirect::route('paywithpaypal');
}
public function getPaymentStatus(Request $request)
{
$payment_id = Session::get('paypal_payment_id');
Session::forget('paypal_payment_id');
if (empty($request->input('PayerID')) || empty($request->input('token'))) {
\Session::put('error','Payment failed');
return Redirect::route('paywithpaypal');
}
$payment = Payment::get($payment_id, $this->_api_context);
$execution = new PaymentExecution();
$execution->setPayerId($request->input('PayerID'));
$result = $payment->execute($execution, $this->_api_context);
if ($result->getState() == 'approved') {
\Session::put('success','Payment success !!');
return Redirect::route('paywithpaypal');
}
\Session::put('error','Payment failed !!');
return Redirect::route('paywithpaypal');
}
}
To create the view file for PayPal integration in Laravel 10, you will need to add the following code to your paywithpaypal.blade.php
file. This file will serve as the template for displaying the PayPal payment form and related information. Here are the steps to create and configure the paywithpaypal.blade.php
file:
-
Open your Laravel project in your preferred code editor.
-
Navigate to the
resources/views
directory located in the root of your project. -
Inside the
views
directory, create a new file namedpaywithpaypal.blade.php
. -
Open the
paywithpaypal.blade.php
file and add the following code:
<html>
<head>
<meta charset="utf-8">
<title> How To Integrate Paypal Payment Gateway In Laravel 10 - Vidvatek</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h3 class="text-center" style="margin-top: 90px;"> How To Integrate Paypal Payment Gateway In Laravel 10 - Vidvatek</h3>
<div class="panel panel-default" style="margin-top: 60px;">
@if ($message = Session::get('success'))
<div class="custom-alerts alert alert-success fade in">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
{!! $message !!}
</div>
<?php Session::forget('success');?>
@endif
@if ($message = Session::get('error'))
<div class="custom-alerts alert alert-danger fade in">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
{!! $message !!}
</div>
<?php Session::forget('error');?>
@endif
<div class="panel-heading"><b>Paywith Paypal</b></div>
<div class="panel-body">
<form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('paypal') !!}" >
{{ csrf_field() }}
<div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
<label for="amount" class="col-md-4 control-label">Enter Amount</label>
<div class="col-md-6">
<input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus>
@if ($errors->has('amount'))
<span class="help-block">
<strong>{{ $errors->first('amount') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Paywith Paypal
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Now, create Paypal sandbox test account for like below screenshot.
Once you have entered the payment amount, you will be presented with a form like the one shown below. If you do not have a PayPal account, you will need to create one before proceeding with the payment.
After clicking on the "Continue" button, you will be redirected to a success page similar to the screenshot shown below.
Once you reach this view, you will see another success message confirming your transaction. You will also have the option to check your transaction details by clicking on the provided link (www.sandbox.paypal.com).
In conclusion, integrating the PayPal payment gateway into your Laravel 10 application opens up a world of possibilities for processing online payments. Throughout this article, we have covered the step-by-step process of integrating PayPal and provided code examples to guide you along the way.
By following the steps outlined in this article, you have learned how to set up your Laravel application to handle PayPal payments. You have seen how to configure the necessary files, create views for payment forms, and process payment transactions using PayPal's APIs.
You might also like:
- Read Also: AJAX CRUD Operations In Laravel 10: Step-by-Step Guide
- Read Also: Laravel 10 Import and Export CSV and Excel Files
- Read Also: Building Complete CRUD Application in Laravel 10
- Read Also: How to Get Current Date and Time in Python