How to integrate Razorpay with Laravel
In this post we will learn how to integrate razorpay payment gateway using laravel.
First create laravel application using composer command.
composer create-project laravel/laravel razorpaywithlaravel
Get in Application
Cd razorpaywithlaravel
Run below composer command for UI
composer require laravel/ui
Run ui vue command for generating auth routes a vue js template
php artisan ui vue
Now run npm install and run dev
npm install
npm run dev
Razorpay Gateway integration with Laravel and vue
In resources\js\app.js add below code .
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
import App from './App.vue';
require('./bootstrap');
window.Vue = require('vue').default;
/**
* The following block of code may be used to automatically register your
* Vue components. It will recursively scan this directory for the Vue
* components and automatically register them with their "basename".
*
* Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
*/
// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
// const app = new Vue({
// el: '#app',
// });
import App from './App.vue';
const app = new Vue({
el: '#app',
template: "",
components: {
App,
},
});
Create new vue file App.vue
App.vue will contain payment data which user will submit
resources\js\App.vue
<template>
<section class="payment">
<div>
<span>Amount:</span>
<input type="text" v-model="amount" />
<button type="button" @click="razorPay">Pay with Razorpay</button>
</div>
</section>
</template>
Now install razorpay packages with composer command
composer require razorpay/razorpay
Create values.php inside config directory for pass razorpay KEY_ID and Secret key
config\values.php
<?php
return [
'razorpayKey' => env('RZ_KEY_ID', 'YOUR_KEY'),
'razorpaySecret' => env('RZ_SECRET', 'YOUR_SECRET'),
];
Create Controller: Create a controller for razorpay gateway using artisan command
php artisan make:controller PaymentgatewayController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;
class PaymentgatewayController extends Controller
{
public function razorpay(Request $request)
{
$api = new Api(Config("values.razorpayKey"), Config("values.razorpaySecret"));
$orderData = $api->order->create([
'receipt' => '111',
'amount' => $request->amount * 100,
'currency' => 'INR'
]); // Creates Razorpay order
$data = [
"key" => Config("values.razorpayKey"),
"amount" => $request->amount * 100,
"order_id" => $orderData['id'],
];
return response()->json($data, 200);
}
function verify(Request $request)
{
$success = true;
$error = "Payment Failed!";
if (empty($request->razorpay_payment_id) === false) {
$api = new Api(Config("values.razorpayKey"), Config("values.razorpaySecret"));
try {
$attributes = [
'razorpay_order_id' => $request->razorpay_order_id,
'razorpay_payment_id' => $request->razorpay_payment_id,
'razorpay_signature' => $request->razorpay_signature
];
$api->utility->verifyPaymentSignature($attributes);
} catch (SignatureVerificationError $e) {
$success = false;
$error = 'Razorpay Error : ' . $e->getMessage();
}
}
if ($success === true) {
// Update database with success data
// Redirect to success page
return redirect('/');
} else {
// Update database with error data
// Redirect to payment page with error
// Pass $error along with route
return redirect('/');
}
}
}
Create Blade File
Create blade file inside resources/views paymentgateway.blade.php, resources\views\app.blade.php, resources\views\razorpay.blade.php
paymentgateway.blade.php
<form name='razorpayform' action="/pay/verify" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id">
<input type="hidden" name="razorpay_signature" id="razorpay_signature">
<input type="hidden" name="razorpay_order_id" id="razorpay_order_id" value="<?php echo request()->order_id ?>">
</form>
app.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel with Razorpay Pay</title>
</head>
<body>
<div id="app"></div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
resources\views\razorpay.blade.php
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<form name='razorpayform' action="/pay/verify" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id">
<input type="hidden" name="razorpay_signature" id="razorpay_signature">
<input type="hidden" name="razorpay_order_id" id="razorpay_order_id" value="<?php echo request()->order_id ?>">
</form>
<script>
var options = {
"key": "<?php echo request()->key ?>",
"amount": "<?php echo request()->amount ?>",
"currency": "INR",
"name": "YOUR COMPANY NAME",
"description": "YOUR COMPANY DESCRIPTION",
"image": "YOUR COMPANY IMAGE",
"order_id": "<?php echo request()->order_id ?>",
"handler": function(response) {
alert(response.razorpay_payment_id);
alert(response.razorpay_order_id);
alert(response.razorpay_signature)
},
"theme": {
"color": "#F37254"
}
};
options.handler = function(response) {
document.getElementById('razorpay_payment_id').value = response.razorpay_payment_id;
document.getElementById('razorpay_signature').value = response.razorpay_signature;
document.razorpayform.submit();
};
options.theme.image_padding = false;
options.modal = {
ondismiss: function() {
window.location.href = "/pay?payment=false"
},
escape: true,
backdropclose: false
};
var rzp1 = new Razorpay(options);
rzp1.on('payment.failed', function(response) {
alert(response.error.code);
alert(response.error.description);
alert(response.error.source);
alert(response.error.step);
alert(response.error.reason);
alert(response.error.metadata.order_id);
alert(response.error.metadata.payment_id);
});
rzp1.open();
</script>
Create Routes : Now create routes in web.php for submit for payment form
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PaymentgatewayController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
Route::view('/pay/razorpay', 'razorpay');
Route::post('/pay/verify', [PaymentgatewayController::class, 'verify']);
Route::get('/{any}', function () {
return view('app');
})->where('any', '.*');
routes\api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PaymentgatewayController;
/*
|--------------------------------------------------------------------------
| 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::post('payment/razorpay', [PaymentgatewayController::class, 'razorpay'])->name('paymentRazorpay');
Config Database and razorpay secret key and ID:
Configure database using .env file and migrate database using artisan migrate command
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_razorpay_db
DB_USERNAME=root
DB_PASSWORD=
RZ_KEY_ID=rzp_test_kS80NTezFBTFjA
RZ_SECRET=YjcL7bBXU7Ei60RmE3IHgWn0
php artisan migrate
Run application :
Now run your application with php artisan serve command
php artisan command