Paytm Payment Gateway Integration in Laravel 10

Paytm Payment Gateway Integration in Laravel 10

In this tutorial, You will learn how to integrate Paytm payment gateway in Laravel web applications using the help of anandsiddharth/laravel-paytm-wallet package.

If you encounter an invalid checksum error while using the Paytm payment gateway SDK, you can also find a solution to resolve the invalid checksum error during the integration of the Paytm payment gateway.

Paytm Payment Gateway Integration in Laravel 10

  • Step 1: Setup New Laravel Project
  • Step 2: Setup Database with Laravel Project
  • Step 3: Install Anandsiddharth paytm package
  • Step 4: Create Migration and Create Model
  • Step 5: Define Route
  • Step 6: Create Controller
  • Step 7: Create Blade View file
  • Step 8: Start Development Server

Step 1: Setup New Laravel Project

First of all, open your terminal or command prompt.

Then you need to execute the following command into it to download and install laravel app on your server:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Setup Database with Laravel Project

Once you have installed laravel web app in your server. Now, you need to setup database with laravel project.

So, open your .evn file, which is located in root directory. Then add the database details like followings:

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name here
DB_USERNAME=database username here
DB_PASSWORD=database password here

Step 3: Install Anandsiddharth paytm package

Now, open again your terminal or cmd and execute the following command into it to install this package into your laravel project:

composer require anandsiddharth/laravel-paytm-wallet

Once you have successfully installed the package, now you need to register the provider and alias.

So, Go to the app/config/app.php and add the below lines code into it:

'providers' => [
// Other service providers…
Anand\LaravelPaytmWallet\PaytmWalletServiceProvider::class,
],
'aliases' => [
// Other aliases
'PaytmWallet' => Anand\LaravelPaytmWallet\Facades\PaytmWallet::class,
],

Then you need to set a paytm credential like below. So, visit to the app/config/services.php and set the paytm credential.

'paytm-wallet' => [
'env' => 'production', // values : (local | production)
'merchant_id' => 'YOUR_MERCHANT_ID',
'merchant_key' => 'YOUR_MERCHANT_KEY',
'merchant_website' => 'YOUR_WEBSITE',
'channel' => 'YOUR_CHANNEL',
'industry_type' => 'YOUR_INDUSTRY_TYPE',
],

All the credentials mentioned are provided by Paytm after signing up as a merchant.

Step 4: Create Migration and Create Model

Now you need to create table name events and it’s migration, model file. So execute the following command on terminal or cmd:

php artisan make:model Event -m

Its command will create one model name Event and also create one migration file for the events table. After successfully run the command go to database/migrations file and put the below here :

<?php 
  
use Illuminate\Support\Facades\Schema; 
use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 
   
class CreateEventsTable extends Migration 
{ 
    /** 
     * Run the migrations. 
     * 
     * @return void 
     */ 
    public function up() 
    { 
        Schema::create('products', function (Blueprint $table) { 
            $table->increments('id'); 
            $table->string('name');
            $table->string('mobile_number');
            $table->integer('amount');
            $table->string('order_id');
            $table->string('status')->default('pending');
            $table->string('transaction_id')->default(0);
            $table->timestamps(); 
        }); 
    } 
   
    /** 
     * Reverse the migrations. 
     * 
     * @return void 
     */ 
    public function down() 
    { 
        Schema::dropIfExists('events'); 
    } 
} 

Next, migrate the table using the below command.

php artisan migrate

Now, add the fillable property inside the Event.php file.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Event extends Model
{
  protected $fillable = ['name','mobile_number',
                         'amount','status',
                       'order_id','transaction_id'];
}

Step 5: Define Route

Now, you need to define routes in web.php. So, visit to routes directory and open web.php.

Then add the following routes into it:

use App\Http\Controllers\EventController;

Route::get('event', [EventController::class, 'bookEvent']);
Route::post('payment', [EventController::class, 'eventOrderGen']);
Route::post('payment/status', [EventController::class, 'paymentCallback']);

