fonepay-laravel maintained by aansh
Aansh Fonepay
A small, framework-agnostic client for the Fonepay third-party v2 API. It is
built for Laravel but does not depend on the full framework: only the
illuminate/* packages are required.
It covers the four operations the gateway exposes — login, dynamic QR generation, bank listing and payment-status lookup — plus server-side verification and an opt-in callback endpoint.
Requirements
| PHP | 8.3 or 8.4 |
| Laravel | 12 or 13 |
Laravel 11 is not supported: it is end of life and its laravel/framework
releases are blocked by published security advisories.
Why this package
- One login per token lifetime, not per request. Concurrent calls are single-flighted through a cache lock.
- Signed bytes are sent bytes. The JSON body is serialised once, signed, then transmitted verbatim, so re-encoding can never invalidate a signature.
- Exact money. Amounts are handled as
Money(integer minor units), never floats. - Typed failures. Every gateway response maps to a named exception; nothing is swallowed.
- No secret defaults. Credentials come from config, and a missing value
throws a
ConfigurationExceptionbefore any network call. - Callbacks are never trusted. The callback route re-reads the payment from
the status API before reporting success; a forged
COMPLETEDcannot pass.
Installation
composer require aansh/fonepay-laravel
The service provider and the Fonepay alias are auto-discovered.
Publish the config if you want to edit it in place:
php artisan vendor:publish --provider="Aansh\Fonepay\FonepayServiceProvider" --tag=fonepay-config
For database-managed connections, publish and run the package migration explicitly:
php artisan vendor:publish --provider="Aansh\Fonepay\FonepayServiceProvider" --tag=fonepay-migration
php artisan migrate
The migration is not loaded automatically. It creates a tenant-agnostic
fonepay_connections table in the application's current database; configure
your own tenant database connection before running it if needed.
Optionally install bacon/bacon-qr-code to render a QR string as SVG:
composer require bacon/bacon-qr-code
Configuration
FONEPAY_USERNAME=your-merchant-username
FONEPAY_PASSWORD=your-merchant-password
FONEPAY_TERMINAL_ID=your-terminal-id
FONEPAY_PRIVATE_KEY_PATH=/absolute/path/to/private.pem
FONEPAY_PUBLIC_KEY_PATH=/absolute/path/to/public.pem
# Optional
FONEPAY_BASE_URL=https://dev-external-gateway-new.fonepay.com/merchantThirdparty
FONEPAY_BASE_PATH=/api/merchant/third-party/v2
FONEPAY_CALLBACK_ENABLED=false
FONEPAY_DEBUG=false
FONEPAY_PRIVATE_KEY and FONEPAY_PUBLIC_KEY accept a raw PEM and take
precedence over the _PATH variants, which is useful when the key lives in a
secret manager.
Config driver (default)
The default config driver keeps credentials in the connections array.
Every connection is named, and the configured default is used unless you ask
for another:
'connections' => [
'default' => [...],
'sports' => ['username' => env('FONEPAY_SPORTS_USERNAME'), ...],
],
Fonepay::connection('sports')->generateQrCode($request);
Token and bank caches are keyed per connection, so merchants never share credentials.
Database driver
Set FONEPAY_DRIVER=database after publishing and running the migration. Add
rows using Aansh\Fonepay\Database\Models\FonepayConnection; credential values
and PEM keys are encrypted by Laravel's application key. The first row becomes
the default unless another active row is already marked default. Marking a
second row default demotes the previous one. Credential changes flush the
connection's resolved config and token.
use Aansh\Fonepay\Database\Models\FonepayConnection;
FonepayConnection::create([
'name' => 'bank-a',
'label' => 'Bank A',
'username' => 'merchant-user',
'password' => 'merchant-password',
'terminal_id' => 'TERM-001',
'base_url' => 'https://dev-external-gateway-new.fonepay.com/merchantThirdparty',
'base_path' => '/api/merchant/third-party/v2',
'payment_mode' => 'QR',
'qr_type' => 'INTENT_QR',
'private_key' => file_get_contents('/secure/private.pem'),
'public_key' => file_get_contents('/secure/public.pem'),
'settings' => ['timeout' => 10, 'retry_times' => 2],
]);
The table stores name, label, bank_code, bank_name, username,
encrypted password/keys, terminal_id, base_url, base_path, key paths,
payment_mode, qr_type, JSON settings, active/default flags, test-health
results, and timestamps. No tenant column is included; the consuming
application owns tenancy. base_url must use fonepay.com or a subdomain.
Use FONEPAY_DATABASE_CACHE_TTL to set the resolved-connection cache lifetime.
Fonepay::connections() and the provider's all() return metadata only, never
credentials.
Test a connection without displaying credentials:
php artisan fonepay:test bank-a
Usage
Generate a QR
use Aansh\Fonepay\Data\GenerateQrRequest;
use Aansh\Fonepay\Facades\Fonepay;
use Aansh\Fonepay\Support\ReferenceLabel;
$qr = Fonepay::generateQrCode(new GenerateQrRequest(
amount: \Aansh\Fonepay\Support\Money::fromDecimal('1500.00'),
referenceLabel: ReferenceLabel::make('FEE'), // unique per attempt
billId: 'INV-2026-0001',
));
$qr->qrString; // render this
$qr->prn; // gateway reference number
$qr->referenceLabel; // your idempotency key
Use generateOrResume() when a client may retry the same reference: a cached
QR is returned instead of a second intent.
Track a payment
$status = Fonepay::getPaymentStatus($referenceLabel);
$status->state; // PaymentState::Completed | Pending | Failed | Cancelled
$status->transactionAmount; // Money
Reconcile many at once:
$results = Fonepay::getPaymentStatuses($references, concurrency: 5);
Each value is either a PaymentStatus or a Throwable, keyed by reference
label.
Verify before fulfilling
use Aansh\Fonepay\Exceptions\PaymentNotVerifiedException;
try {
$receipt = Fonepay::verifyPayment($referenceLabel, '1500.00');
} catch (PaymentNotVerifiedException $e) {
// wrong state, wrong amount, or unknown reference
}
$receipt->isSuccessful();
$receipt->paidAmount;
verifyPayment() always reads the gateway status; it never trusts a caller
payload.
Banks
foreach (Fonepay::getBanks() as $bank) {
$bank->name;
$bank->code;
$bank->intentScheme;
}
The list is cached for banks_cache_ttl seconds (default 300).
Callback endpoint
Enable it and point Fonepay at POST /api/fonepay/callback:
FONEPAY_CALLBACK_ENABLED=true
The controller:
- verifies the signature when a public key is configured,
- requires a reference label and amount,
- re-reads the status from Fonepay,
- returns
200only when the payment verified.
Listen for the outcome instead of editing the controller:
use Aansh\Fonepay\Events\PaymentVerified;
use Illuminate\Support\Facades\Event;
Event::listen(PaymentVerified::class, function (PaymentVerified $event) {
// $event->receipt
});
Error handling
All exceptions extend Aansh\Fonepay\Exceptions\FonepayException:
| Exception | When |
|---|---|
ConfigurationException |
missing credential, key or connection |
AuthenticationException |
login rejected |
TransportException |
connection timeout / DNS / TLS failure |
MalformedResponseException |
non-JSON or unexpected payload |
MalformedSignatureException |
body could not be signed |
DuplicateReferenceLabelException |
reference already used (409 on QR) |
ValidationException |
gateway rejected the payload (400/422) |
InvalidTerminalException |
unknown terminal (409 on status) |
InvalidReferenceLabelException |
unknown reference (500 on status) |
PaymentNotVerifiedException |
state or amount did not match |
InvalidAmountException |
malformed money input |
PHP 8.3 support
The minimum PHP version is 8.3 and no PHP 8.4-only syntax is used, so the
package runs unchanged on 8.3. Locally the suite is executed on PHP 8.4; the
support contract is enforced by the CI matrix in
.github/workflows/tests.yml, which runs PHP 8.3 and 8.4 against Laravel 12 and
13 on every push.
Testing
composer test # phpunit
composer lint # pint --test
composer analyse # phpstan level 8
The suite fakes HTTP through Laravel's client, including an assertion that the signature header verifies against the exact bytes that were sent.
Migrating from mantraideas/laravel-fonepay
| Old | New |
|---|---|
Fonepay::generateQrCode(new GenerateQrCodeDTO(...)) |
Fonepay::generateQrCode(new GenerateQrRequest(...)) |
Fonepay::getPaymentStatus($prn) |
Fonepay::getPaymentStatus($referenceLabel) |
Fonepay::getBanks() |
unchanged |
StatusDTO->paymentStatus |
PaymentStatus->gatewayStatus / ->state |
StatusDTO->totalTransactionAmount (string) |
PaymentStatus->transactionAmount?->toDecimal() |
float $amount |
Money::fromDecimal('1000.00') |
FONEPAY_PRIVATE_KEY_PATH |
FONEPAY_PRIVATE_KEY_PATH or FONEPAY_PRIVATE_KEY |
The old package logs in on every call, signs a different string than it sends, and accepts floats; this one fixes all three.
License
MIT.