Readouble

Laravel 5.1 Laravelキャッシャー

イントロダクションIntroduction

LaravelキャッシャーはStripeによるサブスクリプション(定期課金)サービスの読みやすく、スラスラと記述できるインターフェイスを提供します。これにより書くことが恐ろしくなるような、サブスクリプション支払いのための決まりきったコードのほとんどが処理できます。基本的なサブスクリプション管理に加え、キャッシャーはクーポン、サブスクリプションの変更、購入数、キャンセル猶予期間、さらにインボイスのPDF発行まで行います。Laravel Cashier provides an expressive, fluent interface to Stripe's[https://stripe.com] subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs.

設定Configuration

ComposerComposer

最初に、composer.jsonファイルに、Cashierパッケージを追加し、composer updateコマンドを実行します。First, add the Cashier package to your composer.json file and run the composer update command:

"laravel/cashier": "~5.0"(2015年2月18日以降のバージョン、およびStripe SDK 2.0まで)
"laravel/cashier": "~4.0"(2015年2月18日以降のバージョン)
"laravel/cashier": "~3.0"(2015年2月16日までのバージョン)

サービスプロバイダーService Provider

次にapp設定ファイルへ、Laravel\Cashier\CashierServiceProviderサービスプロバイダーを登録します。Next, register the Laravel\Cashier\CashierServiceProvider service provider[/docs/{{version}}/providers] in your app configuration file.

マイグレーションMigration

キャッシャーを使用する前に、データベースにいくつかカラムを追加する必要があります。心配ありません。cashier:table Artisanコマンドで必要なカラムを追加するマイグレーションが生成されます。たとえばusersテーブルにカラムを追加するには、php artisan cashier:table usersを実行します。Before using Cashier, we'll need to add several columns to your database. Don't worry, you can use the cashier:table Artisan command to create a migration to add the necessary column. For example, to add the column to the users table run the command: php artisan cashier:table users.

マイグレーションを生成したら、後はmigrateコマンドを実行するだけです。Once the migration has been created, simply run the migrate command.

モデルの準備Model Setup

次にBillableトレイトと適切な日付ミューテターをモデルで定義してください。Next, add the Billable trait and appropriate date mutators to your model definition:

use Laravel\Cashier\Billable;
use Laravel\Cashier\Contracts\Billable as BillableContract;

class User extends Model implements BillableContract
{
    use Billable;

    protected $dates = ['trial_ends_at', 'subscription_ends_at'];
}

モデルの$datesプロパティにカラムを追加することで、Eloquentに文字列ではなくCarbon/DateTimeインスタンスを指定カラムで返すように指示します。Adding the columns to your model's $dates property will instruct Eloquent to return the columns as Carbon / DateTime instances instead of raw strings.

StripeキーStripe Key

最後に、services.php設定ファイルへStripeキーを設置します。Finally, set your Stripe key in your services.php configuration file:

'stripe' => [
    'model'  => 'User',
    'secret' => env('STRIPE_API_SECRET'),
],

サブスクリプションSubscriptions

サブスクリプション作成Creating Subscriptions

サブスクリプションを作成するには最初にbillableなモデルのインスタンスを取得しますが、通常App\Userのインスタンスでしょう。モデルインスタンスが獲得できたら、モデルのサブスクリプションを管理するためにsubscriptionメソッドを使います。To create a subscription, first retrieve an instance of your billable model, which typically will be an instance of App\User. Once you have retrieved the model instance, you may use the subscription method to manage the model's subscription:

$user = User::find(1);

$user->subscription('monthly')->create($creditCardToken);

createメソッドは自動的にStripeのサブスクリプションを作成すると同時に、StripeのカスタマーIDと関連する支払い情報をデータベースに保存します。Stripeでプランの試用期間を設定している場合、試用終了日も自動的に、ユーザーのレコードに設定されます。The create method will automatically create the Stripe subscription, as well as update your database with Stripe customer ID and other relevant billing information. If your plan has a trial configured in Stripe, the trial end date will also automatically be set on the user record.

Stripeの中で定義しているものではなく、アプリケーション独自の試用期間を実装したい場合は、試用終了日を自前で設定する必要があります。If you want to implement trial periods, but are managing the trials entirely within your application instead of defining them within Stripe, you must manually set the trial end date:

$user->trial_ends_at = Carbon::now()->addDays(14);

$user->save();

ユーザー詳細情報の指定Additional User Details

ユーザーに関する詳細情報を追加したい場合は、createメソッドの第2引数に渡すことができます。If you would like to specify additional customer details, you may do so by passing them as the second argument to the create method:

$user->subscription('monthly')->create($creditCardToken, [
    'email' => $email, 'description' => 'Our First Customer'
]);

