TABLE OF CONTENTS

Subscribe for
weekly updates

newsletter

In this latest technology world, the combination of Laravel and VueJS is unbeatable and very powerful to make any high-end application that runs smooth. There is an increasing need for e-commerce/content-driven websites. You now need a payment gateway to make easy transactions. So here is the way to integrate Razorpay payment gateway to your Laravel 6/7/8 versions along with VueJS.

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

Initial Set-Up: Laravel and NPM Dependencies Installation

First of all, you need a fresh Laravel version and node dependencies installed to get started; run the below commands mentioned 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 the 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 also have a root element with an id of the app 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') }}"></script>

Having a developer with both front-end and back-end insights works as an asset for your project.

A full-stack developer sees the bigger picture and codes accordingly, lessening the troubleshooting time, issues, and bugs. { break; } the loop of your search and contact us today!

Try Our 15 Days Risk-Free Trial

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

// 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 gateway, users will enter the credentials and will 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 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>

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:

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

I hope the tutorial: Razorpay payment gateway integration has helped you as expected. Feel free to contact us with questions, suggestions, or feedback. You can visit VueJS and Laravel tutorials pages and explore more about both the technology individually. Each tutorial will provide you with a github repository so that you can play around with the code.

Bacancy has a skilled set of developers who has expertise with backend and frontend development. Our dedicated full-stack developers analyze the project requirements and problems from front-end and back-end perspectives, providing the optimum solution. Are you looking for developers who have both frontend and backend experience? If yes, then without wasting a second, contact us and hire fullstack developers.

Hire Full Stack Developer

Connect Now

Get In Touch

[email protected]

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.