Quick Summary:

In this modern technology world, the combination of Laravel and VueJS is unbeatable and very powerful for making any high-end application run smoothly. There is an increasing need for e-commerce/content-driven websites. You now need a payment gateway to make easy transactions. So here is how to integrate the Razorpay payment gateway into your latest versions of Laravel along with VueJS.

Without further ado, let’s get started with the Razorpay Payment Gateway Integration in Laravel and VueJS 2.

Table of Contents

Initial Set-Up: Laravel and NPM Dependencies Installation

First, you need the latest Laravel version and Node dependencies installed to get started; run the commands below one by one to install the required stuff.

Copy Text
composer create-project laravel/laravel razorpay-demo
cd razorpay-demo
composer require laravel/ui
php artisan ui vue
npm install
npm run dev

Note: If you face this error
“Cannot find module ‘webpack/lib/rules/DescriptionDataMatcherRulePlugin’”

Run this command

Copy Text
npm i vue-loader

Then in a separate terminal, run the Laravel server by using the following command

Copy Text
php artisan serve

Include /js/app.js and app tag in the view

Your app.js file will be compiled and saved to public/js/app.js. Make sure to add a root element with the app’s ID to your HTML scaffolding. Otherwise, Vue won’t know where to mount the components.

// resources/views/app.blade.php

Copy Text
<div id="app"></div>
<script src="{{ asset('js/app.js') }}" data-rocket-defer defer></script>
Streamline Your Payment Gateway Integration

Hire full stack developer from us and ensure smooth payment integration to provide reliable and secure user experience.

VueJS Set-Up: Razorpay Payment Gateway Integration in Laravel and VueJS 2

The following are the ways to set up Razorpay Laravel integration with Vue js.

// resources/js/app.js

Copy Text
import App from './App.vue';
const app = new Vue({
  el: '#app',
  template: "",
  components: {
    App,
  },
});

Create App.vue File

This file contains the Payment data for now; in your real-time application, you need to pass the user information and amount on the “pay” button click.

// resources/js/App.vue

Copy Text
<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>

<script>
import axios from "axios";

export default {
  name: "app",
  data() {
    return {
      amount: 100,
    };
  },
  methods: {
    razorPay() {
      axios
        .post("/api/payment/razorpay", { amount: this.amount })
        .then((res) => {
          if (res.data) {
            window.location.href = "/pay/razorpay?key=" + res.data.key + "&amount=" + res.data.amount + "&order_id=" + res.data.order_id;
          }
        })
        .catch((err) => {});
    },
  },
};
</script>

Create Razorpay Account

Create an Account from here: https://razorpay.com

Get id and secret from here: https://dashboard.razorpay.com/app/keys

Create Razorpay Account

Open .env file and add RazorPay key and secret to it

// .env

Copy Text
RZ_KEY_ID=YOUR_KEY
RZ_SECRET=YOUR_SECRET

Set-Up and Install Razorpay Package

Use the below command to install RazorPay package

Copy Text
composer require razorpay/razorpay

Create config file to access .env values and use the below code.

// config/values.php

Copy Text
 env('RZ_KEY_ID', 'YOUR_KEY'),
  'razorpaySecret' => env('RZ_SECRET', 'YOUR_SECRET'),
];

Create Razorpay Controller

Use the below command to create a controller.

Copy Text
php artisan make:controller RazorPayController

// app/Http/Controllers/RazorPayController.php

Copy Text
order->create([
     'receipt' => '123',
     '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('/');
   }
 }
}

Add Routes

Moving further in our tutorial: Razorpay payment gateway integration. Let’s add routes for displaying the Razorpay page and verifying requests. Open the routes/web.php file and use the below code.

// routes/web.php

Copy Text
use App\Http\Controllers\RazorPayController;
 
Route::view('/pay/razorpay', 'razorpay');
Route::post('/pay/verify', [RazorPayController::class, 'verify']);

Now, add an API route to access through VueJS. For that use the following code.

// routes/api.php

Copy Text
use App\Http\Controllers\RazorPayController;
 
Route::post('payment/razorpay', [RazorPayController::class, 'razorpay'])->name('paymentRazorpay');

Create Razorpay View

This is the Razorpay Laravel and Vue js gateway. Users enter their credentials and pay using various methods. Here, you can enter your company/personal details like name, description, and logo to show users who they are paying.

// resources/views/razorpay.blade.php

Copy Text
<script data-minify="1" src="https://www.bacancytechnology.com/blog/wp-content/cache/min/1/v1/checkout.js?ver=1733982185" data-rocket-defer defer></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>

You can also prefill user data if you have already; you need to add this under options.

Copy Text
prefill: {
  name: “USER NAME”,
  email: “USER EMAIL”,
  phone: “USER CONTACT”
}

Check Transaction

The user interface will look something like this.

Check Transaction

Now it’s time to check the payment transaction; for that, visit RazorPay Dashboard.

Here is the reference image:

Check Transaction

The entire source code is available here: razorpay-payment-gateway-integration-example. Use the below command to clone the repository and play around with it.

Copy Text
git clone https://github.com/keyurkansara/razorpay-laravel-vue.git

Conclusion

The tutorial on Razorpay Laravel and Vue js payment gateway integration has helped you to generate secure transactions. Moreover, you can visit VueJS and Laravel tutorials pages and explore more about both technologies individually. Each tutorial will provide you with a github repository to play around with the code.

Bacancy has a skilled team of developers who are experts in both backend and frontend development. Our dedicated full-stack developers analyze the project requirements and problems from both front-end and back-end perspectives, providing the optimum solution.

Looking to Integrate Razorpay into Your Project Seamlessly?

Let our experts simplify the process and implement Razorpay payment integration with Laravel and Vue.js 2 for secure and efficient transactions.

Connect Now

Build Your Agile Team

Hire Skilled Developer From Us

solutions@bacancy.com

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?