Paytm payment gateway integration with laravel 5.4

By | December 9, 2019

Hello Coders !!
This tutorial is about the Paytm payment gateway integration with laravel 5.4 with Laravel’s latest framework. So you can follow step by step to integrate paytm payment gateway integration in fresh Laravel. Also, if you want to integrate into existing code then just follow after the installation step.

So the first step is to install the latest laravel 5.4

Step 1: Install Laravel 5.4

Open your terminal and run below command to install Laravel.

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

You just need to open the terminal and reach up to your working directory and paste this command and this command will create the folder name “paytm” and fresh laravel will be installed there.

Now add the database connection values in .env file. You will find this file in the root path and add database connection values in these parameters.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=paytm
DB_USERNAME=root
DB_PASSWORD=*****

For in detail laravel scratch installation you can follow this tutorial Install Laravel. This will help you with laravel installation for a beginner.

Step 2: Install paytm package


We will use the GitHub repository of “anandsiddharth/laravel-paytm-wallet”. Now we will run this command in the terminal inside the installed laravel root path.

composer require anandsiddharth/laravel-paytm-wallet

After you installed successfully this package. Now you need to open the file “config/app.php” and add this service provider at the end of each service.

'providers' => [
	....
Anand\LaravelPaytmWallet\PaytmWalletServiceProvider::class,
],

'aliases' => [
	....
	'PaytmWallet' => Anand\LaravelPaytmWallet\Facades\PaytmWallet::class,
],

Now, we have added the packages, service providers and aliases so now we will add the configuration of API key and ID inside file “config/services.php” like a below-shown command.

<?php
return [
    ......
//Already exist command, Add below this code

    'paytm-wallet' => [
        'env' => 'local', // values can be "local" or "production"
        'merchant_id' => env('YOUR_MERCHANT_ID'),
        'merchant_key' => env('YOUR_MERCHANT_KEY'),
        'merchant_website' => env('YOUR_WEBSITE'),
        'channel' => env('YOUR_CHANNEL'),
        'industry_type' => env('YOUR_INDUSTRY_TYPE'),
    ],
];

So you can see that variables values are coming from env file so we will add these values in our .env file that is placed in root.

And to get this Merchant Id and Merchant key you just need to visit this site for Paytm payment gateway integration https://dashboard.paytm.com/ and after login visit here https://dashboard.paytm.com/next/apikeys and generate this ID and key and paste here.

YOUR_MERCHANT_ID=DIY12386817555501617
YOUR_MERCHANT_KEY=bKMfNxPPf_QdZppa
YOUR_WEBSITE=DIYtestingweb
YOUR_CHANNEL=WEB
YOUR_INDUSTRY_TYPE=Retail

Step 3: Create an Event Registration Table and Model

Let’s create the table “event_registration” for PayPal payment logs.

Run below command in a terminal for creating a table.

php artisan make:migration create_event_registration_table

If you found any difficulties running this command then once again run the step 2 command.

After the above table creating command run you will find the table migration file in the path “database/migrations“. Currently, as per my setup, my file name is “2019_12_08_114319_create_event_registration_table.php” so now open this file and add some needed attributes after that this file will now look like this.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateEventRegistrationTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('event_registration', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('mobile_no');
            $table->text('address');
            $table->tinyInteger('status')->default(0);
            $table->integer('fee');
            $table->string('order_id');
            $table->string('transaction_id')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('event_registration');
    }
}

After adding these attributes now run this below command to migrate this table in the database.

php artisan migrate

This will create the table in the MySQL database.

Step 4: Create Model file

Let’s create the model file for table “event_registration”

For this let’s run this below command.

php artisan make:model EventRegistration --migration

The created file will look like this.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class EventRegistration extends Model
{
    //
}

After updating the file it will look like this.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class EventRegistration extends Model
{

    protected $table = 'event_registration';

    protected $fillable = ['name','mobile_no','address','status','fee','order_id','transaction_id'];

}

Step 4: Create Web and API Route

Let’s add some routes in web.php and api.php

web.php file

<?php