Step 6: Create Controller

Once you have defined routes in web.php. Now, execute the following command on the terminal to create the controller name EventController:

php artisan make:controller EventController

Then visit app/HTTP/Controller/EventController and add the following code into it:

<?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Event;
use PaytmWallet;


class EventController extends Controller
{


    /**
     * Redirect the user to the Payment Gateway.
     *
     * @return Response
     */
    public function bookEvent()
    {
        return view('book_event');
    }


    /**
     * Redirect the user to the Payment Gateway.
     *
     * @return Response
     */
    public function eventOrderGen(Request $request)
    {
     $this->validate($request, [
          'name' => 'required',
          'mobile_no' =>'required|numeric|digits:10|unique:events,mobile_number',
        ]);

        $input = $request->all();
        $input['order_id'] = rand(1111,9999);
        $input['amount'] = 50;

        Event::insert($input);

        $payment = PaytmWallet::with('receive');
        $payment->prepare([
          'order' => $input['order_id'],
          'user' => 'user id',
          'mobile_number' => $request->mobile_number,
          'email' => $request->email,
          'amount' => $input['amount'],
          'callback_url' => url('payment/status')
        ]);
        return $payment->receive();
    }

    /**
     * Obtain the payment information.
     *
     * @return Object
     */
    public function paymentCallback()
    {
        $transaction = PaytmWallet::with('receive');

        $response = $transaction->response();

        if($transaction->isSuccessful()){
          Event::where('order_id',$response['ORDERID'])->update(['status'=>'success', 'payment_id'=>$response['TXNID']]);

          dd('Payment Successfully Credited.');

        }else if($transaction->isFailed()){
          Event::where('order_id',$order_id)->update(['status'=>'failed', 'payment_id'=>$response['TXNID']]);
          dd('Payment Failed. Try again lator');
        }
    }    
}

Step 7: Create Blade View file

In this step, you need to create blade views file, Go to app/resources/views/ and create one file name event.blade.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Paytm Payment Gateway Integrate - Tutsmake.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
    <style>
        .mt40{
            margin-top: 40px;
        }
    </style>
</head>
<body>
  
<div class="container">

<div class="row">
    <div class="col-lg-12 mt40">
        <div class="card-header" style="background: #0275D8;">
            <h2>Register for Event</h2>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Whoops!</strong> Something went wrong<br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ url('payment') }}" method="POST" name="paytm">
    {{ csrf_field() }}
  
     <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <strong>Name</strong>
                <input type="text" name="name" class="form-control" placeholder="Enter Name">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <strong>Mobile Number</strong>
                <input type="text" name="mobile_number" class="form-control" placeholder="Enter Mobile Number">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <strong>Email Id</strong>
                <input type="text" name="email" class="form-control" placeholder="Enter Email id">
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <strong>Event Fees</strong>
                <input type="text" name="amount" class="form-control" placeholder="" value="100" readonly="">
            </div>
        </div>
        <div class="col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
   
</form>
</div>
   
</body>
</html>

Step 8: Start Development Server

In this step, you will use the PHP artisan serve command. It will start your server locally

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now you are ready to run our example so run bellow command to quick run.

http://localhost:8000/event

Or direct hit in your browser

http://localhost/blog/public/event

Here is the testing Card Credentials:

 Card No : 4242424242424242
Month : any future month
Year : any future Year
CVV : 123
Password : 123123

Conclusion

In this tutorial, you have learned how to integrate paytm payment gateway in the laravel Application.

If you found any invalid checksum issue in this laravel paytm package. Go to App/vendor/anandsiddharth/laravel-paytm-wallet/lib/encdec_paytm.php file. Next, file the function checkString_e() and replace the function to below code here:

 function checkString_e($value) {
$myvalue = ltrim($value);
$myvalue = rtrim($myvalue);
if (in_array($myvalue, ['null', 'NULL']))
$myvalue = '';
return $myvalue;
}

after putting the code and run your project again. if you still found this issue contact on paytm customer support and active your wallet credential.

Recommended Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *