Money and payments
How a module sells for balance and refunds through Purchase, listens to payment, refund and dispute events, and adds its own payment system as a gateway driver.
By the end, your module sells for balance so that a repeated request never charges twice, refunds against the same purchase, and reacts to payments, refunds and disputes on invoices. If the module connects a payment system, the gateway driver is covered here too.
Minimal example
The Example module sells an XP boost for balance and returns the money if the boost is cancelled. The purchase key is built from the buyer id and a request key sent by the form, so a double click or a retry after a dropped connection arrives with the same key. The second file listens for a paid invoice in the provider's boot().
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Services;
use Flute\Core\Database\Entities\User;
use Flute\Core\Modules\Payments\Services\Minor;
use Flute\Core\Modules\Payments\Services\Purchase;
use Flute\Core\Modules\Payments\Services\PurchaseResult;
use Flute\Core\Services\BalanceHistoryMeta;
use Flute\Modules\Example\database\Entities\Boost;
final class BoostShop
{
public const SOURCE = 'example';
public function buy(User $buyer, int $hours, string $requestKey): PurchaseResult
{
return Purchase::run(
$buyer,
Minor::major(Minor::of((string) config('example.price_per_hour', '10')) * $hours),
self::SOURCE,
self::reference($buyer->id, $requestKey),
static function () use ($buyer, $hours): int {
$boost = new Boost();
$boost->userId = $buyer->id;
$boost->hours = $hours;
$boost->saveOrFail();
return $boost->id;
},
BalanceHistoryMeta::make()->itemName('XP boost'),
__('example.history.boost'),
);
}
public function cancel(int $buyerId, string $requestKey): PurchaseResult
{
return Purchase::refund(self::SOURCE, self::reference($buyerId, $requestKey));
}
private static function reference(int $buyerId, string $requestKey): string
{
return 'boost-' . $buyerId . '-' . $requestKey;
}
}<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Providers;
use DI\Container;
use Flute\Core\Modules\Payments\Events\PaymentSuccessEvent;
use Flute\Core\Support\ModuleServiceProvider;
use Flute\Modules\Example\Services\TopUpBonus;
final class ExampleProvider extends ModuleServiceProvider
{
public function register(Container $container): void
{
}
public function boot(Container $container): void
{
$this->bootstrapModule();
events()->addListener(
PaymentSuccessEvent::NAME,
static fn(PaymentSuccessEvent $e) => app(TopUpBonus::class)->paid($e->getInvoice()),
);
}
}TopUpBonus::paid() first checks whether the invoice with this transactionId was already handled: the event can arrive twice if the process died right after the commit.
How it works
Purchase::run() opens its own transaction at READ COMMITTED and does everything inside it: locks the buyer row, looks up the (source, reference) pair, checks the post-chargeback purchase block, debits the balance with a purchase history row, writes the purchase row, calls $deliver, puts the event into the outbox and commits. After the commit the core announces the new balance and sends PurchaseCompletedEvent.
The (source, reference) pair is the idempotency key, held by a unique index on balance_purchases. A repeat with the same key, including a concurrent one from another process, charges nothing, skips $deliver and returns the first purchase with replayed = true. An exception from $deliver rolls back the debit and frees the key, and the exception reaches the caller.
Purchase::refund() returns whatever is left of the purchase, or a part of it with amount:. A partial refund is safe to repeat when you pass refundKey:. To take the item back in the same transaction, use within:. Refunds never add up to more than the purchase price.
Inside $deliver and within:, only write to the database. Send notifications, HTTP requests and game server commands after run() has returned. The service is static and works in any context: site, admin, API, cron and queue.
Payment and purchase events are sent after the commit, and once more from the outbox if the process died between the commit and the dispatch. A listener drops the repeat by the key in the table below.
Reference
| Call | What it does |
|---|---|
Purchase::run(User $buyer, float $price, string $source, string $reference, callable $deliver, ?BalanceHistoryMeta $meta = null, ?string $description = null): PurchaseResult | sells for balance. $source up to 64 characters (the module id), $reference up to 191 |
Purchase::refund(string $source, string $reference, ?string $description = null, ?BalanceHistoryMeta $meta = null, ?float $amount = null, ?callable $within = null, ?string $refundKey = null): PurchaseResult | refunds a purchase, the whole remainder or $amount |
user()->topup(float $sum, ?User $user = null, ?string $source = null, ?string $description = null, ?BalanceHistoryMeta $meta = null): void | credits the balance under your own source (a gift, a reward). Sends the core.balance_topup notification. Has no repeat key |
user()->unbalance(float $sum, ?User $user = null, ?string $source = null, ?string $description = null, ?BalanceHistoryMeta $meta = null): void | debits without a purchase row, so Purchase::refund() cannot return it |
app(Stakes::class)->hold(string $purse, int $owner, int $amount, string $source, string $ref, string $group, DateTimeImmutable $expiresAt): int | holds an amount until an event ends (a duel, a bet), then settle() or release(). Only inside the caller's transaction, safe to repeat by (source, ref). The purse (Flute\Core\Stakes\Purse) is registered by a module, the core has none of its own: the Rewards module holds site balance this way |
PurchaseResult | purchaseId, amount, ledgerId, replayed, refunded (everything returned), delivered (what $deliver or within: returned), refundedAmount |
NAME | When | Fields | Drop repeats by |
|---|---|---|---|
payment.success | an invoice is paid and the money credited | getInvoice(), getUser() | getInvoice()->transactionId |
payment.failed | the gateway reported a failure | getInvoice(), getReason() | not needed, sent once per gateway event |
payment.refunded | a refund on a paid invoice was applied | invoice, user, balanceDebited, full, reversalId | reversalId |
payment.dispute_opened | the payer's bank opened a dispute | invoice, user, reversalId | reversalId |
payment.dispute_resolved | the dispute was won (won = true) or lost | invoice, user, won, reversalId | reversalId |
purchase.completed | a balance purchase went through | user, amount, source, reference, purchaseId, ledgerId | purchaseId |
purchase.refunded | purchase money came back, fully or in part | user, amount, source, reference, purchaseId, ledgerId, full | ledgerId |
The event classes live in Flute\Core\Modules\Payments\Events. Listen to purchase.* with a $e->source === BoostShop::SOURCE check, otherwise your module receives other modules' purchases. The Referral module reacts to invoice payments, refunds and disputes this way: it credits a share to the referrer and takes it back on a refund.
Your own payment system
A payment system is added as a gateway driver: one class in the module's Surfaces/ folder with the #[PaymentGatewayDriver] attribute. You need no controller, route, migration or settings screen. The admin builds the settings form from the definition() fields, and the core provides the webhook address. Put "category": "payment" into module.json, and the payment system screen will offer the module even while it is disabled.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Surfaces;
use Flute\Core\Modules\Payments\Gateway\AbstractGatewayDriver;
use Flute\Core\Modules\Payments\Gateway\Checkout;
use Flute\Core\Modules\Payments\Gateway\Field;
use Flute\Core\Modules\Payments\Gateway\GatewayContext;
use Flute\Core\Modules\Payments\Gateway\GatewayDefinition;
use Flute\Core\Modules\Payments\Gateway\GatewayEvent;
use Flute\Core\Modules\Payments\Gateway\Notification;
use Flute\Core\Modules\Payments\Gateway\PaymentRequest;
use Flute\Core\Modules\Payments\Gateway\Support\Sign;
use Flute\Core\Surfaces\Attributes\PaymentGatewayDriver;
#[PaymentGatewayDriver]
final class ExampleGateway extends AbstractGatewayDriver
{
public function definition(): GatewayDefinition
{
return GatewayDefinition::make('Example')
->currencies('RUB')
->ack('YES')
->fields(Field::text('shop')->required(), Field::secret('secret')->required());
}
public function start(PaymentRequest $payment, GatewayContext $ctx): Checkout
{
$sign = Sign::join([
$ctx->settings->string('shop'),
$payment->amount->decimal(),
$ctx->settings->string('secret'),
$payment->transactionId,
]);
return Checkout::redirect('https://pay.example.com/?' . http_build_query([
'o' => $payment->transactionId,
'a' => $payment->amount->decimal(),
's' => $sign,
]));
}
public function parse(Notification $notification, GatewayContext $ctx): ?GatewayEvent
{
$notification->requireSignature(
Sign::join([
$notification->input('amount'),
$ctx->settings->string('secret'),
$notification->input('order'),
]),
$notification->input('sign'),
);
return GatewayEvent::paid(
$notification->input('order'),
(string) $notification->input('amount'),
eventId: $notification->input('id'),
);
}
}Form field labels live in Resources/lang/{ru,en}/example.php (the domain is the gateway id in lower case) under fields.shop.label, fields.shop.help and fields.shop.placeholder. How the owner connects the system is described in Payment providers. The driver keeps no state and never touches the database. Settings, test mode and addresses come in GatewayContext, and requests to the gateway API go only through $ctx->http.
parse() checks authenticity first and throws InvalidNotification, in which case nothing is applied, while null means "the notification is genuine but not about a payment". From the event the core takes only the invoice or payment id, the amount, the currency and the event id, and reads the rest from the invoice. A repeat of the same notification is dropped by the gateway event journal, and the last line of defence is the invoice row lock with its "paid" flag. A driver test extends GatewayContractTestCase, see Module tests.
| Call | What it does |
|---|---|
make(string $id) | the gateway id, also PaymentGateway.adapter. Only [A-Za-z0-9_], up to 32 characters |
currencies(string ...$iso), anyCurrency() | currencies the owner can attach the gateway to |
fields(Field ...$fields) | settings fields: Field::text, secret, number, toggle, select, rows, with required(), default(), rules(), shownWith() |
ack(string $body, int $status = 200, string $contentType = 'text/plain') | the answer to the gateway for an accepted notification |
acceptsGet(), handlesReturn() | the gateway sends notifications as GET; the payer's return is also checked through parse() |
withoutTestMode(), invoiceTtl(int $minutes), pollEvery(int $minutes), logo(string $modulePath), docs(string $url) | no test mode switch; invoice lifetime; polling interval; logo from the module folder; link to the system's docs |
Optional interfaces from Flute\Core\Modules\Payments\Contracts: ChecksCredentials (check(GatewayContext $ctx): ?string, the key check button in the admin), PollsStatus (poll(InvoiceRef $invoice, GatewayContext $ctx): ?GatewayEvent, the payments.poll task runs every minute), InitiatesRefunds (refund(InvoiceRef $invoice, Money $amount, string $reason, GatewayContext $ctx): GatewayEvent, refunds from the admin through the gateway). The driver returns refund and dispute events from parse() with GatewayEvent::refund(), refundedTotal(), disputeOpened(), disputeWon(), disputeLost(). Ready drivers for 80 systems live in the PaymentGateways module, one folder per system. Its provider registers drivers outside Surfaces/ with $container->get(SurfaceRegistry::class)->add(SurfaceKeys::PAYMENT_GATEWAY, $driver).
What the core requires from a module
| Rule | How it gets broken |
|---|---|
sell for balance only through Purchase::run(), refund its money only through Purchase::refund() | a hand-made "check balance, debit, deliver" charges twice; a refund via user()->topup() leaves the purchase unrefunded and sends no purchase.refunded |
amounts are integers in the currency's minor units (JPY has 0 places, KWD 3), through Minor and Gateway\Money | a manual * 100, round(), comparing two floats |
Purchase::run() and refund() outside anyone else's transaction | calling them inside db()->transaction() |
gateway API requests through $ctx->http, requests to a user-typed address through Resilience\PublicHost | your own Guzzle client or file_get_contents |
a payment action in the admin asks to confirm the sign-in: ActionDescriptor::requiresElevation() or the elevated middleware | refunding or granting money without a password |
Common mistakes
| What you see | Cause |
|---|---|
LogicException: A purchase must not run inside another database transaction | run() or refund() was called inside an open transaction |
LogicException: Purchase key [example, …] belongs to another buyer. | the same reference already belongs to another user's purchase. Put the buyer id into the key |
InvalidArgumentException: Purchase price must be positive. | the price is 0 or below one minor unit. Give free items without Purchase |
PaymentException: Refund is more than is left of the purchase | amount: is larger than what is left to refund |
BalanceNotEnoughException | not enough money, the missing sum is in getNeededSum(). Show the top-up button <x-account-button to="topup"> |
| "Purchases on this account are blocked because a payment was refunded…" | WalletException: the account has an open chargeback and cannot spend until topped up to a non-negative balance |
LogicException: Payment gateway [Example] is registered by two drivers. | two drivers with the same id in make() |