PHPackages                             born-mt/mita-gpg-sdk - 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. born-mt/mita-gpg-sdk

ActiveLibrary[Payment Processing](/categories/payments)

born-mt/mita-gpg-sdk
====================

PHP SDK for Malta Government Payment Gateway (GPG) API integration

1.0.1(6mo ago)116MITPHPPHP ^8.1|^8.2|^8.3

Since Nov 5Pushed 3mo agoCompare

[ Source](https://github.com/Born-MT/mita-gpg-sdk)[ Packagist](https://packagist.org/packages/born-mt/mita-gpg-sdk)[ RSS](/packages/born-mt-mita-gpg-sdk/feed)WikiDiscussions main Synced 1mo ago

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

Malta GPG SDK
=============

[](#malta-gpg-sdk)

[![CircleCI](https://camo.githubusercontent.com/90f03549ba57752ad6fb7918a70c1f457fb312369fe27c4a9222ed68eb137287/68747470733a2f2f636972636c6563692e636f6d2f67682f426f726e2d4d542f6d6974612d6770672d73646b2f747265652f6d61696e2e7376673f7374796c653d737667)](https://circleci.com/gh/Born-MT/mita-gpg-sdk/tree/main)[![PHP Version](https://camo.githubusercontent.com/cc9cdea9aa96b40a822425e981b0a030e3371202973c7d57b74e8e99834f81dc/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

A comprehensive PHP SDK for integrating with Malta's Government Payment Gateway (GPG) API. This package provides a clean, type-safe interface for processing payments through Malta's official payment infrastructure.

Features
--------

[](#features)

- **Complete API Coverage**: All GPG endpoints (Hosted Payment Page, Transactions, Reporting)
- **Type Safety**: Full PHP 8.1+ enums and typed properties
- **Payment Operations**: SALE, AUTH, CAPTURE, REFUND, VOID
- **Webhook Support**: Built-in signature verification and payload parsing
- **Exception Handling**: Comprehensive error handling with specific exceptions
- **Test Mode**: Built-in sandbox support
- **DTOs**: Clean data transfer objects for requests and responses
- **PSR Compliant**: Follows PHP standards and best practices
- **Framework Agnostic**: Use with Laravel, Symfony, or any PHP project

Official Documentation
----------------------

[](#official-documentation)

- **API Documentation**:
- **MITA GPG Info**:

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

[](#installation)

Install via Composer:

```
composer require born-mt/mita-gpg-sdk
```

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

[](#requirements)

- PHP 8.1 or higher
- ext-json
- guzzlehttp/guzzle ^7.5

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

[](#quick-start)

### Initialize the Client

[](#initialize-the-client)

```
use BornMT\MitaGpg\Client\GpgClient;

$client = new GpgClient(
    apiKey: 'your-api-key-here',
    testMode: true, // Set to false for production
    timeout: 30 // Optional timeout in seconds
);
```

### Create a Simple Payment

[](#create-a-simple-payment)

```
use BornMT\MitaGpg\DTO\PaymentRequest;
use BornMT\MitaGpg\Enums\TransactionType;

// Create payment request
$request = new PaymentRequest(
    amount: 50.00,
    uniqueReference: uniqid('order_'),
    transactionType: TransactionType::SALE,
    customerEmail: 'customer@example.com',
    customerFirstName: 'John',
    customerLastName: 'Doe',
    description: 'Order #12345',
    redirectUrl: 'https://yoursite.com/payment/success',
    callbackUrl: 'https://yoursite.com/webhook/gpg',
    cancelUrl: 'https://yoursite.com/payment/cancel'
);

// Create the payment
$response = $client->createPayment($request);

if ($response->isSuccess()) {
    // Redirect user to payment page
    $paymentUrl = $client->buildPaymentPageUrl($response->getTransactionId());
    header("Location: $paymentUrl");
    exit;
}
```

### Pre-Authorize and Capture

[](#pre-authorize-and-capture)

```
// Step 1: Pre-authorize payment (hold funds)
$authRequest = new PaymentRequest(
    amount: 150.00,
    uniqueReference: 'booking_' . uniqid(),
    transactionType: TransactionType::AUTH,
    customerEmail: 'guest@hotel.com',
    description: 'Hotel Reservation'
);

$authResponse = $client->createPayment($authRequest);
$transactionId = $authResponse->getTransactionId();

// Redirect to payment page...
// User completes 3D Secure authentication...

// Step 2: Later, capture the payment
$captureResponse = $client->capturePayment(
    transactionId: $transactionId,
    amount: 150.00 // Can capture partial amount
);

if ($captureResponse->isSuccess()) {
    echo "Payment captured successfully!";
}
```

### Handle Webhooks

[](#handle-webhooks)

```
// In your webhook endpoint controller
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_GPG_SIGNATURE'] ?? null;
$secret = 'your-webhook-secret';

try {
    // Parse and verify webhook
    $webhook = $client->parseWebhook($payload, $signature, $secret);

    // Handle the transaction
    if ($webhook->isProcessed()) {
        // Payment successful
        $transactionId = $webhook->getTransactionId();
        $amount = $webhook->getAmount();
        $orderRef = $webhook->getUniqueReference();

        // Update your database
        updateOrder($orderRef, 'paid', $transactionId);

        // Send confirmation email
        sendConfirmationEmail($webhook->getCustomerEmail());
    } elseif ($webhook->isDeclined()) {
        // Payment declined
        handleDeclinedPayment($webhook);
    }

    // Always return 200 to acknowledge receipt
    http_response_code(200);
    echo json_encode(['status' => 'ok']);

} catch (\BornMT\MitaGpg\Exceptions\InvalidSignatureException $e) {
    // Invalid signature - possible security issue
    http_response_code(403);
    echo json_encode(['error' => 'Invalid signature']);
}
```

### Refund a Payment

[](#refund-a-payment)

```
// Full refund
$refundResponse = $client->refundPayment(
    transactionId: 'transaction-id-here'
);

// Partial refund
$partialRefund = $client->refundPayment(
    transactionId: 'transaction-id-here',
    amount: 25.00
);

if ($refundResponse->isSuccess()) {
    echo "Refund processed successfully!";
}
```

### Get Transaction Details

[](#get-transaction-details)

```
$transaction = $client->getTransaction('transaction-id-here');

echo "Status: " . $transaction['result']['status'];
echo "Amount: " . $transaction['result']['amount'];
echo "Card: " . $transaction['result']['cardNumber'];
```

### Get Transaction History

[](#get-transaction-history)

```
$transactions = $client->getTransactions([
    'startDate' => '2025-01-01',
    'endDate' => '2025-01-31',
    'status' => 'PROCESSED',
    'pageSize' => 50,
    'pageNumber' => 1
]);

foreach ($transactions['result']['transactions'] as $tx) {
    echo "{$tx['transactionId']}: {$tx['amount']} EUR - {$tx['status']}\n";
}
```

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

[](#api-reference)

### GpgClient

[](#gpgclient)

The main client class for interacting with Malta GPG API.

#### Constructor

[](#constructor)

```
public function __construct(
    string $apiKey,
    bool $testMode = false,
    int $timeout = 30,
    array $options = []
)
```

#### Methods

[](#methods)

##### createPayment(PaymentRequest $request): PaymentResponse

[](#createpaymentpaymentrequest-request-paymentresponse)

Create a new Hosted Payment Page transaction.

##### capturePayment(string $transactionId, ?float $amount = null): PaymentResponse

[](#capturepaymentstring-transactionid-float-amount--null-paymentresponse)

Capture a pre-authorized payment (full or partial).

##### refundPayment(string $transactionId, ?float $amount = null): PaymentResponse

[](#refundpaymentstring-transactionid-float-amount--null-paymentresponse)

Refund a processed payment (full or partial).

##### voidPayment(string $transactionId): PaymentResponse

[](#voidpaymentstring-transactionid-paymentresponse)

Cancel/void a pending or authorized transaction.

##### getTransaction(string $transactionId): array

[](#gettransactionstring-transactionid-array)

Get details of a specific transaction.

##### getTransactions(array $filters = \[\]): array

[](#gettransactionsarray-filters---array)

Get list of transactions with optional filters.

##### buildPaymentPageUrl(string $transactionId): string

[](#buildpaymentpageurlstring-transactionid-string)

Build the Hosted Payment Page URL for a transaction.

##### verifyWebhookSignature(string $payload, string $signature, string $secret): bool

[](#verifywebhooksignaturestring-payload-string-signature-string-secret-bool)

Verify webhook signature using HMAC SHA256.

##### parseWebhook(string $payload, ?string $signature, ?string $secret): WebhookPayload

[](#parsewebhookstring-payload-string-signature-string-secret-webhookpayload)

Parse and optionally verify webhook payload.

### DTOs

[](#dtos)

#### PaymentRequest

[](#paymentrequest)

```
new PaymentRequest(
    float $amount,
    string $uniqueReference,
    TransactionType $transactionType = TransactionType::SALE,
    ?string $customerEmail = null,
    ?string $customerFirstName = null,
    ?string $customerLastName = null,
    ?string $customerPhone = null,
    ?string $description = null,
    ?string $redirectUrl = null,
    ?string $callbackUrl = null,
    ?string $cancelUrl = null,
    bool $isTest = false,
    array $metadata = [],
    array $udfFields = []
)
```

**Fluent Methods:**

- `setAmount(float $amount)`
- `setCustomerEmail(string $email)`
- `setCustomerName(string $firstName, string $lastName)`
- `setDescription(string $description)`
- `setRedirectUrl(string $url)`
- `setCallbackUrl(string $url)`
- `addMetadata(string $key, mixed $value)`
- `setUdfField(int $fieldNumber, string $value)` (1-5)

#### PaymentResponse

[](#paymentresponse)

```
// Methods
isSuccess(): bool
getTransactionId(): ?string
getGatewayId(): ?string
getStatus(): ?TransactionStatus
getPaymentUrl(): ?string
getMessage(): ?string
getRawResponse(): array
```

#### WebhookPayload

[](#webhookpayload)

```
// Methods
isProcessed(): bool
isDeclined(): bool
isPending(): bool
getTransactionId(): string
getStatus(): TransactionStatus
getAmount(): float
getAuthCode(): ?string
getCardNumber(): ?string (masked)
getUniqueReference(): ?string
getUdfField(int $fieldNumber): ?string
getRawPayload(): array
```

### Enums

[](#enums)

#### TransactionType

[](#transactiontype)

- `SALE` - Immediate payment
- `AUTH` - Pre-authorization
- `CAPTURE` - Capture authorized payment
- `REFUND` - Refund payment
- `VOID` - Cancel transaction

#### TransactionStatus

[](#transactionstatus)

- `PENDING` - Payment initiated
- `PROCESSED` - Payment successful
- `DECLINED` - Payment declined
- `AUTHORIZED` - Pre-authorized
- `REFUNDED` - Payment refunded
- `CANCELLED` - Transaction cancelled
- `FAILED` - Technical failure

### Exceptions

[](#exceptions)

All exceptions extend `GpgException`:

- **AuthenticationException** (401) - Invalid API key
- **ValidationException** (400/422) - Request validation failed
- **ApiException** (4xx/5xx) - General API errors
- **NetworkException** - Connection/network errors
- **InvalidSignatureException** (403) - Webhook signature verification failed

Advanced Usage
--------------

[](#advanced-usage)

### Custom UDF Fields

[](#custom-udf-fields)

```
$request = new PaymentRequest(
    amount: 100.00,
    uniqueReference: 'order_123'
);

// Add custom user-defined fields (up to 5)
$request->setUdfField(1, 'Customer ID: 456')
        ->setUdfField(2, 'Product SKU: ABC123')
        ->setUdfField(3, 'Campaign: SUMMER2025');

$response = $client->createPayment($request);
```

### Custom Metadata

[](#custom-metadata)

```
$request = new PaymentRequest(
    amount: 50.00,
    uniqueReference: 'booking_789'
);

$request->addMetadata('hotel_id', '123')
        ->addMetadata('room_type', 'deluxe')
        ->addMetadata('check_in', '2025-06-01');
```

### Error Handling

[](#error-handling)

```
use BornMT\MitaGpg\Exceptions\{
    AuthenticationException,
    ValidationException,
    ApiException,
    NetworkException
};

try {
    $response = $client->createPayment($request);
} catch (AuthenticationException $e) {
    // Invalid API key
    log_error("Auth failed: " . $e->getMessage());
    echo "Configuration error. Please contact support.";
} catch (ValidationException $e) {
    // Invalid request data
    $errors = $e->getErrors();
    foreach ($errors as $field => $message) {
        echo "$field: $message\n";
    }
} catch (NetworkException $e) {
    // Connection issue
    echo "Service temporarily unavailable. Please try again.";
} catch (ApiException $e) {
    // Other API error
    log_error("API Error: " . $e->getMessage());
    echo "Payment processing error. Please try again.";
}
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run with coverage:

```
composer test-coverage
```

Getting API Credentials
-----------------------

[](#getting-api-credentials)

### For Testing/Development

[](#for-testingdevelopment)

Contact GPG Support to request test API keys:

- **Email**:
- **Phone**: +356 21234710
- Mention you need sandbox/test credentials

### For Production

[](#for-production)

1. Open merchant accounts with BOV and/or HSBC Malta
2. Ensure accounts are 3D Secure enabled
3. Raise an eRFS (electronic Request for Service) to MITA
4. Provide your bank account details and business information
5. Wait for approval (processing time varies)
6. Receive production API credentials

Security Best Practices
-----------------------

[](#security-best-practices)

1. **Never commit API keys** - Use environment variables
2. **Always verify webhook signatures** - Prevent spoofing
3. **Use HTTPS** - Required for production
4. **Validate amounts** - Check amounts match your records
5. **Log everything** - Keep audit trail of transactions
6. **Handle errors gracefully** - Don't expose internal details to users
7. **Test thoroughly** - Use test mode before production
8. **Monitor webhooks** - Alert on missed/failed webhooks

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

[](#payment-flow)

1. **Customer initiates payment** on your website
2. **Create payment** via API (POST /api/HostedPaymentPage)
3. **Redirect customer** to GPG Hosted Payment Page
4. **Customer enters card details** on secure GPG page
5. **3D Secure authentication** by customer's bank
6. **Payment processed** by acquiring bank
7. **Customer redirected** back to your site
8. **Webhook sent** with final transaction status
9. **Update your database** based on webhook

Support
-------

[](#support)

- **GPG Support**:
- **MITA**:  / +356 21234710
- **Documentation**:
- **Issues**:

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Credits
-------

[](#credits)

- **Born MT** -
- **Malta Information Technology Agency (MITA)** -
- **APCOPay** - Payment gateway provider

Changelog
---------

[](#changelog)

### 1.0.0 (2025-01-05)

[](#100-2025-01-05)

- Initial release
- Full API coverage
- Webhook support
- Comprehensive documentation

---

**Made with ❤️ in Malta**

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance76

Regular maintenance activity

Popularity7

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

189d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/bd996adc5b32d9c20f01ab8328f3633c333489cb3915ba30555395d269aab5d8?d=identicon)[webeerannie](/maintainers/webeerannie)

---

Tags

paymentgpg3d-secureapcopayMaltagovernment-payment-gatewaymita

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/born-mt-mita-gpg-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/born-mt-mita-gpg-sdk/health.svg)](https://phpackages.com/packages/born-mt-mita-gpg-sdk)
```

###  Alternatives

[shetabit/multipay

PHP Payment Gateway Integration Package

291348.2k3](/packages/shetabit-multipay)[bitpay/sdk

Complete version of the PHP library for the new cryptographically secure BitPay API

42337.5k4](/packages/bitpay-sdk)[sebdesign/laravel-viva-payments

A Laravel package for integrating the Viva Payments gateway

4845.9k](/packages/sebdesign-laravel-viva-payments)[henryejemuta/laravel-monnify

A laravel package to seamlessly integrate monnify api within your laravel application

132.1k](/packages/henryejemuta-laravel-monnify)[tsaiyihua/laravel-linepay

linepay library for laravel

102.9k](/packages/tsaiyihua-laravel-linepay)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
