laravel 钱包

1.安装插件

composer require bavix/laravel-wallet

2.发布资源和配置文件

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

3.执行数据迁移

4.使用
User模型

use Bavix\Wallet\Traits\HasWallet;
use Bavix\Wallet\Interfaces\Wallet;
use Bavix\Wallet\Traits\CanPay;
use Bavix\Wallet\Interfaces\Customer;

class User extends Authenticatable implements Wallet, Customer
{
    use HasWallet, CanPay;
}

产品模型,带标题title和价格price字段

use Bavix\Wallet\Traits\HasWallet;
use Bavix\Wallet\Interfaces\Customer;
use Bavix\Wallet\Interfaces\ProductInterface;

class Product extends Model implements ProductInterface
{
    use HasWallet;

    public function canBuy(Customer $customer, int $quantity = 1, bool $force = false): bool
    {
        return true; 
    }
    
    public function getAmountProduct(Customer $customer): int|string
    {
        return $this->price;
    }

    public function getMetaProduct(): ?array
    {
        return [
            'title' => '购买附件',
            'description' => '来自:'.$this->title,
        ];
    }
}

控制器

Auth::user()->balance; // 我的余额

Auth::user()->pay($model); // 根据$model数据中price支付
dd(Auth::user()->paid($model)); // 是否已购买

$user->deposit(100, ['description'=>'test']); // 存入,原因
$user->withdraw(1, ['description' => 'payment of taxes']); // 扣除(余额不足报错),原因
$user->forceWithdraw(200, ['description' => 'payment of taxes']); // 强扣(允许余额扣成负值),原因
相关文章