PHP code example of born-mt / mita-gpg-sdk

1. Go to this page and download the library: Download born-mt/mita-gpg-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

born-mt / mita-gpg-sdk example snippets


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
);

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: '[email protected]',
    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;
}

// Step 1: Pre-authorize payment (hold funds)
$authRequest = new PaymentRequest(
    amount: 150.00,
    uniqueReference: 'booking_' . uniqid(),
    transactionType: TransactionType::AUTH,
    customerEmail: '[email protected]',
    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!";
}

// 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']);
}

// 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!";
}

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

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

$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";
}

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

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 = []
)

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

// 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

$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);

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

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

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.";
}