Moolre PHP SDK

Initiate hosted payments and verify Moolre transactions from a PHP backend.

# Moolre PHP SDK

Use the framework-agnostic `moolre/moolre-php` Composer package to create hosted Moolre payment sessions and verify transactions from a PHP backend.

## Installation

```bash
composer require moolre/moolre-php
```

The SDK requires PHP 7.4 or later and the JSON extension. cURL is recommended; PHP streams are used as a fallback.

## Configure the client

Keep credentials in server-side environment variables. Live payment initiation requires a public key and account number. Sandbox initiation requires an account number and API user; a public key is optional in sandbox. Verification always requires the API user.

```php
use Moolre\Client;

$isProduction = getenv('MOOLRE_PRODUCTION') === 'true';

$client = new Client(
    $isProduction ? (getenv('MOOLRE_PUBLIC_KEY') ?: '') : '',
    getenv('MOOLRE_ACCOUNT_NUMBER') ?: '',
    null,
    $isProduction ? Client::DEFAULT_BASE_URL : Client::SANDBOX_BASE_URL,
    60,
    false,
    getenv('MOOLRE_API_USER') ?: '',
    $isProduction ? Client::DEFAULT_VERIFICATION_URL : Client::SANDBOX_VERIFICATION_URL,
);
```

## Initiate a payment

Create a unique reference in your application, store the pending order, then redirect the customer to the returned hosted authorization URL.

```php
$payment = $client->initiatePayment([
    'reference' => Client::generateReference('order_1001'),
    'email' => 'customer@example.com',
    'amount' => '120.00',
    'currency' => 'GHS',
    'callback' => 'https://example.com/moolre/webhook',
    'redirect' => 'https://example.com/moolre/receipt',
    'expiration_time' => 10,
]);

header('Location: ' . $payment->authorizationUrl(), true, 302);
exit;
```

## Verify before fulfilment

Treat the callback and customer redirect as notifications, not proof of payment. Load the pending order by reference and verify it server-side before fulfilling it.

```php
$transaction = $client->verifyPayment($reference);

if (!$transaction->matchesAmountAndAccountNumber(
    $order['amount'],
    $order['account_number'],
)) {
    throw new RuntimeException('Payment could not be verified for this order.');
}

// Mark this order as paid exactly once, then fulfil it.
```

## Resources

- [GitHub repository](https://github.com/moolrehq/moolre-php)
- [Packagist package](https://packagist.org/packages/moolre/moolre-php)

Back to the Moolre AI documentation index