How to integrate paytm payment gateway in laravel example

How to integrate paytm payment gateway in laravel example

As we know that paytm is fastest growing plateform to provies payment services. So here i will let you know how to integrate paytm payment gateway in laravel with an example.

Paytm provides digital payment methods and boomed after digital india movement. Most of the marchant accepts paytm payment. 

Here, in this example we will use a laravel package (“anandsiddharth/laravel-paytm-wallet”) to integrate paytm payment gateway in our laravel application.

So let’s start paytm integration process in our laravel application from scratch. You will need to just follow the steps as mentioned in this tutorial.  

Step 1: Install laravel

In this first step, we will create a fresh laravel application using the following command. If you don’t want to install new application you can also integrate into your existing application. You can jump directly to the next step otherwise just open your terminal and run the command as given below.

composer create-project --prefer-dist laravel/laravel test-app

Step 2: Install Package

For installing the desired package, you will just need to run the following composer command in your terminal. It will automatically dowload all the files required for this package in your application.

composer require anandsiddharth/laravel-paytm-wallet

After running the above command, you will need to setup some configurations for this package. So open config/app.php file and add provider and alias as given as under.

config/app.php

'providers' => [

  ....

  Anand\LaravelPaytmWallet\PaytmWalletServiceProvider::class,

],

'aliases' => [

  ....

  'PaytmWallet' => Anand\LaravelPaytmWallet\Facades\PaytmWallet::class,

],

Now we will need to add some other configuration like marchant id and key. So open config/services.php file and add the line of code as mentaioned below.

config/services.php

<?php


return [


    ......
    'paytm-wallet' => [
        'env' => 'local', // values : (local | 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'),
    ],


];

Now add these secret key date in the application’s environment file like below.

YOUR_MERCHANT_ID=DIY12XXXXXXXXXXXXXXXX
YOUR_MERCHANT_KEY=bKXXXXXXXXXXX

YOUR_WEBSITE=XXXXXXXXX

YOUR_CHANNEL=WEB

YOUR_INDUSTRY_TYPE=Retail

Step 3: Create table and model

In this step, we will create customers table and Customer model using laravel migration. So open you terminal and run following artisan command to generate new migration.

php artisan make:migration create_customers_table

Now open migration file and add scema like below.

<?php


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


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


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop("customer");
    }
}

After the above, we will need to migrate this migration.

php artisan migrate

Now, create Customer.php model file under app directory.

app/Customer.php

<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class Customer extends Model
{
    protected $table = 'customers';


    protected $fillable = ['name','mobile','address','status','charges','order_id','transaction_id'];


    /* 
    status : 0 => progress, 1 => Fail, 2 => Successful
    */
}

Step 4: Create Routes

Here, we will create required routes for web and api as mentioned below.

routes/web.php

<?php


/*
|--------------------------------------------------------------------------
| 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('register', 'CustomerController@register');
Route::post('payment', 'CustomerController@payment');

Now open api.php route file and add the following route for capturing payment status.

routes/api.php

<?php


/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/


Route::post('payment/status', 'CustomerController@paymentCallback');

Step 5: Create Controller

As mentioned in the routes, we have used Customer Controller. So let’s create CustomerController.php file and add method as written in the routes.

app/Http/Controllers/CustomerController.php

<?php


namespace App\Http\Controllers;


use PaytmWallet;
use Illuminate\Http\Request;
use App\Customer;


class CustomerController 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 payment(Request $request)
    {


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


        $input = $request->all();
        $input['order_id'] = $request->mobile.rand(1,100);
        $input['charges'] = 100;


        Customer::create($input);


        $payment = PaytmWallet::with('receive');
        $payment->prepare([
          'order' => $input['order_id'],
          'user' => 'your paytm user',
          '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 View/Blade Files

Next, we will need to create view files which are basically blade templets for viewing the data in the web browser. Here we will create register.blade.php file.

resources/view/register.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel- 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:</strong>
                        <input type="text" name="mobile" class="form-control" placeholder="Mobile">
                    </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 Paytm</button>
                    </div>
                </div>


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


</body>
</html>

After doing all the above steps we have successfully integrated paytm payment gateway in our laravel application.

Now for showing what we have exactly done, we can run the following artisan command to serve the application on local environment.

php artisan serve

You can also read the article for integrating stripe payment gateway in the laravel application by clicking on the link below.

How to integrate stripe payment gateway in laravel application