Cashfree Payment Gateway Integration In Laravel

  • 17-09-2022
  • 5058
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

In this tutorial we will learn Cashfree Payment Gateway Integration In Laravel application. To get done we need to generate an API key from the payment gateway provider. I have already below given some step images, by following this step you will be able to find your API key to authentication payment.

Cashfree Payment Gateway Integration In Laravel?

  • Step 1: Generate API Key
  • Step 2: Config .env
  • Step 3: Route Define
  • Step 4: Cash Free Payment Controller
  • Step 5: Form View Blade File
  • Step 6: Start Server

To create an account in cash-free click Create Account and apply to verification your business account.

Step 1. Generate API Key

Goto code menu and click on the API Keys as per the below image given. You will be redirected to the API key generate dashboard.

image

Click on the three dots on the right side of the table. and click on View API keys and there will show a model with the both API key APP ID and the other secret key.

image

Step 2. Config .env File

Once you got both keys from the cash-free dashboard, go to your .env file. you will find the root of your project. open the file and paste both keys into your file.

How to Integrate Razorpay Payment Gateway in Laravel 9 Example

.env
CASHFREE_API_KEY=2348819b1223ac38d38c64ee19188432
CASHFREE_API_SECRET=17a62f830df771696e620ebf3ceba5e6492f8303

Step 3. Route Define

Create a cash-free controller for the make order generate method and success response handle method.

php artisan make:controller CashfreePaymentController

As well as create a route as per the below example given, We will use the first route for the show form. the second route for the creation order. third route for the callback response handle.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CashfreePaymentController;

/*
|--------------------------------------------------------------------------
| 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('cashfree/payments/create', [CashfreePaymentController::class, 'create'])->name('callback');
Route::post('cashfree/payments/store', [CashfreePaymentController::class, 'store'])->name('store');
Route::any('cashfree/payments/success', [CashfreePaymentController::class, 'success'])->name('success');

Step 4. Cash Free Payment Controller

Open your CashfreePaymentController and paste the below code into your controller file.

app/Http/Controllers/CashfreePaymentController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Str;

class CashfreePaymentController extends Controller
{
     public function create(Request $request)
     {
          return view('payment-create');
     }

     public function store(Request $request)
     {
          $validated = $request->validate([
               'name' => 'required|min:3',
               'email' => 'required',
               'mobile' => 'required',
               'amount' => 'required'
          ]);
               
          $url = "https://sandbox.cashfree.com/pg/orders";

          $headers = array(
               "Content-Type: application/json",
               "x-api-version: 2022-01-01",
               "x-client-id: ".env('CASHFREE_API_KEY'),
               "x-client-secret: ".env('CASHFREE_API_SECRET')
          );

          $data = json_encode([
               'order_id' =>  'order_'.rand(1111111111,9999999999),
               'order_amount' => $validated['amount'],
               "order_currency" => "INR",
               "customer_details" => [
                    "customer_id" => 'customer_'.rand(111111111,999999999),
                    "customer_name" => $validated['name'],
                    "customer_email" => $validated['email'],
                    "customer_phone" => $validated['mobile'],
               ],
               "order_meta" => [
                    "return_url" => 'http://127.0.0.1:8000/cashfree/payments/success/?order_id={order_id}&order_token={order_token}'
               ]
          ]);

          $curl = curl_init($url);

          curl_setopt($curl, CURLOPT_URL, $url);
          curl_setopt($curl, CURLOPT_POST, true);
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

          $resp = curl_exec($curl);

          curl_close($curl);

          return redirect()->to(json_decode($resp)->payment_link);
     }

     public function success(Request $request)
     {
          dd($request->all()); // PAYMENT STATUS RESPONSE
     }
}

Step 5. Form View Blade File

Now, create a blade file in the views inside the resources folder. A file is a form. It Will help us to generate payment orders through the collect user data from the client side.

This is just a simple user data collection form, you can modify it according to your requirement.

resources/views/payment-create.blade.php
<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8">
     <title>Laravel 9 Cashfree Payment Gateway Integration Tutorial</title>
     <meta name="csrf-token" content="{{ csrf_token() }}">
     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
     <div class="container mt-3">
          <div class="row justify-content-center">
               <div class="col-12 col-md-6 mb-3">
                    <div class="card text-dark bg-light mb-3">
                    <div class="card-header text-center">
                         <h3 class="card-title " style="display: inline-block;">Create New Payment - Webappfix</h3>
                    </div>
                    <div class="card-body">
                         <form action="{{ route('store') }}" method="POST" name="laravel9-cashfree-integration">
                              @csrf
                              <div class="form-floating py-2">
                              <input type="text" class="form-control" name="name" id="name" value="{{ old('name') }}" placeholder="name">
                              <label for="name">Full Name</label>
                              </div>
                              <div class="form-floating py-2">
                              <input type="email" class="form-control" name="email" id="email" value="{{ old('email') }}" placeholder="email">
                              <label for="email">Email Address</label>
                              </div>
                              <div class="form-floating py-2">
                              <input type="text" class="form-control" name="mobile" id="mobile" value="{{ old('mobile') }}" placeholder="mobile">
                              <label for="mobile">Mobile Number</label>
                              </div>
                              <div class="form-floating py-2">
                              <input type="text" class="form-control" name="amount" id="amount" value="{{ old('amount') }}" placeholder="amount">
                              <label for="amount">Amount</label>
                              </div>
                              <button class="w-100 btn btn-lg btn-success" type="submit">Place Order</button>
                         </form>
                         @if ($errors->any())
                         <div class="alert alert-danger text-start" role="alert">
                              <strong>Opps!</strong> Something went wrong<br>
                              <ul>
                              @foreach ($errors->all() as $error)
                                   <li>{{ $error }}</li>
                              @endforeach
                              </ul>
                         </div>
                         @endif
                    </div>
                    </div>
               </div>
          </div>
     </div>
</body>
</html>

Step 6. Start Server

Well, we will all be set, lets do start our application development server locally using the below-provided command in your project application terminal.

php artisan serve

once your application development server is started, in your browser paste the given URL and run.

http://127.0.0.1:8000/cashfree/payments/create
Output:

This is the use of basic information collected from data. Once you submit the form it will generate an order and redirect you to the cash-free payment dashboard.

image

You will see an interface something like this, for the collection of cash-free payments.

image

Once you enter your card details and click on the pay now button, there will be an ask for the enter OTP. Enter OTP you will receive in your given mobile phone number. if the test mode then you will see below of OTP input.

image

Order successfully create as well as successfully payment done. You will see in your payment dashboard something like that given.

image

Laravel Tap Payment Gateway Integration Tutorial Example


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :