Share
Explore

icon picker
PortPos Class

This example here is for Laravel

Class Overview

The PortPos class is designed to interact with the PortPos payment gateway API. It supports operations such as generating invoices, validating IPN (Instant Payment Notification), and retrieving invoice details. This class handles the communication with the PortPos API endpoints and simplifies the integration process.

Data Flow

Untitled Diagram (3).jpg

Initialization

Generating the PortPos App and Secret

go logged in with your user name or password
go the the Applications >Add Application
select your merchant, provide a name to the key, hit the save button we will get the app and secret key save it for future use.

public function __construct($appKey, $secretKey, $mode)
Initializes a new instance of the PortPos class.
Parameters:
$appKey (string): The application key provided by PortPos for API access. Default is null.
$secretKey (string): The secret key provided by PortPos for securing API communication. Default is null.
$mode (string): Determines the API environment. Accepts 'sandbox' for testing and 'production' for live transactions. Default is 'sandbox'.

Example
$appKey = env('PORTPOS_APP_KEY');
$secretKey = env('PORTPOS_SECRET_KEY');
$mode = "sandbox";
$portPos = new PortPos($appKey, $secretKey, $mode);

Generate Invoice

public function generateInvoice(array $data)
Generates a new invoice using the PorPos API.
Parameters:
$data (array): An associative array containing the invoice data.
[
"order" => [
"amount" => 100,
"currency" => "BDT",
"redirect_url" => "http://localhost:8000/thank-you",
"ipn_url" => "http://localhost:8000/ipn",
"reference" => "PAY1234",
"validity" => 900
],
"product" => [
"name" => "Product Title", // This title displyed over the payment page
"description" => "Product Descriptions", // This customer can see from payment page
],
"billing" => [
"customer" => [
"name" => "Jhon Doe",
"email" => "email@example.com",
"phone" => "8801710000000",
"address" => [
"street" => "Road 06, Gulshan1,",
"city" => "Dhaka",
"state" => "Dhaka",
"zipcode" => 1212,
"country" => "BGD"
]
]
],
"shipping" => [
"customer" => [
"name" => "Jhon Doe",
"email" => "email@example.com",
"phone" => "8801710000000",
"address" => [
"street" => "Road 06, Gulshan1,",
"city" => "Dhaka",
"state" => "Dhaka",
"zipcode" => 1212,
"country" => "BGD"
]
]
],
"customs" => [
["value_a" => "Test 1"],
['value_b' => "Test 2"]
]
]
Returns: The API response as an object on success, or false on failure. The response typically includes invoice details such as the invoice ID, status, and payment information.

IPN Validate

public function ipnValidate($invoiceId, $amount)
Validates an IPN (Instant Payment Notification) received from PortPos.
Parameters:
$invoiceId PortPos InvoiceId (string): Provide the PortPos Invoice Id
$amount (float): The PortPos Invoice amount

Returns: The API response as an object on success, or false on failure. This method is used to verify that the payment notification received is valid and matches the expected invoice details.

Retrieve Invoice


public function getInvoice($invoiceId)

Retrieves details of an existing invoice from the PortPos API.
Parameters:
$invoiceId (string): The unique identifier of the invoice to retrieve.
Returns: The API response as an object on success, or false on failure. The response includes comprehensive invoice details such as the amount, status, payer information, etc.

Set Mode

public function setMode($mode)

Sets the API mode for subsequent requests.
Parameters:
$mode (string): The mode of operation. Accepts 'sandbox' for testing purposes or 'production' for real transactions.
No return value.
PortPos Service Class
<?php

namespace App\Services; //modify the namespace accroding to your

use Exception;
use Illuminate\Support\Facades\Http;

