Payment gateways are a crucial element of any e-commerce store, enabling smooth and secure online transactions. This tutorial will guide you through the process of integrating Moneris into your Laravel 11 application, ensuring a seamless payment experience for your users.

Laravel 11 Payment Gateway -  Integrate Moneris  Payment Gateway

Table Of Content

1 Prerequisites

1.) PHP version of 8.2
2.) MySql
3.) Moneris Payment Gateway

2 Introduction

In this article, I am going to show you how to Integrate Moneris Payment Gateway to your Laravel application.

3 Create / Install a Laravel Project

3.1 Install Laravel Project

First, make sure your computer has a composer.
Use the following command to install new Laravel Project.

composer create-project laravel/laravel moneris-payment-app

Then, navigate to your project directory:

cd moneris-payment-app

3.2 Configure MySql Database

Upon Successful Transaction, the payment trasactions data will be stored in the database. This process involves accessing the .env file to input and define the database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel11
DB_USERNAME=root
DB_PASSWORD=

4 Add Payment Gateway Library

4.1 Add Moneris Library

Download the Moneris Library file's from this link, and create "Libraries" Folder under "App" folder. Next add this Library Path in "composer.json"

"autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/",
            "App\\Libraries\\": "app/libraries/"
        }
    },
Now run the following command

composer dump-autoload

5  Get Moneris Payment Gateway Configuration Keys

5.1 Login into Moneris Merchant Resource Center

Login into Moneris Merchant Resource Center using "Username","Store ID" and Password

5.2 Get Moneris API Token

Inside the Moneris Gateway merchant account, you need to obtain an API Token. Go to My Account and click on the ADMIN. Then click on Store Settings and click on the button to generate an API Token.

 Moneris Merchant Resource Center Dashboard
 Moneris Merchant Resource Center Store Setting
 Moneris Merchant Resource Center API Token

6 Configure Moneris Credentials

6.1 Add the Moneris API Credentials in .env

Insert the Store ID and API Token, Which we obtained from previous step MONERIS_STORE_ID and MONERIS_API_TOKEN.

MONERIS_STORE_ID =Your Store ID
MONERIS_API_TOKEN=Store API Token

7 Create Migration and Model

Now, you need to create migration for new table payments to store the response of Moneris API. Also, create a model Payment for the same. Run this below command.

php artisan make:model Payment —migration

In the generated new migration file, update the up and down methods as described below:

database/migrations/2024_05_22_163057_payment.php


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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('payments',function(Blueprint $table) {
            $table->increments('id');
            $table->string('txn_number');
            $table->string('receipt_id');
            $table->string('referenc_num');
            $table->string('user_email');
            $table->string('amount');
            $table->longText('message');
            $table->timestamps();
          });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};

Use the following command to run the migration to update your database.

php artisan migrate

app/Models/Payment.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    use HasFactory;
    protected $table = 'payments';
    protected $guarded = ['id'];
}


8 Create New Controller - MonerisController

Now create a controller "MonerisController" and add index() and store() methods
Use the following artisan command to Create Controller.

php artisan make:controller MonerisController

app/Http/Controllers/MonerisController.php

