Simplified Laravel 9 Cashfree Integration Tutorial for Beginners

Last Updated: 01 Feb, 2023

In this awesome tutorial, we are going to learn the simplest way of integrating Cashfree Payment Gateway inside Laravel 9 application. We will be using REST APIs that have been provided by Cashfree.

Cashfree is a powerful and scalable payments platform that has been designed for business payment needs. It provides the following services which are very easy to use:

  • Helps to Collect Online Payments
  • Provides Multiple Channels
  • Helps to Send Payouts
  • Allows Easy Reconcilation
  • Offers Recurring Payments
  • Allows to manage International Payments and do more.

Simplest way to integrate Cashfree Payment Gateway in Laravel 9 application?

Hi friends, I am feeling very excited to share my experience of integrating cashfree in laravel application. Just follow the below mentioned steps to get this done.

Step 1: Create New Laravel 9 Application

At first, let's create a new laravel 9 application by running below command in your terminal:

composer create-project laravel/laravel l9cashfreepg

Step 2: Update .env file for DB Connection

Next, let's modify .env file and provide your database credentials as follows:

DB_DATABASE=l9cashfreepg
DB_USERNAME={your_dbuser}
DB_PASSWORD={your_dbpass}

Step 3: Setup Cashfree API KEYs and Endpoint

Now, let's go to cashfree official website (https://www.cashfree.com/) and login to your account. If you have not created your cashfree account yet, create a new account. Then, you can get your API_KEY and API_SECRET. Let's configure these credentials in .env file as follows:

CFPG_API_KEY=dfsd706e124dfk7wea3099edrt4784
CFPG_API_SECRET=a178dfk7wea35def32f3350ab32f2ab5706e124
CFPG_ENDPOINT=https://test.cashfree.com/

Next, open your app/config/services.php file and copy the following code inside it:

'cashfree' => [
    'api_key' => env('CFPG_API_KEY'),
    'api_secret' => env('CFPG_API_SECRET'),
    'endpoint' => env('CFPG_ENDPOINT')
],

Step 4: Create CFPGPayment Model & Migration

Next, you have to create model and migration files to store payment details inside it. Execute below given command in the therminal:

php artisan make:model CFPGPayment
php artisan make:migration create_cfpgpayments_table

Above command will generate a model and a migration file. Open app/Models/CFPGPayment.php file and copy below provided code into it:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CFPGPayment extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'email',
        'mobile',
        'amount'
    ];
}

