Skip to Content
Module developmentIntegrations

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().

app/Modules/Example/Services/BoostShop.php
<?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;
    }
}
app/Modules/Example/Providers/ExampleProvider.php
<?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

CallWhat it does
Purchase::run(User $buyer, float $price, string $source, string $reference, callable $deliver, ?BalanceHistoryMeta $meta = null, ?string $description = null): PurchaseResultsells 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): PurchaseResultrefunds a purchase, the whole remainder or $amount
user()->topup(float $sum, ?User $user = null, ?string $source = null, ?string $description = null, ?BalanceHistoryMeta $meta = null): voidcredits 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): voiddebits 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): intholds 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
PurchaseResultpurchaseId, amount, ledgerId, replayed, refunded (everything returned), delivered (what $deliver or within: returned), refundedAmount
NAMEWhenFieldsDrop repeats by
payment.successan invoice is paid and the money creditedgetInvoice(), getUser()getInvoice()->transactionId
payment.failedthe gateway reported a failuregetInvoice(), getReason()not needed, sent once per gateway event
payment.refundeda refund on a paid invoice was appliedinvoice, user, balanceDebited, full, reversalIdreversalId
payment.dispute_openedthe payer's bank opened a disputeinvoice, user, reversalIdreversalId
payment.dispute_resolvedthe dispute was won (won = true) or lostinvoice, user, won, reversalIdreversalId
purchase.completeda balance purchase went throughuser, amount, source, reference, purchaseId, ledgerIdpurchaseId
purchase.refundedpurchase money came back, fully or in partuser, amount, source, reference, purchaseId, ledgerId, fullledgerId

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.

app/Modules/Example/Surfaces/ExampleGateway.php
<?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.

What the core requires from a module

RuleHow 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\Moneya manual * 100, round(), comparing two floats
Purchase::run() and refund() outside anyone else's transactioncalling them inside db()->transaction()
gateway API requests through $ctx->http, requests to a user-typed address through Resilience\PublicHostyour own Guzzle client or file_get_contents
a payment action in the admin asks to confirm the sign-in: ActionDescriptor::requiresElevation() or the elevated middlewarerefunding or granting money without a password

Common mistakes

What you seeCause
LogicException: A purchase must not run inside another database transactionrun() 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 purchaseamount: is larger than what is left to refund
BalanceNotEnoughExceptionnot 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()

See also

On this page