Payment gateways are essential for any e-commerce platform, allowing seamless and secure transactions. This guide will show you how to integrate Moneris Payment Gateway in Codeigniter 4, ensuring a smooth experience for your users.

Codeigniter 4 Payment Gateway -  Integrate Moneris  Payment Gateway

Table Of Content

1 Prerequisites

1.) PHP version of 8.2
2.) MySql
3.) Moneris Merchant Resource Center Account

2 Introduction

In this article, I will guide you on how to integrate Moneris Payment Gateway with your Codeigniter 4 application.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

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

composer create-project codeigniter4/appstarter ci-4-moneris-payment

Then, navigate to your project directory:

cd ci-4-moneris-payment

3.2 Configure MySql Database

Edit the .env file to define the database credentials for Codeigniter 4 Payment Gateway transactions.

database.default.hostname = localhost
database.default.database = codeigniter_4
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306

4 Add Payment Gateway Library

4.1 Add Moneris Library

Download the Moneris library files and upload them under the App/Libraries/Moneris folder.

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 Dashboard
 Moneris Merchant Resource Center Dashboard

6 Configure Moneris Credentials

6.1 Add the Moneris API Credentials in .env

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

MONERIS_STORE_ID=Your Store ID
MONERIS_API_TOKEN=Your Store API Token

7 Create Migration and Model

Create a migration to store payment responses from the Moneris Payment Gateway. Run the following commands:

php spark make:model PaymentModel

open the created model at app/Models/PaymentModel.php. Inside the file you can see configuration options, you can read the documentation to further learn about its configuration options. We will now update the configs: app/Models/PaymentModel.php

<?php
namespace App\Models;

use CodeIgniter\Model;

class PaymentModel extends Model
{
    protected $table            = 'payments';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
}

After creating the model, we will then create a migration file. Run this below command.

php spark make:migration AddPayment

Open the created migration file on app/Database/Migrations/ and paste these codes:

<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddPayment extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'BIGINT',
                'constraint' => 255,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'txn_number' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'receipt_id' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'referenc_num' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'user_email' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'amount' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'message' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'created_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('payments');
    }

    public function down()
    {
        $this->forge->dropTable('payments');
    }
}

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

php spark migrate

8 Create New Controller - MonerisController

Create the MonerisController and define the methods index and store to process payments using Moneris Payment Gateway Codeigniter sample code.

php spark make:controller MonerisController

app/Controllers/MonerisController.php

<?php
namespace App\Controllers;

use App\Libraries\Moneris\Moneris;
use App\Libraries\Moneris\Transaction;
use App\Libraries\Moneris\CofInfo;
use App\Libraries\Moneris\MpgRequest;
use App\Libraries\Moneris\MpgHttpsPost;
use App\Libraries\Moneris\HttpsPost;
use App\Libraries\Moneris\MpgResponse;
use App\Libraries\Moneris\MpgAvsInfo ;
use App\Libraries\Moneris\MpgCvdInfo ;
use App\Models\PaymentModel;

class MonerisController extends BaseController
{

    private $paymentModel;

    public function __construct()
    {
        $this->paymentModel = new PaymentModel();
    }

    public function index(): string
    {
		return view('checkout');
    }
	public function store()
    {
        $data=array();
        $data=$_REQUEST;
     /************************ Request Variables ***************************/
 $store_id=env('MONERIS_STORE_ID');
 $api_token=env('MONERIS_API_TOKEN');
/********************* Transactional Variables ************************/
$type='purchase';
$order_id='ord-'.date("dmy-G:i:s");
$cust_id='CUST'.rand(0,1000);
$amount=number_format($data['amount'],2);
$pan=$data['cardit_card_number'];
$expiry_date=$data['expiry_month'].$data['expiry_year'];		//December 2008
$crypt='7';
/************************** AVS Variables *****************************/
$avs_street_number = $data['street_number'];
$avs_street_name = $data['street_name'];
$avs_zipcode = $data['zipcode'];
$avs_email = $data['email'];
$avs_hostname = 'www.getsamplecode.com';
$avs_browser = 'Mozilla';
$avs_shiptocountry = 'Canada';
$avs_merchprodsku = '123456';
$avs_custip = $_SERVER['REMOTE_ADDR'];
$avs_custphone = $data['custphone'];
/************************** CVD Variables *****************************/
$cvd_indicator = '1';
$cvd_value = $data['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 = $this->paymentModel->save([
                '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

Add the routes for Moneris payment processing in the app/Config/Routes.php file:

$routes->get('payment', 'MonerisController::index');  
$routes->post('moneris-payment', 'MonerisController::store');

10 Create Payment View File

Develop a payment form in app/Views/payment.php to collect user payment details.

  <!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 Codeigniter 4 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">
  
   <?php if (session()->getFlashdata('message')) : ?>
                              <div 
                                  style="color: green;
                                      border: 2px green solid;
                                      text-align: center;
                                      padding: 5px;margin-bottom: 10px;">
                                  Payment Successful!
                              </div>
                          <?php 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="moneris-payment" >
            
              <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>
      
  
      
      <script type="text/javascript" src="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/js/dist/search/search.min.js"></script>
      
  
  </body>
  </html>

11 Folder Structure

Here’s the folder structure for the project:

12 Run Laravel Server to Test the App

Run the server and visit http://localhost:8080/index.php/payment to test the Moneris Payment Gateway Codeigniter sample code integration.

php spark serve

13 Conclusion

That’s all! The Moneris Payment Gateway integration in Codeigniter 4 is complete. You can now process secure payments in your application.

Reference URL

Tags