PHP code example of alifaraun / wallet

1. Go to this page and download the library: Download alifaraun/wallet 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/ */

    

alifaraun / wallet example snippets


use Alifaraun\Wallet\Concerns\HasWallets;
use Alifaraun\Wallet\Contracts\WalletHolder;
use Illuminate\Database\Eloquent\Model;

class Reseller extends Model implements WalletHolder
{
    use HasWallets;
}

use Alifaraun\Wallet\Facades\Wallet;

$wallet = $reseller->walletOrCreate(currency: 'USD', name: 'Main balance');

Wallet::credit($wallet, 100.00, type: 'topup', causer: auth()->user());
Wallet::debit($wallet, 19.99, type: 'voucher_sale', causer: auth()->user());

$wallet->refresh();
$wallet->balance; // 80.01

$reseller->wallet('USD');         // ?Wallet — null if it doesn't exist
$reseller->walletOrFail('USD');   // Wallet — throws WalletNotFoundException if missing
$reseller->walletOrCreate('USD'); // Wallet — fetches or creates (idempotent)

$reseller->walletOrCreate();      // currency omitted -> config('wallet.default_currency')

Wallet::credit(
    wallet: $wallet,
    amount: 100.00,
    type: 'topup',                 // string|BackedEnum
    operation: $invoice,           // optional ?Model
    causer: auth()->user(),        // optional ?Model
    fee: 2.00,                     // deducted from the credited amount
    description: 'Bank deposit',
    reference: 'dep_8842',         // optional unique key (per wallet)
    extra: ['gateway' => 'meeg'],
);

Wallet::debit(
    wallet: $wallet,
    amount: 19.99,
    type: 'voucher_sale',
    causer: auth()->user(),
    fee: 0.50,                     // added to the amount leaving the wallet
);

[$debit, $credit] = Wallet::transfer(
    from: $resellerA->walletOrFail('USD'),
    to: $resellerB->walletOrFail('USD'),
    amount: 50.00,
    causer: auth()->user(),
    fee: 1.00,                     // optional; charged to the sender (see below)
    reference: 'xfer_8842',        // optional idempotency key (see below)
);