class PortPos
{

private $_appKey = "";
private $_secretKey = "";

public $mode = "sandbox";

private $config_data = [
'sandbox' => [
'invoice_endpoint' => 'https://api-sandbox.portpos.com/payment/v2/invoice/',
'ipn_endpoint' => 'https://api-sandbox.portpos.com/payment/v2/invoice/ipn/',
],
'production' => [
'invoice_endpoint' => 'https://api.portpos.com/payment/v2/invoice/',
'ipn_endpoint' => 'https://api.portpos.com/payment/v2/invoice/ipn/',
],
];

protected $_params = array();

public function __construct($appKey = null, $secretKey = null, $mode = 'sandbox')
{
if (!empty($appKey)) {
$this->_setAppKey($appKey);
}

if (!empty($secretKey)) {
$this->_setSecretKey($secretKey);
}

$this->setMode($mode);
}

public function generateInvoice($data)
{
// $data = json_encode($data);
$this->_params = $data;

$url = $this->config_data[$this->mode]['invoice_endpoint'];

return $this->_process("post", $url);
}

public function ipnValidate($invoiceId,$amount)
{
$this->_params = [];
$url = $this->config_data[$this->mode]['ipn_endpoint'] . $invoiceId . '/' . $amount;
return $this->_process("post", $url);
}

public function getInvoice($invoiceId)
{
$url = $this->config_data[$this->mode]['invoice_endpoint'] . $invoiceId;
return $this->_process("get", $url);
}

public function setMode($mode)
{
$this->mode = $mode;
}

protected function _setAppKey($appKey)
{
$this->_appKey = $appKey;
}

protected function _setSecretKey($secretKey)
{
$this->_secretKey = $secretKey;
}

private function _process($method = "get", $url = null)
{
$headers['Authorization'] = 'Bearer ' . base64_encode($this->_appKey . ":" . md5($this->_secretKey . time()));
$headers['Content-Type'] = 'application/json';
return $this->_request($method, $headers, $url);
}

private function _request($method, $headers = [], $url = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

if ($method == "post") {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->_params));
}

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
// dump($response);
$info = curl_getinfo($ch);
curl_close($ch);
if (substr($info['http_code'], 0, 2) == 20 && !empty($response)) {
return json_decode($response);
} else {
return false;
}
}
}

Example

Generating and redirect to Payment Page

$portPos = new PortPos('your_app_key', 'your_secret_key','sandbox');
$invoiceData = [
"order" => [
"amount" => $amount,
"currency" => $currency,
"redirect_url" => "http://localhost:8000/thank-you",
"ipn_url" => "http://localhost:8000/ipn",
"reference" => $transaction_id,
"validity" => 10000
],
"product" => [
"name" => "Payment for Airforce",
"description" => "Payment taking for airforce",
],
"billing" => [
"customer" => [
"name" => $name,
"email" => $email,
"phone" => $phone,
"address" => [
"street" => "Dhaka, Bangladesh",
"city" => "Dhaka",
"state" => "Dhaka",
"zipcode" => 1207,
"country" => "BGD"
]
]
],
"customs" => [
["value_a" => $course->name ?? ""],
['value_b' => $user->branch->name],
['value_c' => $user->post->name],
['value_d' => $user->district_name->name]
]
];
$response = $portPos->generateInvoice($invoiceData);

if ($response) {
// Handle successful invoice generation the redirected to the data->action->url
return Redirect::to($res->data->action->url);
} else {
// Handle failure
}


Handle Callback/Success/Fail Page

Add IPN route
//routes/web.php
Route::get('/thank-you', [YourPaymentController::class, 'callBack']);

Handle in Controller
//app/Http/Controllers/TestController.php
<?php

namespace App\Http\Controllers;

use App\Services\PortPos;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use stdClass;

class YourPaymentController extends Controller
{
public function callBack(Request $request)
{
$invoiceId = $request->query("invoice");
$status = $request->query("status");
if($status !=="ACCEPTED"){
return view("payment-failed-view");
}

if ($user->status !== 'pending') {
return view("payment-success-or-failed-view"); //show payment success or failed view depending on your order status
}

$portPos = new PortPos('your_app_key', 'your_secret_key','sandbox');
$res = $portPos->getInvoice($invoiceId);
if(!$res){
return view("payment-failed-view");
}

if($res->status !== "success" || $res->order->status !== "ACCEPTED"){
$user->update(['status' => 'cancel']); //update the status with failed payment
return view("payment-failed-view");
}
$user->update(['status' => 'success']); //finally update success status
return view("payment-success-view");
}
}


Handle IPN

Add IPN route
//routes/web.php
Route::get('/ipn', [YourPaymentController::class, 'ipnListener']);

Exclude from CSRF Token
//app/Http/Middleware/VerifyCsrfToken.php
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
'/ipn'
];

Handle in Controller
//app/Http/Controllers/TestController.php
<?php

namespace App\Http\Controllers;

use App\Services\PortPos;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use stdClass;

class YourPaymentController extends Controller
{
public function ipnListener(Request $request)
{
$status = $request->status;
$transaction_id = $request->reference; //use this reference id to findout the user and the order details
if($status !=="ACCEPTED"){
return ['message'=>"not a accepted invoice"];
}
if ($user->status !== 'pending') {
return ['message' =>'Transaction is already successfully Completed!'];
}

$portPos = new PortPos('your_app_key', 'your_secret_key','sandbox');
$res = $portPos->ipnValidate($request->invoice,$request->amount);
if(!$res){
return ['message'=>"IPN not reachable"]; //this response recorder PortPos Side and can be check for later reference
}
if(
$res->status == "success" &&
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.