Stripeがサポートしている追加のフィールドについては、顧客の作成に関するドキュメントを確認してください。To learn more about the additional fields supported by Stripe, check out Stripe's documentation on customer creation[https://stripe.com/docs/api#create_customer].

クーポンCoupons

サブスクリプションの作成時に、クーポンを適用したい場合は、withCouponメソッドを使用してください。If you would like to apply a coupon when creating the subscription, you may use the withCoupon method:

$user->subscription('monthly')
     ->withCoupon('code')
     ->create($creditCardToken);

サブスクリプション状態の確認Checking Subscription Status

ユーザーがアプリケーションで何かをサブスクリプションしたら、バラエティー豊かで便利なメソッドでサブスクリプション状況を簡単にチェックできます。まず初めにsubscribedメソッドがtrueを返したら、サブスクリプションが現在試用期間であるにしても、そのユーザーはアクティブなサブスクリプションを持っています。Once a user is subscribed to your application, you may easily check their subscription status using a variety of convenient methods. First, the subscribed method returns true if the user has an active subscription, even if the subscription is currently within its trial period:

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

subscribedメソッドはルートミドルウェアで使用しても大変役に立つでしょう。ユーザーのサブスクリプション状況に基づいてルートやコントローラーへのアクセスをフィルタリングできます。The subscribed method also makes a great candidate for a route middleware[/docs/{{version}}/middleware], allowing you to filter access to routes and controllers based on the user's subscription status:

public function handle($request, Closure $next)
{
    if ($request->user() && ! $request->user()->subscribed()) {
        // このユーザーは支払っていない顧客…
        return redirect('billing');
    }

    return $next($request);
}

ユーザーがまだ試用期間であるかを調べるには、onTrialメソッドを使用します。このメソッドはまだ使用期間中であるとユーザーに警告を表示するために便利です。If you would like to determine if a user is still within their trial period, you may use the onTrial method. This method can be useful for displaying a warning to the user that they are still on their trial period:

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

onPlanメソッドはStripe IDに基づく指定プランのサブスクリプション購入者であるかを調べます。The onPlan method may be used to determine if the user is subscribed to a given plan based on its Stripe ID:

if ($user->onPlan('monthly')) {
    //
}

キャンセルしたサブスクリプションの状態Cancelled Subscription Status

ユーザーが一度アクティブなサブスクリプション購入者になってから、サブスクリプションをキャンセルしたことを調べるには、cancelledメソッドを使用します。To determine if the user was once an active subscriber, but has cancelled their subscription, you may use the cancelled method:

if ($user->cancelled()) {
    //
}

また、ユーザーがサブスクリプションをキャンセルしているが、まだ完全に期限が切れる前の「猶予期間」中であるかを調べることもできます。例えば、ユーザーが3月5日にサブスクリプションをキャンセルし、3月10日に無効になる場合、そのユーザーは3月10日までは「猶予期間」中です。subscribedメソッドは、この期間中、まだtureを返すことに注目して下さい。You may also determine if a user has cancelled their subscription, but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. Note that the subscribed method still returns true during this time.

if ($user->onGracePeriod()) {
    //
}

everSubscribedメソッドにより、そのユーザーがアプリケーションの永久サブスクリプションプランを持っているかを決定することができます。The everSubscribed method may be used to determine if the user has ever subscribed to a plan in your application:

if ($user->everSubscribed()) {
    //
}

プラン変更Changing Plans

アプリケーションのサブスクリプション済みユーザーが新しいサブスクリプションプランへ変更したくなるのはよくあるでしょう。ユーザーを新しいサブスクリプションに変更するには、swapメソッドを使用します。例としてユーザーをささっとpremiumサブスクリプションプランへ変更してみましょう。After a user is subscribed to your application, they may occasionally want to change to a new subscription plan. To swap a user to a new subscription, use the swap method. For example, we may easily switch a user to the premium subscription:

$user = App\User::find(1);

$user->subscription('premium')->swap();

ユーザーが試用期間中の場合、試用期間は通常通りに続きます。また、そのサブスクリプションに"quantity"(購入数)が存在する場合、その個数も維持されます。プランの変更時にprorateメソッドを使うことで支払いの按分を指示することもできます。さらにswapAndInvoiceメソッドでプラン変更のインボイスを即座に発行することもできます。If the user is on trial, the trial period will be maintained. Also, if a "quantity" exists for the subscription, that quantity will also be maintained. When swapping plans, you may also use the prorate method to indicate that the charges should be pro-rated. In addition, you may use the swapAndInvoice method to immediately invoice the user for the plan change:

$user->subscription('premium')
            ->prorate()
            ->swapAndInvoice();

購入数Subscription Quantity