Route::get('/', function () {
    return view('welcome');
});

Route::get('event-registration', 'OrderController@register');
Route::post('payment', 'OrderController@order');

api.php file

<?php
Route::post('payment/status', 'OrderController@paymentCallback');

Step 5: Create Controller file

run below command for creating a controller file

php artisan make:controller OrderController

This command will create the controller file inside the “app\http\controllers” folder with the name “OrderController.php“.

so after update the file and after add some functions the file will look like this.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class OrderController extends Controller
{
    /**
     * Redirect the user to the Payment Gateway.
     *
     * @return Response
     */
    public function register()
    {
        return view('register');
    }


    /**
     * Redirect the user to the Payment Gateway.
     *
     * @return Response
     */
    public function order(Request $request)
    {


        $this->validate($request, [
            'name' => 'required',
            'mobile_no' => 'required|numeric|digits:10|unique:event_registration,mobile_no',
            'address' => 'required',
        ]);


        $input = $request->all();
        $input['order_id'] = $request->mobile_no.rand(1,100);
        $input['fee'] = 50;


        EventRegistration::create($input);


        $payment = PaytmWallet::with('receive');
        $payment->prepare([
          'order' => $input['order_id'],
          'user' => 'user@123',
          'mobile_number' => 'your paytm number',
          'email' => 'your paytm email',
          'amount' => $input['fee'],
          'callback_url' => url('api/payment/status')
        ]);
        return $payment->receive();
    }


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


        $response = $transaction->response();
        $order_id = $transaction->getOrderId();


        if($transaction->isSuccessful()){
          EventRegistration::where('order_id',$order_id)->update(['status'=>2, 'transaction_id'=>$transaction->getTransactionId()]);


          dd('Payment Successfully Paid.');
        }else if($transaction->isFailed()){
          EventRegistration::where('order_id',$order_id)->update(['status'=>1, 'transaction_id'=>$transaction->getTransactionId()]);
          dd('Payment Failed.');
        }
    }    
}

Step 6: Create a view file

We will create the view file inside the resources/view folder with the name register.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5.4 - Payment gateway using Paytm</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>


<div class="container">
    <div class="panel panel-primary" style="margin-top:30px;">
        <div class="panel-heading"><h2 class="text-center">Laravel 5.4 - Payment gateway using Paytm</h2></div>
        <div class="panel-body">
            <form action="{{ url('payment') }}" class="form-image-upload" method="POST" enctype="multipart/form-data">


                {!! csrf_field() !!}


                @if (count($errors) > 0)
                    <div class="alert alert-danger">
                        <strong>Whoops!</strong> There were some problems with your input.<br><br>
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif


                <div class="row">
                    <div class="col-md-12">
                        <strong>Name:</strong>
                        <input type="text" name="name" class="form-control" placeholder="Name">
                    </div>
                    <div class="col-md-12">
                        <strong>Mobile No:</strong>
                        <input type="text" name="mobile_no" class="form-control" placeholder="Mobile No.">
                    </div>
                    <div class="col-md-12">
                        <strong>Address:</strong>
                        <textarea class="form-control" placeholder="Address" name="address"></textarea>
                    </div>
                    <div class="col-md-12">
                        <br/>
                        <div class="btn btn-info btn-block">
                            Event Fee : 50 Rs/-
                        </div>
                    </div>
                    <div class="col-md-12">
                        <br/>
                        <button type="submit" class="btn btn-success btn-block">Pay to PatTM</button>
                    </div>
                </div>


            </form>
        </div>
    </div>
</div>


</body>
</html>

Now you are ready to go. You are all set now you just need to run this page on the browser and you are done.

Just run this http://localhost:8000/event-registration or http://{your-domain}/event-registration. As per my setup, it is http://paytm.test/event-registration.

Paytm register fee form

It will look like this.

So this is the tutorial about the Paytm payment gateway integration with Laravel 5.4 with all the steps.

Please share the link if you like this article and also let us know in the comment if you have any queries. Happy Coding !!

Here is the GITHUB link for the whole source code!

Leave a Reply

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