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 Codeigniter 4 application, ensuring a seamless payment experience for your users.
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 am going to show you how to Integrate Moneris Payment Gateway to 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
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.
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 file's from this
link , and create "Moneris" Folder under "App/Libraries" folder and upload all files.
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.
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
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 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
Now create a controller "MonerisController" and add index() and store() methods
Use the following command to Create Controller.
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
Define routes for the MonerisController in the Routes.php file
app/Config/Routes.php
$routes->get('payment', 'MonerisController::index');
$routes->post('moneris-payment', 'MonerisController::store');
10 Create Payment View File
Create View "payment.php" File to Show Form
app/Views/checkout.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 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
Moneris.php
CofInfo.php
HttpsPost.php
MpgAvsInfo.php
MpgCvdInfo.php
MpgHttpsPost.php
MpgRequest.php
MpgResponse.php
Transaction.php
12 Run Laravel Server to Test the App
Use the following command to Test the App.
php spark serve
Visit the URL
http://localhost:8080/index.php/payment
13 Conclusion
That’s all we need to do.
Now the Moneris Payment Gateway Integration completed in Codeigniter 4 application. You can try it out.
Tags