Open the databse/migrations/*_create_cfpgpayments_table.php file and copy below mentioned code into it:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('cfpgpayments', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('mobile');
            $table->string('email');
            $table->string('amount');
            $table->string('purpose');
            $table->string('payment_request_id');
            $table->string('payment_link');
            $table->string('payment_status');
            $table->string('payment_id')->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('cfpgpayments');
    }
};

Next, execute the below command to run laravel migrattion that will create the tables in the mysql db:

php artisan migrate

Step 5: Create Application Routes

Next, open the routes/web.php file and copy the following code inside it:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CFPGPaymentController;

Route::group(['prefix' => 'cashfreepayments'], function () {
    Route::get('/', [CFPGPaymentController::class, 'index']);
    Route::get('/create', [CFPGPaymentController::class, 'create']);
    Route::post('/', [CFPGPaymentController::class, 'store']);
    Route::any('/success', [CFPGPaymentController::class, 'success']);
});

Step 6: Create CFPGPayment Controller

php artisan make:controller CFPGPaymentController

Next, let's create a controller app/Http/Controllers/CFPGPaymentController.php file and copy below given code in it:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Validator;
use App\Models\CFPGPayment;

class CFPGPaymentController extends Controller
{
    protected $rpp = 10;

    public function index(Request $request)
    {
        $request_data = $request->all();

        $view_data = [];
        
        if (!$request->ajax()){

            $view_data['title'] = 'Payment List';
            return view('cfpgpayments.index')->with($view_data);

        } else {

            $page = $request_data['page'];
            $view_data['page'] = $page;
        
            $records = CFPGPayment::orderBy('created_at', 'desc')->paginate($this->rpp);
            
            $record_starts = $this->rpp * ($page - 1) + 1;
            $record_ends = $this->rpp * ($page - 1) + count($records);
            
            $view_data['records'] = $records;
            $view_data['record_starts'] = $record_starts;
            $view_data['record_ends'] = $record_ends;
            return view('cfpgpayments.list')->with($view_data);
        }
    }

    public function create(Request $request)
    {
        $view_data['title'] = 'Create New Payment';
        return view('cfpgpayments.payments.create')->with($view_data);
    }

    public function store(Request $request)
    {
        $posted_data = $request->all();

        $validator = Validator::make($posted_data, array(
            'name' => 'required|min:3',
            'email' => 'required',
            'mobile' => 'required',
            'amount' => 'required'
        ), array(
            'name.required' => 'Enter your name.',
            'name.min' => 'Name must be min of 3 characters.',
            'email.required' => 'Enter your email address.',
            'mobile.required' => 'Enter your mobile number.',
            'amount.required' => 'Enter your amount.'
        ));

        if ($validator->fails()) {
            return redirect()->back()->withInput($request->only('name', 'email', 'mobile', 'amount'))->withErrors($validator->errors());
        }

        try {
            $cashfree = config('services.cashfree');

            $name = trim($request->name);
            $email = trim($request->email);
            $mobile = trim($request->mobile);
            $amount = intval($request->amount);
            $purpose = 'Cashfree Invoice Payment';

            $payload = array(
                'appId' => $cashfree['api_key'],
                'secretKey' => $cashfree['api_secret'],
                'orderId' => 'CFORDER-' . Str::random(9),
                'orderAmount' => $amount,
                'orderCurrency' => 'INR',
                'orderNote' => $purpose,
                'customerName' => $name,
                'customerPhone' => $mobile,
                'customerEmail' => $email,
                'returnUrl' => url('/cashfreepayments/success')
            );

            $request_string = "";
            foreach($payload as $key=>$value) {
                $request_string .= $key.'='.rawurlencode($value).'&';
            }

            $end_point = $cashfree['endpoint'];
            $opUrl = $end_point . "api/v1/order/create";

            try {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "$opUrl?");
                curl_setopt($ch, CURLOPT_POST, count($payload));
                curl_setopt($ch, CURLOPT_POSTFIELDS, $request_string);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                $curl_result=curl_exec ($ch);
                curl_close ($ch);
                $response = json_decode($curl_result);
                if ($response->{'status'} == "OK") {
                    $paymentLink = $response->{"paymentLink"};
                    CFPGPayment::insert([
                        'name' => $name,
                        'email' => $email,
                        'mobile' => $mobile,
                        'amount' => $amount,
                        'purpose' => $purpose,
                        'payment_request_id' => $cf_request["orderId"],
                        'payment_link' => $paymentLink,
                        'payment_status' => 'created',
                        'created_at' => now(),
                        'updated_at' => now()
                    ]);
                    header('Location: ' . $paymentLink);
                    exit();
                } else {
                    echo "<pre>";
                    print_r($response);
                    exit;
                }
            } catch (Exception $e) {
                $return_data = array(
                    'status' => 'ERROR',
                    'message' => $e->getMessage()
                );
            }
        }catch (Exception $e) {
            echo "<pre>";
            print('Error: ' . $e->getMessage());
            exit;
        }
    }

    public function success(Request $request)
    {
        $request_data = $request->all();

        $payment_id = $request_data['referenceId'];
        $payment_status = trim($request_data['txStatus']);
        $payment_request_id = $request_data['orderId'];

        $cf_payment = CFPGPayment::where('payment_request_id', $payment_request_id)->first();
        
        if (strtolower($payment_status) == 'success') {
            $cf_payment->payment_status = $payment_status;
            $cf_payment->payment_id = $payment_id;
            $cf_payment->save();
            dd('Payment Successful');
        } else {
            dd('Payment Failed!');
        }
        dd($request_data);
    }
}

Step 7: Create Blade View Pages

Now, create the following blade files under resources/views/cfpgpayments directory:

resources/views/cfpgpayments/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Cashfree Payment Gateway Integration Tutorial - Laravel 9</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">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<div class="container mt-3">
    <div class="row text-center"><h1>Cashfree Payment Gateway Integration Tutorial in Laravel 9</h1></div>
    <div class="row" id="result-div"><strong style="color: #0cf;text-align: center;">Fetching payments...</strong></div>
</div>
<script>
var pageNo = 1;
$(document).ready(function(){
    $.ajax({
        url: "{{url('cashfreepayments')}}",
        type: "GET",
        dataType: "HTML",
        data: { 'page': pageNo }
    }).done(function(data){
        $("#result-div").empty().html(data);
    }).fail(function(jqXHR, ajaxOptions, thrownError){
        console.log('No response from server');
    }).always(function(){
    });
});
</script>
</body>
</html>

resources/views/cfpgpayments/list.blade.php

<div class="col-12 mb-3">
    <div class="card text-white bg-success mb-3">
        <div class="card-header">
            <h3 class="card-title" style="display: inline-block;">Payments List</h3>
            <a href="{{url('/cashfreepayments/create')}}" class="btn btn-primary float-end">Create New Payment</a>
        </div>
        <div class="card-body table-responsive">
            <table class="table table-striped text-white">
                <thead>
                <tr style="text-transform: uppercase;">
                    <th>#</th>
                    <th>Name</th>
                    <th>EMail</th>
                    <th>Mobile</th>
                    <th>Amount</th>
                    <th>Purpose</th>
                    <th>Status</th>
                    <th>PaymentId</th>
                    <th>CreatedAt</th>
                </tr>
                </thead>
                <tbody>
                @if($records->count() > 0)
                    @foreach($records as $rec)
                    <tr>
                        <td>{{$loop->iteration}}</td>
                        <td>{{$rec->name}}</td>
                        <td>{{$rec->email}}</td>
                        <td>{{$rec->mobile}}</td>
                        <td>{{$rec->amount}}</td>
                        <td>{{$rec->purpose}}</td>
                        <td><button class="btn btn-info">{{$rec->payment_status}}</button></td>
                        <td>{{$rec->payment_id}}</td>
                        <td>{{$rec->created_at}}</td>
                    </tr>
                    @endforeach
                @else
                    <tr class="text-center"><td colspan="8">Record not found!!</td></tr>
                @endif
                </tbody>
            </table>
            {!! $records->links() !!}
        </div>
    </div>
</div>

resources/views/cfpgpayments/create.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Cashfree Payment Gateway Integration Tutorial - Laravel 9</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">
</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-success mb-3">
                    <div class="card-header">
                        <h3 class="card-title text-white" style="display: inline-block;">Create New Payment</h3>
                        <a href="{{url('/cashfreepayments')}}" class="btn btn-primary float-end">Payments List</a>
                    </div>
                    <div class="card-body">
                        <form action="{{ url('cashfreepayments') }}" method="POST" name="laravel9-cashfree-integration">
                            {{ csrf_field() }}
                            <div class="form-floating">
                              <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">
                              <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">
                              <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">
                              <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-primary" 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 8: Run Your Application

All set, let's start the development server now by executing below command in your terminal:

php artisan serve

Once development server is started, in your browser, open below URL:

http://127.0.0.1:8000/cashfreepayments

Note: Test Card Credentials link to test your application:

https://docs.cashfree.com/docs/data-to-test-integration

Thank You, Please Share.

Recommended Posts

Simplified Laravel 9 REST API Tutorial using Sanctum  Authentication

Simplified Laravel 9 REST API Tutorial using Sanctum Authentication

In this simplified tutorial, you will learn the simplest way to create a REST API application in Laravel 9 that will be authenticated using Laravel Sanctum.

Simplified Laravel 9 Razorpay Integration Tutorial for Beginners

Simplified Laravel 9 Razorpay Integration Tutorial for Beginners

This simplified tutorial will show you the easy and simplest way of integrating Razorpay Payment Gateway in Laravel 9 Application.

Simplified Laravel 9 Instamojo Integration Tutorial for Beginners

Simplified Laravel 9 Instamojo Integration Tutorial for Beginners

In this simple tutorial, you will be learning the easy and comprehensive way of integrating Instamojo Payment Gateway inside Laravel 9 application.