PHPackages                             tamimiqbal/dgepay-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. tamimiqbal/dgepay-php

ActiveLibrary[Payment Processing](/categories/payments)

tamimiqbal/dgepay-php
=====================

PHP SDK for the DGePay Payment Gateway API (Bangladesh). Supports bKash, Nagad, and other MFS providers via DGePay aggregator.

v1.0.0(1mo ago)00MITPHPPHP &gt;=8.1

Since Mar 17Pushed 1mo agoCompare

[ Source](https://github.com/IamTIqbal/dgepay-php-client)[ Packagist](https://packagist.org/packages/tamimiqbal/dgepay-php)[ RSS](/packages/tamimiqbal-dgepay-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

DGePay PHP Client
=================

[](#dgepay-php-client)

⚠️ Disclaimer
This is an unofficial community-driven integration for DGePay.
This project is not affiliated with or endorsed by DGePay or Bangladesh Bank.

> **Developer:** [Tamim Iqbal](https://tamimiqbal.com) — IT Manager &amp; AI Developer

A complete PHP SDK for the **DGePay Payment Gateway API** (Bangladesh). Supports **bKash**, **Nagad**, and other MFS (Mobile Financial Service) providers through the DGePay payment aggregator.

Built from real-world production integration, with all the undocumented gotchas already handled.

[![PHP Version](https://camo.githubusercontent.com/83dd395020c37276225039739320f6c8e7e99963ab21ee3d09282cb48dad2a60/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d626c7565)](https://php.net)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

---

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Laravel Integration](#laravel-integration)
- [API Reference](#api-reference)
    - [Authentication](#authentication)
    - [Initiate Payment](#initiate-payment)
    - [Handle Callback](#handle-callback)
    - [Check Transaction Status](#check-transaction-status)
    - [Utilities](#utilities)
- [Payment Flow](#payment-flow)
- [Status Codes](#status-codes)
- [Gotchas &amp; Troubleshooting](#gotchas--troubleshooting)
- [Security Notes](#security-notes)
- [Testing](#testing)
- [License](#license)

---

Features
--------

[](#features)

- **Complete API coverage** — Authentication, payment initiation, callback handling, and transaction status checks
- **AES-128-ECB encryption** — Automatic payload encryption/decryption as required by DGePay
- **HMAC-SHA256 signatures** — Correct signature generation matching DGePay API documentation v1.9
- **Callback decryption** — Handles encrypted callback data with base64 `+` character fix
- **Laravel integration** — Service provider, facade, and config publishing out of the box
- **Framework-agnostic** — Works with any PHP 8.1+ project (uses cURL internally)
- **Production-tested** — Built from a live integration, with all edge cases and undocumented behaviors handled

---

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- `ext-curl` — For HTTP requests
- `ext-json` — For JSON encoding/decoding
- `ext-openssl` — For AES encryption/decryption

---

Installation
------------

[](#installation)

### Via Composer

[](#via-composer)

```
composer require tamimiqbal/dgepay-php
```

### Manual Installation

[](#manual-installation)

Clone or download the repository, then include the autoloader:

```
require_once 'path/to/dgepay-api/src/DgePay.php';
```

---

Quick Start
-----------

[](#quick-start)

```
use DgePay\DgePay;

// Initialize
$dgepay = new DgePay([
    'client_id'      => 'your_client_id',
    'client_secret'  => 'your_client_secret',
    'client_api_key' => 'your_api_key',
]);

// Create a payment
$orderId = DgePay::generateTransactionId(); // "DG20260317112339128"

$result = $dgepay->initiatePayment([
    'amount'      => 2499.00,
    'description' => 'Pro Plan - 1 Year',
    'orderId'     => $orderId,
    'redirectUrl' => 'https://yoursite.com/payment/callback',
]);

if ($result['success']) {
    // Redirect user to DGePay payment page
    header('Location: ' . $result['payment_url']);
    exit;
}
```

---

Laravel Integration
-------------------

[](#laravel-integration)

### Auto-Discovery

[](#auto-discovery)

If you're using Laravel 5.5+, the service provider and facade are auto-discovered.

### Manual Registration

[](#manual-registration)

Add to `config/app.php`:

```
'providers' => [
    DgePay\Laravel\DgePayServiceProvider::class,
],

'aliases' => [
    'DgePay' => DgePay\Laravel\Facades\DgePay::class,
],
```

### Publish Config

[](#publish-config)

```
php artisan vendor:publish --tag=dgepay-config
```

### Environment Variables

[](#environment-variables)

Add to your `.env` file:

```
DGEPAY_CLIENT_ID=your_client_id
DGEPAY_CLIENT_SECRET=your_client_secret
DGEPAY_CLIENT_API_KEY=your_api_key
DGEPAY_BASE_URL=https://apiv2.dgepay.net/dipon/v3
```

### Usage in Controllers

[](#usage-in-controllers)

```
use DgePay\DgePay;

class PaymentController extends Controller
{
    public function __construct(
        protected DgePay $dgepay,
    ) {}

    public function initiate(Request $request)
    {
        $result = $this->dgepay->initiatePayment([
            'amount'      => 2499.00,
            'description' => 'Pro Plan',
            'orderId'     => DgePay::generateTransactionId(),
            'redirectUrl' => route('payment.callback'),
        ]);

        if ($result['success']) {
            return redirect()->away($result['payment_url']);
        }

        return back()->with('error', $result['message']);
    }
}
```

---

API Reference
-------------

[](#api-reference)

### Authentication

[](#authentication)

```
$auth = $dgepay->authenticate();

if ($auth['success']) {
    echo $auth['access_token']; // JWT token
}
```

**How it works:**

- Sends HTTP Basic Auth header: `base64(client_id:client_secret)`
- POST body contains `client_id` and `client_secret`
- Returns a JWT access token used in subsequent requests

> **Note:** You don't need to call `authenticate()` manually. It's called automatically by `initiatePayment()` and `getTransactionStatus()`.

---

### Initiate Payment

[](#initiate-payment)

```
$result = $dgepay->initiatePayment([
    // Required
    'amount'      => 2499.00,          // Payment amount (BDT)
    'redirectUrl' => 'https://...',     // Where to redirect after payment
    'orderId'     => 'DG20260317...',   // Your unique transaction ID

    // Optional
    'description'           => 'Plan subscription',
    'payment_method'        => null,    // Force: "bKash", "Nagad", etc.
    'customer_token'        => null,    // Returning customer token
    'payee_information'     => null,    // Payee info
    'unique_user_reference' => '123',   // Your user ID
    'meta_data'             => [        // Up to 3 custom fields
        'custom_field_1' => 'pro',
        'custom_field_2' => 'user@example.com',
        'custom_field_3' => 'COUPON50',
    ],
]);
```

**Returns on success:**

```
[
    'success'        => true,
    'payment_url'    => 'https://checkout.dgepay.net/payment-methods?data=...',
    'transaction_id' => 'DG20260317112339128',
]
```

**Returns on failure:**

```
[
    'success' => false,
    'message' => 'Error description',
]
```

---

### Handle Callback

[](#handle-callback)

After payment, DGePay redirects the user to your `redirectUrl` with encrypted data:

```
https://yoursite.com/callback?data=

```

⚠️ **CRITICAL**: PHP converts `+` to spaces in query strings. You MUST fix this before decryption.

```
// Step 1: Get and fix the raw data
$rawData = str_replace(' ', '+', $_GET['data']);

// Step 2: Decrypt
$decrypted = $dgepay->decryptCallbackData($rawData);

// Step 3: Parse the result
$result = $dgepay->parseCallbackResult($decrypted ?? $_GET);

if ($result['is_success']) {
    // Payment successful!
    $orderId   = $result['unique_txn_id'];  // Your order ID
    $txnNumber = $result['txn_number'];     // DGePay txn number
    $method    = $result['payment_method']; // "bKash", "Nagad", etc.

    // RECOMMENDED: Verify with API before activating
    $status = $dgepay->getTransactionStatus($orderId);
    if ($status['success'] && $status['data']['status_code'] == 3) {
        // Verified! Activate the order.
    }
} elseif ($result['is_cancelled']) {
    // User cancelled
} else {
    // Payment failed
}
```

**Decrypted callback data structure:**

```
[
    'status_code'            => 3,                           // 3 = success, 8 = cancelled
    'customer_token'         => null,
    'unique_txn_id'          => 'DG20260317112339128',       // Your order ID
    'payment_method'         => 'bKash',
    'txn_number'             => '46629357',                  // DGePay txn number
    'third_party_txn_number' => 'TR0011ITaWLiz1773746629790', // MFS provider txn
    'message'                => 'TRANSACTION SUCCESS',
    'txn_id'                 => '42836aac54c4...',           // DGePay internal ID
    'amount'                 => 100,
    'created_date'           => 1773746629,                  // Unix timestamp
    'metadata'               => [
        'custom_field_1' => 'pro',
        'custom_field_2' => 'user@example.com',
        'custom_field_3' => 'COUPON50',
    ],
]
```

---

### Check Transaction Status

[](#check-transaction-status)

```
$result = $dgepay->getTransactionStatus('DG20260317112339128');

if ($result['success']) {
    $data = $result['data'];

    echo $data['status_code'];     // "3" = success
    echo $data['message'];         // "TRANSACTION SUCCESS"
    echo $data['txn_number'];      // Gateway transaction number
    echo $data['payment_method'];  // "bKash", "Nagad", etc.
    echo $data['amount'];          // Payment amount
}
```

---

### Utilities

[](#utilities)

#### Generate Transaction ID

[](#generate-transaction-id)

```
$txnId = DgePay::generateTransactionId();        // "DG20260317112339128"
$txnId = DgePay::generateTransactionId('PAY');    // "PAY20260317112339128"
```

#### Status Constants

[](#status-constants)

```
DgePay::STATUS_SUCCESS;    // "3"
DgePay::STATUS_CANCELLED;  // "8"

DgePay::isSuccessStatus('3');    // true
DgePay::isCancelledStatus('8');  // true
```

#### Encrypt/Decrypt Payloads

[](#encryptdecrypt-payloads)

```
$encrypted = $dgepay->encryptPayload(['key' => 'value']);
$decrypted = $dgepay->decryptPayload($encrypted);
```

#### Signature Generation

[](#signature-generation)

```
$signature = $dgepay->generateSignature($data);
```

#### Custom Logger

[](#custom-logger)

```
$dgepay->setLogger(function (string $level, string $message, array $context) {
    error_log("[{$level}] {$message}: " . json_encode($context));
});
```

---

Payment Flow
------------

[](#payment-flow)

```
┌──────────┐       ┌──────────┐       ┌──────────┐       ┌──────────┐
│  Your    │       │  DGePay  │       │  MFS     │       │  Your    │
│  Server  │       │  API     │       │ Provider │       │  Server  │
└────┬─────┘       └────┬─────┘       └────┬─────┘       └────┬─────┘
     │                  │                  │                   │
     │  1. authenticate │                  │                   │
     │─────────────────>│                  │                   │
     │  JWT token       │                  │                   │
     ││                  │                   │
     │  webview_url     │                  │                   │
     │                   │
     │                  │   User pays via  │                   │
     │                  │   bKash/Nagad    │                   │
     │                  │