<?php
namespace App\Http\Controllers;
use App\Libraries\Moneris;
use App\Libraries\Transaction;
use App\Libraries\CofInfo;
use App\Libraries\MpgRequest;
use App\Libraries\MpgHttpsPost;
use App\Libraries\HttpsPost;
use App\Libraries\MpgResponse;
use App\Libraries\MpgAvsInfo ;
use App\Libraries\MpgCvdInfo ;
use App\Models\Payment;
use App\Http\Requests;
use Illuminate\Http\Request;
use Redirect;
class MonerisController extends Controller
{
    public function index()
    {
		return view('payment-moneris');
    }
	public function store(Request $request)
    {
//   dd($request);
     /************************ Request Variables ***************************/
 $store_id=env('MONERIS_STORE_ID');
 $api_token=env('MONERIS_API_TOKEN');
//exit;
/********************* Transactional Variables ************************/
$type='purchase';
$order_id='ord-'.date("dmy-G:i:s");
$cust_id='CUST'.rand(0,1000);
$amount=number_format($request->amount,2);
$pan=$request->cardit_card_number;
$expiry_date=$request->expiry_month.$request->expiry_year;		//December 2008
$crypt='7';
/************************** AVS Variables *****************************/
$avs_street_number = $request->street_number;
$avs_street_name = $request->street_name;
$avs_zipcode = $request->zipcode;
$avs_email = $request->email;
$avs_hostname = 'www.getsamplecode.com';
$avs_browser = 'Mozilla';
$avs_shiptocountry = 'Canada';
$avs_merchprodsku = '123456';
$avs_custip = $_SERVER['REMOTE_ADDR'];
$avs_custphone = $request->custphone;;
/************************** CVD Variables *****************************/
$cvd_indicator = '1';
$cvd_value = $request->card_cvv;;
/********************** AVS Associative Array *************************/
$avsTemplate = array(
					 'avs_street_number'=>$avs_street_number,
                     'avs_street_name' =>$avs_street_name,
                     'avs_zipcode' => $avs_zipcode,
                     'avs_hostname'=>$avs_hostname,
					 'avs_browser' =>$avs_browser,
					 'avs_shiptocountry' => $avs_shiptocountry,
					 'avs_merchprodsku' => $avs_merchprodsku,
					 'avs_custip'=>$avs_custip,
					 'avs_custphone' => $avs_custphone
                    );
/********************** CVD Associative Array *************************/
$cvdTemplate = array(
					 'cvd_indicator' => $cvd_indicator,
                     'cvd_value' => $cvd_value
                    );
/************************** AVS Object ********************************/
$mpgAvsInfo = new mpgAvsInfo ($avsTemplate);
/************************** CVD Object ********************************/
$mpgCvdInfo = new mpgCvdInfo ($cvdTemplate);
/***************** Transactional Associative Array ********************/
$txnArray=array(
				'type'=>$type,
       			'order_id'=>$order_id,
       			'cust_id'=>$cust_id,
       			'amount'=>$amount,
       			'pan'=>$pan,
       			'expdate'=>$expiry_date,
       			'crypt_type'=>$crypt
          		);
/********************** Transaction Object ****************************/
$mpgTxn = new Transaction($txnArray);
/************************ Set AVS and CVD *****************************/
$mpgTxn->setAvsInfo($mpgAvsInfo);
$mpgTxn->setCvdInfo($mpgCvdInfo);
/************************ Request Object ******************************/
$mpgRequest = new mpgRequest($mpgTxn);
$mpgRequest->setProcCountryCode("CA"); //"US" for sending transaction to US environment
$mpgRequest->setTestMode(true); //false or comment out this line for production transactions
/*********************** HTTPS Post Object ****************************/
$mpgHttpPost  =new mpgHttpsPost($store_id,$api_token,$mpgRequest);
/*************************** Response *********************************/
$mpgResponse=$mpgHttpPost->getMpgResponse();

if($mpgResponse->getResponseCode()>50)
return redirect()->back()->with('error',$mpgResponse->getMessage());
else
{
$payment = Payment::create([
                'txn_number' => $mpgResponse->getTxnNumber(),
                'receipt_id' => $mpgResponse->getReceiptId(),
                'referenc_num' => $mpgResponse->getReferenceNum(),
                'user_email' => $avs_email,
                'amount' => $mpgResponse->getTransAmount(),
                'message' => $mpgResponse->getMessage()
            ]);	
return redirect()->back()->with('message',"Payment Successful");
		}


    }
}
?>

9 Define a Route

Define routes for the MonerisController in the web.php file
routes/web.php

Route::get('payment', [MonerisController::class, 'index']);  
Route::post('moneris-payment', [MonerisController::class, 'store'])->name('moneris.payment.store');  

10 Create Payment Blade File

Create View "payment-moneris.blade.php" File to Show Form
resources/views/payment-moneris.blade.php