しばしばサブスクリプションは「個数(quantity)」による影響を受けます。たとえばアプリケーションで毎月10ドルアカウントのユーザーごとに課金している場合です。購入数を簡単に増やしたり、減らしたりするには、incrementdecrementメソッドを使用します。Sometimes subscriptions are affected by "quantity". For example, your application might charge $10 per month per user on an account. To easily increment or decrement your subscription quantity, use the increment and decrement methods:

$user = User::find(1);

$user->subscription()->increment();

// 現在の購入数に5つ増やす…
 $user->subscription()->increment(5);

$user->subscription()->decrement();

// 現在の購入数から5つ減らす…
$user->subscription()->decrement(5);

もしくは特定の数量を設置するには、updateQuantityメソッドを使ってください。Alternatively, you may set a specific quantity using the updateQuantity method:

$user->subscription()->updateQuantity(10);

購入数の詳細については、Stripeドキュメントを読んでください。For more information on subscription quantities, consult the Stripe documentation[https://stripe.com/docs/guides/subscriptions#setting-quantities].

サブスクリプションの税金Subscription Taxes

キャッシャーを使えばStripeへ「税率(tax_percent)」を送るのも簡単です。サブスクリプションに対する顧客の支払いの税率を指定するには、モデルにgetTaxPercentメソッドをbillableモデルへ実装し、小数点以下の桁数が2桁以内で0から100までの数値を返します。With Cashier, it's easy to provide the tax_percent value sent to Stripe. To specify the tax percentage a user pays on a subscription, implement the getTaxPercent method on your billable model, and return a numeric value between 0 and 100, with no more than 2 decimal places.

public function getTaxPercent() {
    return 20;
}

これによりモデルごとに税率を適用できるため、多くの州や国に渡るユーザーベースで税率を決める場合に便利です。This enables you to apply a tax rate on a model-by-model basis, which may be helpful for a user base that spans multiple countries.

サブスクリプションキャンセルCancelling Subscriptions

サブスクリプションをキャンセルするにはcancelメソッドをユーザーのサブスクリプションに対して使ってください。To cancel a subscription, simply call the cancel method on the user's subscription:

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

サブスクリプションがキャンセルされるとキャッシャーは自動的に、データベースのsubscription_ends_atカラムをセットします。このカラムはいつからsubscribedメソッドがfalseを返し始めればよいのか、判定するために使用されています。例えば、顧客が3月1日にキャンセルしたが、そのサブスクリプションが3月5日に終了するようにスケジュールされていれば、subscribedメソッドは3月5日になるまでtrueを返し続けます。When a subscription is cancelled, Cashier will automatically set the subscription_ends_at column in your database. This column is used to know when the subscribed method should begin returning false. For example, if a customer cancels a subscription on March 1st, but the subscription was not scheduled to end until March 5th, the subscribed method will continue to return true until March 5th.

ユーザーがサブスクリプションをキャンセルしたが、まだ「猶予期間」が残っているかどうかを調べるにはonGracePeriodメソッドを使います。You may determine if a user has cancelled their subscription but are still on their "grace period" using the onGracePeriod method:

if ($user->onGracePeriod()) {
    //
}

サブスクリプション再開Resuming Subscriptions

ユーザーがキャンセルしたサブスクリプションを、再開したいときには、resumeメソッドを使用してください。If a user has cancelled their subscription and you wish to resume it, use the resume method:

$user->subscription('monthly')->resume($creditCardToken);

ユーザーがサブスクリプションをキャンセルし、それからそのサブスクリプションを再開する場合、そのサブスクリプションの有効期日が完全に切れていなければすぐに課金されません。そのサブスクリプションはシンプルに再度有効になり、元々の支払いサイクルにより課金されますIf the user cancels a subscription and then resumes that subscription before the subscription has fully expired, they will not be billed immediately. Instead, their subscription will simply be re-activated, and they will be billed on the original billing cycle.

StripeのWebフック処理Handling Stripe Webhooks

サブスクリプション不可Failed Subscriptions

顧客のクレジットカードが有効期限切れだったら? 心配いりません。キャッシャーは顧客のサブスクリプションを簡単にキャンセルできるWebフックコントローラーを含んでいます。コントローラーのルートを指定するだけです。What if a customer's credit card expires? No worries - Cashier includes a Webhook controller that can easily cancel the customer's subscription for you. Just point a route to the controller:

Route::post('stripe/webhook', '\Laravel\Cashier\WebhookController@handleWebhook');

これだけです! 課金の失敗はコントローラーにより捉えられ、処理されます。コントローラーはStripeによりサブスクリプションが不能だと判断されると(通常は課金に3回失敗時)、その顧客のサブスクリプションをキャンセルします。Stripeのコントロールパネル設定でWebフックURIを設定する必要があります。That's it! Failed payments will be captured and handled by the controller. The controller will cancel the customer's subscription when Stripe determines the subscription has failed (normally after three failed payment attempts). Don't forget: you will need to configure the webhook URI in your Stripe control panel settings.

StripeのWebフックはLaravelのCSRF確認を適用しない必要があるため、VerifyCsrfTokenミドルウェアで除外するURIのリストへ確実に登録してください。Since Stripe webhooks need to bypass Laravel's CSRF verification[/docs/{{version}}/routing#csrf-protection], be sure to list the URI as an exception in your VerifyCsrfToken middleware:

protected $except = [
    'stripe/*',
];

その他のWebフックOther Webhooks

処理したい追加のStripe Webフックイベントがある場合、シンプルにWebフックコントローラーを拡張してください。メソッド名はCashierが期待する命名規則に従う必要があります。つまりメソッド名はhandleで始まり、取り扱いたいStripeのWebフックを続けます。たとえばinvoice.payment_succeeded Webフックを使用したいのなら、コントローラーにはhandleInvoicePaymentSucceededメソッドを追加しなければなりません。If you have additional Stripe webhook events you would like to handle, simply extend the Webhook controller. Your method names should correspond to Cashier's expected convention, specifically, methods should be prefixed with handle and the "camel case" name of the Stripe webhook you wish to handle. For example, if you wish to handle the invoice.payment_succeeded webhook, you should add a handleInvoicePaymentSucceeded method to the controller.

<?php

namespace App\Http\Controllers;

use Laravel\Cashier\WebhookController as BaseController;

class WebhookController extends BaseController
{
    /**
     * StripeのWebフック処理
     *
     * @param  array  $payload
     * @return Response
     */
    public function handleInvoicePaymentSucceeded($payload)
    {
        // イベントの処理
    }
}

一回だけの課金Single Charges

定期サブスクリプションしている顧客のクレジットカードに対し「一回限り」の課金を行いたい場合は、billableモデルに対しchargeメソッドを使用してください。chargeメソッドは通貨の最低単位の課金を引数に取ります。そのため次の例は100セント(1ドル)をクレジットカードへ課金します。If you would like to make a "one off" charge against a subscribed customer's credit card, you may use the charge method on a billable model instance. The charge method accepts the amount you would like to charge in the lowest denominator of the currency used by your application. So, for example, the example below will charge 100 cents, or $1.00, against the user's credit card:

$user->charge(100);

chargeメソッドは配列で2つ目の引数も取り、裏で動作しているStrip課金の生成にオプションを渡すことができます。The charge method accepts an array as its second argument, allowing you to pass any options you wish to the underlying Stripe charge creation:

$user->charge(100, [
    'source' => $token,
    'receipt_email' => $user->email,
]);

chargeメソッドがfalseを返した場合は課金失敗です。通常これは課金が拒否されたことを意味します。The charge method will return false if the charge fails. This typically indicates the charge was denied:

if ( ! $user->charge(100)) {
    // 課金は拒否された…
}

課金が成功したら完全なStripeレスポンスがメソッドから返されます。If the charge is successful, the full Stripe response will be returned from the method.

インボイスInvoices

invoicesメソッドにより、billableモデルのインボイスの配列を簡単に取得できます。You may easily retrieve an array of a billable model's invoices using the invoices method:

$invoices = $user->invoices();

顧客へインボイスを一覧表示するとき、そのインボイスに関連する情報を表示するために、インボイスのヘルパメソッドを表示に利用できます。ユーザーが簡単にダウンロードできるように、テーブルで全インボイスを一覧表示する例を見てください。When listing the invoices for the customer, you may use the invoice's helper methods to display the relevant invoice information. For example, you may wish to list every invoice in a table, allowing the user to easily download any of them:

<table>
    @foreach ($invoices as $invoice)
        <tr>
            <td>{{ $invoice->dateString() }}</td>
            <td>{{ $invoice->dollars() }}</td>
            <td><a href="/user/invoice/{{ $invoice->id }}">ダウンロード</a></td>
        </tr>
    @endforeach
</table>

インボイスPDF生成Generating Invoice PDFs

ルートやコントローラーの中でdownloadInvoiceメソッドを使うと、そのインボイスのPDFダウンロードを生成できます。このメソッドはブラウザへダウンロードのHTTPレスポンスを正しく行うHTTPレスポンスを生成します。From within a route or controller, use the downloadInvoice method to generate a PDF download of the invoice. This method will automatically generate the proper HTTP response to send the download to the browser:

Route::get('user/invoice/{invoice}', function ($invoiceId) {
    return Auth::user()->downloadInvoice($invoiceId, [
        'vendor'  => 'Your Company',
        'product' => 'Your Product',
    ]);
});

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作