yii2mod/yii2-braintree

Yii2 Braintree 提供了对 Braintree 订阅计费服务的接口。

安装数: 1,079

依赖者: 0

建议者: 0

安全性: 0

星星: 9

关注者: 4

分支: 2

开放问题: 1

类型:yii2-extension

1.4 2016-11-22 14:44 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:37:01 UTC


README

Yii 2 的 Braintree 扩展


此扩展是 Laravel Cashier Braintree 包 的移植版本

Latest Stable Version Total Downloads License Build Status

安装

安装此扩展的最佳方式是通过 composer

运行以下命令

php composer.phar require --prefer-dist yii2mod/yii2-braintree "*"

或者在您的 composer.json 文件的 require 部分添加以下内容

"yii2mod/yii2-braintree": "*"

Braintree 配置

计划信用优惠券

在开始使用 Braintree 的 Cashier 之前,您需要在您的 Braintree 控制面板中定义一个计划信用折扣。此折扣将用于正确处理从年费到月费或从月费到年费的订阅变更。在 Braintree 控制面板中配置的折扣金额可以是任何您希望的价值,因为 Cashier 将在每次应用优惠券时用我们自己的自定义金额覆盖定义的金额。

数据库迁移

在开始使用 Braintree 之前,我们还需要准备数据库。

$tableOptions = null;

if ($this->db->driverName === 'mysql') {
    $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}

$this->createTable('subscription', [
    'id' => $this->primaryKey(),
    'userId' => $this->integer()->notNull(),
    'name' => $this->string()->notNull(),
    'braintreeId' => $this->string()->notNull(),
    'braintreePlan' => $this->string()->notNull(),
    'quantity' => $this->integer()->notNull(),
    'trialEndAt' => $this->timestamp()->null(),
    'endAt' => $this->timestamp()->null(),
    'createdAt' => $this->timestamp()->null(),
    'updatedAt' => $this->timestamp()->null()
], $tableOptions);

$this->addColumn('user', 'braintreeId', $this->string());
$this->addColumn('user', 'paypalEmail', $this->string());
$this->addColumn('user', 'cardBrand', $this->string());
$this->addColumn('user', 'cardLastFour', $this->string());
$this->addColumn('user', 'trialEndAt', $this->timestamp()->null());

您还可以通过以下命令应用迁移

php yii migrate --migrationPath=@vendor/yii2mod/yii2-braintree/migrations

模型设置

接下来,将 Billable 特性添加到您的 User 模型定义中

use yii2mod\braintree\Billable;

class User extends ActiveRecord implements IdentityInterface
{
    use Billable;
}

提供者密钥

接下来,您应该在配置文件中的 bootstrap 部分添加 yii2mod\braintree\BraintreeBootstrap

'bootstrap' => [
    // your other bootstrap components
    [
       'class' => 'yii2mod\braintree\BraintreeBootstrap',
       'environment' => 'braintree env',
       'merchantId' => 'braintree merchantId',
       'publicKey' => 'braintree public key',
       'privateKey' => 'braintree private key',
    ] 
],

订阅

创建订阅

要创建订阅,首先获取您的可计费模型实例,通常是 models\User 的实例。一旦获取了模型实例,您就可以使用 newSubscription 方法创建模型的订阅

$user = User::findOne(1);

$user->newSubscription('main', 'monthly')->create($creditCardToken);

传递给 newSubscription 方法的第一个参数应该是订阅的名称。如果您的应用程序只提供一种订阅,您可能将其称为主要或主要。第二个参数是用户订阅的特定 Braintree 计划。此值应与 Braintree 中计划的标识符相对应。

create 方法将自动创建订阅,并更新您的数据库以包含客户 ID 和其他相关计费信息。

用户其他详细信息

如果您想指定其他客户详细信息,可以在 create 方法的第二个参数中传递它们

$user->newSubscription('main', 'monthly')->create($creditCardToken, [
    'description' => 'Customer for test@example.com'
]);

有关 Braintree 支持的更多字段的详细信息,请参阅 Braintree 文档

优惠券

如果您在创建订阅时想应用优惠券,可以使用 withCoupon 方法

