Laravel Cashier - 使用付款方式创建订阅的单元测试

标签 laravel stripe-payments laravel-cashier

更深入地研究这一点,我不确定这是否可能,这是一种耻辱,因为我正在尝试学习 TDD。

我想用 Billable 测试我的模型正在创建并订阅计划。

/** @test */
public function an_account_can_subscribe_to_a_plan() {
    $account = factory("App\Account")->create();

    Stripe::setApiKey('key');
    $paymentMethod = PaymentMethod::create([
        'type' => 'card',
        'card' => [
            'number' => '4242424242424242',
            'exp_month' => '2',
            'exp_year' => '2021',
            'cvc' => '314'
        ]
    ]);

    $subscription = $account->newSubscription('default', 'starter')->create($paymentMethod);
    $this->assertTrue( $subscription->valid() );  
}

Laravel Cashier 文档展示了如何通过 Stripe.js 发送 token ,但这不适用于单元测试。

我尝试直接包含 Stripe 库并创建一个 PaymentMethod对象,但这也需要我手动设置 API key 。现在我得到的错误是我必须验证我的电话号码才能将原始信用卡号码发送到 strip API。

我希望有更好的方法。如何以 TDD 方式使用 Laravel Cashier 并使用虚假付款方式模拟虚假订阅?

最佳答案

Stripe 不仅提供测试卡号,还提供代币和支付方式。

https://stripe.com/docs/testing#cards

单击 PaymentMethods 选项卡。该值(例如 pm_card_visa )可以在您的测试中直接在服务器端使用,无需前端支付意图实现。

这是我的功能测试示例:

    /**
     * @test
     */
    public function a_user_can_subscribe_to_a_paid_plan()
    {

        $this->actingAs($this->user);
        $this->setUpBilling();

        $enterprise = Plan::where('name', 'Enterprise')->first()->stripe_plan_id;

        $response = $this->post(route('paywall.payment'), [
            'payment_method' => 'pm_card_visa',
            'stripe_plan_id' => $enterprise
        ])
        ->assertSessionDoesntHaveErrors()
        ->assertRedirect();

    }

您的测试可能会有所不同,但您可以使用这些测试付款方式向您的计费 Controller 发出正常请求,并且它会像在前端执行一样进行。

关于Laravel Cashier - 使用付款方式创建订阅的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60398112/

相关文章:

Laravel 收银员在卡更新后重新尝试待处理发票

Laravel 5.2 和收银员

php - 显示特定类别 laravel 5

javascript - 选择单选按钮后的文本输入字段

java - 如何从Stripe API中的收费对象中扣除申请费?

javascript - 使用 Stripe V3 为卡创建 strip 标记,但不使用前端侧的 strip 元素

laravel-5 - Laravel 收银员列出所有发票和总计

php - HTML2PDF - 下载 pdf 文件并将其显示到页面

php - Laravel 表 : there can be only one auto column and it must be defined as a key

node.js - 错误 : TypeError: Cannot read property 'create' of undefined on stripe. 文件上传.create