coreproc / laravel-wallet-plus
轻松为Laravel模型添加虚拟钱包。具有多个钱包和账本系统,帮助跟踪所有钱包交易。
Requires
- php: ^7.3 || ^8.0
Requires (Dev)
- phpunit/phpunit: ^8.2 || ^9.3
- symfony/var-dumper: ^4.3 || ^5.1 || ^6.0
README
轻松为Laravel模型添加虚拟钱包。具有多个钱包和账本系统,帮助跟踪所有钱包交易。
安装
您可以通过Composer安装此包
composer require coreproc/laravel-wallet-plus
您可以使用以下命令发布迁移
php artisan vendor:publish --provider="CoreProc\WalletPlus\WalletPlusServiceProvider" --tag="migrations"
迁移文件发布后,您可以运行迁移来创建wallet-plus表
php artisan migrate
用法
首先,您需要将HasWallets
特性添加到模型中。
use CoreProc\WalletPlus\Models\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()
方法访问模型的特定钱包类型
$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
表中看到与钱包操作相关的交易。
测试
composer test
变更日志
有关最近更改的更多信息,请参阅CHANGELOG。
贡献
有关详细信息,请参阅CONTRIBUTING。
安全性
如果您发现任何安全问题,请通过电子邮件chris.bautista@coreproc.ph联系,而不是使用问题跟踪器。
鸣谢
许可
MIT许可证(MIT)。有关更多信息,请参阅许可文件。