$user->newSubscription('main', 'monthly')
     ->withCoupon('code')
     ->create($creditCardToken);

检查订阅状态

一旦用户订阅了您的应用程序,您可以使用各种方便的方法轻松检查他们的订阅状态。首先,subscribed 方法返回 true,如果用户有一个有效的订阅,即使该订阅目前处于试用期

if ($user->subscribed('main')) {
    //
}

如果您想确定用户是否仍在试用期,可以使用 onTrial 方法。此方法可用于向用户显示警告,说明他们仍在试用期

if ($user->subscription('main')->onTrial()) {
    //
}

subscribedToPlan 方法可用于确定用户是否根据给定的 Braintree 计划 ID 订阅了给定的计划。在此示例中,我们将确定用户的主要订阅是否正在订阅月度计划

if ($user->subscribedToPlan('monthly', 'main')) {
    //
}

已取消订阅状态

要确定用户是否曾经是活跃订阅者,但已取消订阅,您可以使用取消方法。

if ($user->subscription('main')->cancelled()) {
    //
}

您还可以确定用户是否已取消订阅,但仍然处于“宽限期”直到订阅完全到期。例如,如果用户于3月5日取消了一个原定于3月10日到期的订阅,那么用户将处于“宽限期”直到3月10日。请注意,在此期间,已订阅方法仍然返回true。

if ($user->subscription('main')->onGracePeriod()) {
    //
}

更改计划

用户订阅了您的应用程序后,他们可能偶尔想要切换到新的订阅计划。要切换用户到新的订阅,请使用swap方法。例如,我们可以轻松地将用户切换到高级订阅。

$user = User::findOne(1);

$user->subscription('main')->swap('provider-plan-id');

如果用户处于试用期,试用期将保持不变。此外,如果订阅存在“数量”,则该数量也将保持不变。

$user->subscription('main')->swap('provider-plan-id');

如果您想要切换计划但跳过要切换到的计划中的试用期,您可以使用skipTrial方法。

$user->subscription('main')
        ->skipTrial()
        ->swap('provider-plan-id');

订阅税费

使用Cashier,很容易提供发送给Braintree的tax_percent值。要指定用户在订阅上支付的税率,请在您的计费模型上实现taxPercentage方法,并返回一个介于0到100之间的数值,最多保留两位小数。

public function taxPercentage() {
    return 20;
}

这使您能够根据模型应用税率,这可能有助于跨越多个国家的用户基础。

取消订阅

要取消订阅,只需在用户的订阅上调用cancel方法。

$user->subscription('main')->cancel();

当订阅被取消时,Cashier将自动设置您数据库中的endAt列。此列用于知道何时已订阅方法应开始返回false。例如,如果客户于3月1日取消订阅,但订阅原定于3月5日结束,则已订阅方法将继续返回true直到3月5日。

您可以使用onGracePeriod方法确定用户是否已取消订阅但仍在“宽限期”内。

if ($user->subscription('main')->onGracePeriod()) {
    //
}

恢复订阅

如果用户已取消订阅,并且您希望恢复它,请使用resume方法。用户必须仍在他们的宽限期才能恢复订阅。

$user->subscription('main')->resume();

如果用户取消订阅,然后在订阅完全到期之前恢复该订阅,他们不会立即被收费。相反,他们的订阅将简单地重新激活,并在原始计费周期中收费。

订阅试用期

信用卡预付费

如果您想在收集用户支付方式信息的同时为用户提供试用期,应在创建订阅时使用trialDays方法。

$user = User::findOne(1);

$user->newSubscription('main', 'monthly')
            ->trialDays(10)
            ->create($creditCardToken);

此方法将在数据库中的订阅记录上设置试用期结束日期,并指示Braintree在此日期之后不开始向客户收费。

如果客户在试用期结束日期之前未取消订阅,他们将一俟试用期到期立即被收费,因此您应该通知用户他们的试用期结束日期。您可以使用用户实例的onTrial方法或订阅实例的onTrial方法来确定用户是否处于试用期。以下两个示例在目的上基本相同。

if ($user->onTrial('main')) {
    //
}

if ($user->subscription('main')->onTrial()) {
    //
}

信用卡不预付费