Wallet::refund(
    wallet: $wallet,
    amount: 19.99,
    operation: $order,             // 

Wallet::reverse(
    transaction: $failedTransaction,
    causer: auth()->user(),
    description: 'Provider rejected',
);

Wallet::credit($wallet, 12.50);     // you pass 12.50
$txn->amount;                       // you read 12.50
$txn->getRawOriginal('amount');     // stored as 1250

Wallet::credit($wallet, '12.50');

use Alifaraun\Wallet\Models\WalletLimit;

WalletLimit::create([
    'holder_type' => Reseller::class, // omit wallet_id => applies to every Reseller wallet
    'currency' => 'USD',
    'min_amount' => 1.00,             // smallest single debit
    'max_amount' => 3000.00,          // largest single debit
    'daily_max_amount' => 50000.00,   // largest total debits per calendar day
]);

'limits' => [
    'credit' => [
        'USD' => ['min' => null, 'max' => 5000.00, 'daily_max' => 20000.00],
        'default' => ['min' => null, 'max' => null, 'daily_max' => null],
    ],
],

$line = $reseller->walletOrCreate(currency: 'USD', name: 'Credit line', minBalance: -500.00);

Wallet::debit($line, 400.00); // ok, balance -400.00
Wallet::debit($line, 200.00); // throws InsufficientBalanceException (would be -600.00)

$wallet = $reseller->walletOrCreate(currency: 'USD', lowBalanceThreshold: 50.00, lowBalanceMode: 'once');

// or post-creation:
$wallet->update(['low_balance_threshold' => 50.00, 'low_balance_mode' => 'always']);

use Alifaraun\Wallet\Events\LowBalanceWarning;

Event::listen(LowBalanceWarning::class, function (LowBalanceWarning $event) {
    $event->wallet->holder->notify(new WalletRunningLow($event->wallet, $event->balanceAfter, $event->threshold));
});

Wallet::credit($wallet, 50.00, reference: 'pay_123');
Wallet::credit($wallet, 50.00, reference: 'pay_123'); // throws DuplicateReferenceException

use Alifaraun\Wallet\Exceptions\InsufficientBalanceException;
use Alifaraun\Wallet\Exceptions\TransactionLimitExceededException;
use Alifaraun\Wallet\Exceptions\DailyLimitExceededException;

try {
    Wallet::debit($wallet, 5000.00);
} catch (InsufficientBalanceException $e) {
    report("Need {$e->getAttemptedAmount()}, have {$e->getAvailableBalance()}");
} catch (TransactionLimitExceededException | DailyLimitExceededException $e) {
    report("Limit hit on the {$e->getBreachedBound()} bound");
}

use Alifaraun\Wallet\Events\TransactionRecorded;

Event::listen(TransactionRecorded::class, function (TransactionRecorded $event) {
    $event->wallet->holder->notify(
        $event->transaction->debit
            ? new WalletDebited($event->transaction)
            : new WalletCredited($event->transaction)
    );
});

return [
    // Retry the whole transaction on deadlock / lock-wait. Defaults to 3 (safe:
    // the movement fully rolls back before a retry); raise under heavy contention.
    'transaction_attempts' => (int) env('WALLET_TRANSACTION_ATTEMPTS', 3),

    // Swap any model for your own subclass.
    'models' => [
        'wallet' => \Alifaraun\Wallet\Models\Wallet::class,
        'transaction' => \Alifaraun\Wallet\Models\WalletTransaction::class,
        'limit' => \Alifaraun\Wallet\Models\WalletLimit::class,
        'daily_usage' => \Alifaraun\Wallet\Models\WalletDailyUsage::class,
    ],

    // Polymorphic key type for holder/operation/causer columns. 'numeric'
    // (default), 'uuid', or 'ulid'. Read by the migrations, so set it before
    // migrating; all three relations share the type.
    'morphs' => env('WALLET_MORPHS', 'numeric'),

    // Where currency metadata comes from.
    'currency_repository' => \Alifaraun\Wallet\Repositories\ConfigCurrencyRepository::class,
    // REQUIRED — used when you call createWallet()/walletOrCreate()/wallet() without a
    // currency. No hardcoded fallback: set it (here or via WALLET_DEFAULT_CURRENCY) or
    // a defaulted call throws MissingDefaultCurrencyException.
    'default_currency' => env('WALLET_DEFAULT_CURRENCY'),
    'currencies' => [ /* code => ['decimals' => int, 'symbol' => string] */ ],

    // How "today's total" is computed for daily limits.
    'daily_usage' => \Alifaraun\Wallet\Support\CounterTableUsage::class,

    // Limit rules. All positive major-unit numbers or null (= unlimited).
    // Per-transaction (min/max) and daily maximums are enforced.
    'limit_resolver' => \Alifaraun\Wallet\Support\DefaultLimitResolver::class,
    'limits' => [
        'debit'  => ['default_min' => null, 'default_max' => null, 'daily_default_max' => null],
        'credit' => ['default' => ['min' => null, 'max' => null, 'daily_max' => null]],
    ],

    'ref_prefix' => env('WALLET_REF_PREFIX', 'wlt_'),                     // wallet refs
    'transaction_ref_prefix' => env('WALLET_TRANSACTION_REF_PREFIX', 'txn_'), // auto transaction refs
    'daily_window_timezone' => env('WALLET_DAILY_TIMEZONE', config('app.timezone', 'UTC')),

    // Fallback for wallets with no low_balance_mode column of their own.
    'low_balance' => [
        'default_mode' => env('WALLET_LOW_BALANCE_DEFAULT_MODE', 'once'),
    ],
];

// config/wallet.php
'currency_repository' => \Alifaraun\Wallet\Repositories\EloquentCurrencyRepository::class,

use Alifaraun\Wallet\Contracts\CurrencyRepository;

class MyCurrencies implements CurrencyRepository
{
    public function exists(string $code): bool { /* … */ }
    public function decimals(string $code): int { /* … */ }
    public function symbol(string $code): string { /* … */ }
}

// config/wallet.php => 'currency_repository' => MyCurrencies::class

// O(1) counter table (default) — best for high traffic:
'daily_usage' => \Alifaraun\Wallet\Support\CounterTableUsage::class,

// Zero-extra-table SUM() over the ledger — fine for low volume:
'daily_usage' => \Alifaraun\Wallet\Support\LedgerSumUsage::class,

Wallet::debit($wallet, 5.00, type: 'card_issue');
Wallet::credit($wallet, 5.00, type: MyTypes::Bonus); // a BackedEnum also works
bash
php artisan migrate
bash
php artisan vendor:publish --tag=wallet-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=wallet-currency-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=wallet-config