centrex/laravel-wallet

在 Laravel 应用中添加钱包功能

v1.0.2 2024-01-03 07:10 UTC

This package is auto-updated.

Last update: 2024-09-08 12:33:33 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

轻松地将虚拟钱包添加到您的 Laravel 模型中。具有多个钱包和账本系统,以帮助跟踪钱包中的所有交易。

内容

安装

您可以通过 composer 安装此包

composer require centrex/laravel-wallet

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="laravel-wallet-config"

这是已发布的配置文件的内容

return [
];

可选地,您可以使用以下命令发布视图

php artisan vendor:publish --tag="laravel-wallet-views"

用法

首先,您需要将 HasWallets 特性添加到您的模型中。

use Centrex\Wallet\Traits\HasWallets;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable, HasWallets;
}

通过添加 HasWallets 特性,您实际上已将所有钱包关系添加到模型中。

您可以从为给定模型创建钱包开始。

$user = User::find(1);

$wallet = $user->wallets()->create();

然后您可以增加钱包余额

$wallet->incrementBalance(100);

或减少余额

$wallet->decrementBalance(100);

要获取钱包余额,您可以使用 balance 访问器

$wallet->balance;

您可以使用模型中的 wallet() 方法访问钱包

$user->wallet();

您可以通过定义 WalletType 来设置多种类型的钱包。只需在 wallet_types 表中创建一个钱包类型条目,然后使用此钱包类型创建钱包。

use CoreProc\WalletPlus\Models\WalletType;

$walletType = WalletType::create([
    'name' => 'Peso Wallet',
    'decimals' => 2, // Set how many decimal points your wallet accepts here. Defaults to 0.
]);

$user->wallets()->create(['wallet_type_id' => $walletType->id]);

您也可以使用 wallet() 方法通过 wallet() 方法访问特定钱包类型

$pesoWallet = $user->wallet('Peso Wallet'); // This method also accepts the ID of the wallet type as a parameter

$pesoWallet->incrementBalance(100);

$pesoWallet->balance; // Returns the updated balance without having to refresh the model.

钱包中进行的所有操作都记录在 wallet_ledgers 表中。

定义交易

理想情况下,我们希望通过将其链接到交易模型来记录与钱包相关的所有交易。假设我们有一个 PurchaseTransaction 模型,该模型存储用户在我们的应用程序中进行的购买数据。

use Illuminate\Database\Eloquent\Model;

class PurchaseTransaction extends Model
{
    //
}

我们可以通过将 WalletTransaction 协议实现到此模型并使用此交易来减少(或增加,视情况而定)钱包余额来将此 PurchaseTransaction 连接到钱包账本。

use CoreProc\WalletPlus\Contracts\WalletTransaction;
use Illuminate\Database\Eloquent\Model;

class PurchaseTransaction extends Model implements WalletTransaction
{
    public function getAmount() 
    {
        return $this->amount;
    }
}

现在我们可以在钱包中使用它

$wallet = $user->wallet('Peso Wallet');

$purchaseTransaction = PurchaseTransaction::create([
    ...,
    'amount' => 100,
]);

$wallet->decrementBalance($purchaseTransaction);

通过这样做,您将在 wallet_ledgers 表中看到与钱包中的移动相关的交易。

测试

🧹 使用 Pint 保持现代代码库

composer lint

✅ 使用 Rector 运行重构

composer refacto

⚗️ 使用 PHPStan 运行静态分析

composer test:types

✅ 使用 PEST 运行单元测试

composer test:unit

🚀 运行整个测试套件

composer test

更新日志

请参阅 CHANGELOG 了解最近更改的信息。

贡献

请参阅 CONTRIBUTING 了解详细信息。

致谢

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件