如果您想在收集用户支付方式信息之前为用户提供试用期,您可以将用户记录上的trialEndAt列设置为所需的试用期结束日期。例如,这通常在用户注册期间完成。

$user = new User([
    // Populate other user properties...
    'trialEndAt' => Carbon::now()->addDays(10),
]);

收银员将此类试用称为“通用试用”,因为它与任何现有订阅无关。如果当前日期未超过trialEndAt的值,则User实例上的onTrial方法将返回true。

if ($user->onTrial()) {
    // User is within their trial period...
}

如果您想具体知道用户是否处于“通用”试用期内且尚未创建实际订阅,您也可以使用onGenericTrial方法。

if ($user->onGenericTrial()) {
    // User is within their "generic" trial period...
}

一旦您准备好为用户创建实际订阅,您就可以像往常一样使用newSubscription方法。

$user = User::findOne(1);

$user->newSubscription('main', 'monthly')->create($creditCardToken);

处理Braintree Webhooks

失败的订阅

只需将WebhookController添加到您的配置文件中的controllerMap即可。

'controllerMap' => [
        //Braintree webhook
        'webhook' => 'yii2mod\braintree\controllers\WebhookController',
    ],

就这样!失败的支付将被捕获并由控制器处理。当Braintree确定订阅失败时(通常在三次失败的支付尝试后),控制器将取消客户的订阅。别忘了:您需要在Braintree控制面板设置中配置webhook URI,例如:yoursite.com/webhook/handle-webhook

单次收费

简单收费

在使用Braintree时,您应将完整美元金额传递给charge方法。

如果您想对订阅客户的信用卡进行一次性的收费,您可以使用账单模型实例上的charge方法。

// Braintree Accepts Charges In Dollars...
$user->charge(1);

charge方法接受一个数组作为其第二个参数,允许您将任何选项传递给底层的Braintree收费创建。

$user->charge(100, [
    'custom_option' => $value,
]);

如果收费失败,charge方法将抛出异常。如果收费成功,方法将返回完整的Braintree响应。

try {
    $response = $user->charge(100);
} catch (Exception $e) {
    //
}

带发票的收费

有时您可能需要一次性收费,但也要为收费生成发票,以便您可以为客户提供PDF收据。invoiceFor方法可以让您做到这一点。例如,为“一次性费用”向客户开票$5.00。

// Braintree Accepts Charges In Dollars...

$user->invoiceFor('One Time Fee', 5);

发票将立即对用户的信用卡进行收费。invoiceFor方法也接受一个数组作为第三个参数,允许您将任何选项传递给底层的Braintree收费创建。

$user->invoiceFor('One Time Fee', 500, [
    'custom-option' => $value,
]);

发票

您可以使用invoices方法轻松检索账单模型的发票数组。

$invoices = $user->invoices(); // yii2mod\collection\Collection object

在列出客户的发票时,您可以使用发票的辅助方法来显示相关的发票信息。例如,您可能希望在一个GridView中列出每个发票,使用户能够轻松下载其中任何一个。

$dataProvider = new \yii\data\ArrayDataProvider([
            'allModels' => $invoices->all(),
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

 echo yii\grid\GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            [
                'label' => 'Invoice Date',
                'value' => function ($model) {
                    return $model->date()->toFormattedDateString();
                }
            ],
            [
                'label' => 'Total',
                'value' => function ($model) {
                    return $model->total();
                }
            ],
            [
                'header' => 'Action',
                'class' => 'yii\grid\ActionColumn',
                'template' => '{download}',
                'buttons' => [
                    'download' => function ($url, $model, $key) {
                        $options = [
                            'title' => Yii::t('yii', 'Download Invoice'),
                            'data-pjax' => '0',
                        ];
                        $url = ['download-invoice', 'invoiceId' => $model->id];
                        return \yii\helpers\Html::a('<span class="glyphicon glyphicon-download"></span>', $url, $options);
                    }
                ],
            ],
        ],
 ]);

生成发票PDF

在您的控制器中创建download-invoice操作,例如

public function actionDownloadInvoice($invoiceId)
{
    return $user->downloadInvoice($invoiceId, [
        'vendor' => 'Your Company',
        'product' => 'Your Product',
    ]);
}