<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Simplify Your Online Payments With Laravel Moneris Payment Gateway Integration</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
   <link rel="stylesheet" href="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/css/dist/mdb5/standard/core.min.css">
   <link rel='stylesheet' id='roboto-subset.css-css'  href='https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/css/mdb5/fonts/roboto-subset.css?ver=3.9.0-update.5' type='text/css' media='all' />
</head>
 <body>
 <!-- Credit card form -->
 <div class="container-fluid">

 @if(session()->has('error'))
    <div class="alert alert-danger">
        {{ session()->get('error') }}
    </div>
@endif

@if(session()->has('message'))
    <div class="alert alert-success">
        {{ session()->get('message') }}
    </div>
@endif
  <div class="row">
  <div class="col-md-3"></div>
    <div class="col-md-6 mb-4">
      <div class="card mb-4">
        <div class="card-header py-3">
          <h5 class="mb-0">Customer details</h5>
        </div>
        <div class="card-body">
        <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!!route('moneris.payment.store')!!}" >
          {{ csrf_field() }}
            <div class="row mb-4">
              <div class="col">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="name" class="form-control" name="name" />
                  <label class="form-label" for="name">Name</label>
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col">
                <div data-mdb-input-init class="form-outline mb-4">
                  <input type="text" id="street_number" class="form-control" name="street_number" />
                  <label class="form-label" for="street_number">Street Number</label>
                </div>
                </div> 
                <div class="col">
                <div data-mdb-input-init class="form-outline mb-4">
                  <input type="text" id="street_name" class="form-control" name="street_name" />
                  <label class="form-label" for="street_name">Street Name</label>
                </div>
              </div>  
              </div>   
              <div class="row mb-4">
              <div class="col-6">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="zipcode" class="form-control" name="zipcode" />
                  <label class="form-label" for="zipcode">Zipcode</label>
                </div>
              </div>
            </div>
              <div class="row">
              <div class="col">
                <div data-mdb-input-init class="form-outline">
                  <input type="email" id="email" class="form-control" name="email" />
                  <label class="form-label" for="email">Email</label>
                </div>
            </div>
            <div class="col">
            <div data-mdb-input-init class="form-outline">
              <input type="text" id="custphone" class="form-control" name="custphone" />
              <label class="form-label" for="custphone">Phone</label>
            </div>
            </div>
            </div>
            <hr class="my-4" />
            <h5 class="mb-4">Payment</h5>
            <div class="row mb-4">
              <div class="col">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="name_on_card" class="form-control" name="name_on_card" />
                  <label class="form-label" for="name_on_card">Name on card</label>
                </div>
              </div>
              <div class="col">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="cardit_card_number" class="form-control" name="cardit_card_number" />
                  <label class="form-label" for="cardit_card_number">Credit card number</label>
                </div>
              </div>
            </div>
            <div class="row mb-4">
              <div class="col-3">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="expiry_month" class="form-control" name="expiry_month" />
                  <label class="form-label" for="expiry_month">Expiration Month</label>
                </div>
              </div>
              <div class="col-3">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="expiry_year" class="form-control" name="expiry_year" />
                  <label class="form-label" for="expiry_year">Expiration Year</label>
                </div>
              </div>
              <div class="col-3">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="card_cvv" class="form-control" name="card_cvv" />
                  <label class="form-label" for="card_cvv">CVV</label>
                </div>
              </div>
              <div class="col-3">
                <div data-mdb-input-init class="form-outline">
                  <input type="text" id="amount" class="form-control" name="amount" value="10.00" />
                  <label class="form-label" for="amount">Amount</label>
                </div>
              </div>
            </div>

            <button class="btn btn-primary btn-lg btn-block" type="submit">
              Pay Now
            </button>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-3"></div>
    
  </div>
  </div>
  <script type="text/javascript" src="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/js/dist/mdb5/standard/core.min.js"></script>
</body>
</html>

11 Folder Structure

12 Run Laravel Server to Test the App

Use the following artisan command to Test the App.

php artisan serve

Visit the URL http://127.0.0.1:8000

13 Conclusion

That’s all we need to do.
Now the Moneris Payment Gateway Integration completed in Laravel application. You can try it out.

Tags