Easy work with virtual wallet

分享链接:https://github.com/bavix/laravel-wallet

laravel-wallet

Scrutinizer Code Quality
Code Coverage
Build Status
Code Intelligence Status

Package Rank
Latest Stable Version
Latest Unstable Version
License
composer.lock

laravel-wallet - Easy work with virtual wallet.

  • Vendor: bavix
  • Package: laravel-wallet
  • Version: Latest Stable Version
  • PHP Version: 7.1+
  • Laravel Version: 5.5, 5.6, 5.7
  • Composer: composer require bavix/laravel-wallet

Run Migrations

Publish the migrations with this artisan command:

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

Configuration

You can publish the config file with this artisan command:

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

Usage

Add the HasWallet trait and Wallet interface to model.

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

class User extends Model implements Wallet
{
    use HasWallet;
}

Now we make transactions.

$user = User::first();
$user->balance; // int(0)

$user->deposit(10);
$user->balance; // int(10)

$user->withdraw(1);
$user->balance; // int(9)

$user->forceWithdraw(200, ['description' => 'payment of taxes']);
$user->balance; // int(-191)

Purchases

Add the CanBePaid trait and Customer interface to your User model.

use Bavix\Wallet\Traits\CanBePaid;
use Bavix\Wallet\Interfaces\Customer;

class User extends Model implements Customer
{
    use CanBePaid;
}

Add the HasWallet trait and Product interface to Item model.

use Bavix\Wallet\Traits\HasWallet;
use Bavix\Wallet\Interfaces\Product;

class Item extends Model implements Product
{
    use HasWallet;

    public function canBuy(Customer $customer, bool $force = false): bool
    {
        /**
         * If the service can be purchased once, then
         *  return !$customer->paid($this);
         */
        return true; 
    }

    public function getAmountProduct(): int
    {
        return 100;
    }

    public function getMetaProduct(): ?array
    {
        return [
            'title' => $this->title, 
            'description' => 'Purchase of Product #' . $this->id, 
            'price' => $this->getAmountProduct(),
        ];
    }
}

Proceed to purchase.

$user = User::first();
$user->balance; // int(100)

$item = Item::first();
$user->pay($item); // If you do not have enough money, throw an exception
var_dump($user->balance); // int(0)

if ($user->safePay($item)) {
  // try to buy again )
}

var_dump((bool)$user->paid($item)); // bool(true)

var_dump($user->refund($item)); // bool(true)
var_dump((bool)$user->paid($item)); // bool(false)

Eager Loading

User::with('balance');

Supported by

Supported by JetBrains

故地有明月, 何慕异乡圆.
wenber
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!