Readouble

Laravel master Laravel Cashier

イントロダクションIntroduction

Laravel CashierはStripeBraintreeによるサブスクリプション(定期課金)サービスの読みやすく、スラスラと記述できるインターフェイスを提供します。これにより書くことが恐ろしくなるような、サブスクリプション支払いのための決まりきったコードのほとんどが処理できます。基本的なサブスクリプション管理に加え、Cashierはクーポン、サブスクリプションの変更、サブスクリプション数、キャンセル猶予期間、さらにインボイスのPDF発行まで行います。Laravel Cashier provides an expressive, fluent interface to Stripe's[https://stripe.com] and Braintree's[https://braintreepayments.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.

Note: note サブスクリプションを提供するのではなく、「一回だけ」の支払いを取り扱う場合は、Cashierを使用してはいけません。StripeかBraintreeのSDKを直接使用してください。{note} If you're only performing "one-off" charges and do not offer subscriptions. You should not use Cashier. You should use the Stripe and Braintree SDKs directly.

設定Configuration

StripeStripe

ComposerComposer

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

"laravel/cashier": "~7.0"

サービスプロバイダService Provider

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

データベースマイグレーションDatabase Migrations

Cashierを使用する前に、データベースを準備する必要があります。usersテーブルに、いくつかのカラムを追加し、顧客のサブスクリプション情報すべてを保持する新しいsubscriptionsテーブルを作成します。Before using Cashier, we'll also need to prepare the database[/docs/{{version}}/migrations]. We need to add several columns to your users table and create a new subscriptions table to hold all of our customer's subscriptions:

Schema::table('users', function ($table) {
    $table->string('stripe_id')->nullable();
    $table->string('card_brand')->nullable();
    $table->string('card_last_four')->nullable();
    $table->timestamp('trial_ends_at')->nullable();
});

Schema::create('subscriptions', function ($table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('name');
    $table->string('stripe_id');
    $table->string('stripe_plan');
    $table->integer('quantity');
    $table->timestamp('trial_ends_at')->nullable();
    $table->timestamp('ends_at')->nullable();
    $table->timestamps();
});

マイグレーションを作成したら、migrate Artisanコマンドを実行します。Once the migrations have been created, run the migrate Artisan command.

BillableモデルBillable Model

次に、モデル定義にBillableトレイトを追加します。このトレイトは、サブスクリプションの作成、クーポンの適用、クレジットカード情報の更新など、一般的な支払いタスクを実行する様々なメソッドを提供しています。Next, add the Billable trait to your model definition. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons, and updating credit card information:

use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;
}

APIキーAPI Keys

最後に、Stripeキーをservices.php設定ファイルへ設定します。Stripe APIキーはStripeのコントロールパネルから取得します。Finally, you should configure your Stripe key in your services.php configuration file. You can retrieve your Stripe API keys from the Stripe control panel:

'stripe' => [
    'model'  => App\User::class,
    'secret' => env('STRIPE_SECRET'),
],

BraintreeBraintree

Braintree CaveatsBraintree Caveats

多くの操作において、StripeとBraintreeで実装しているCashierの機能は同じものです。両方のサービスはクレジットカードでの支払いを提供していますが、BraintreeはPayPalでの支払いもサポートしています。しかしながら、Braintreeには、Stripeが提供してる機能のいくつかが欠けています。以下の点を考慮し、StripeとBraintreeのどちらを使うのか決めてください。For many operations, the Stripe and Braintree implementations of Cashier function the same. Both services provide subscription billing with credit cards but Braintree also supports payments via PayPal. However, Braintree also lacks some features that are supported by Stripe. You should keep the following in mind when deciding to use Stripe or Braintree:

- BraintreeはPayPalをサポートしていますが、Stripeはしていません。 - Braintreeはサブスクリプション数の`increment`(追加)と`decrement`(減少)メソッドをサポートしていません。これはCashierではなく、Braintreeの制限です。 - Braintreeはパーセンテージをもとにしたディスカウントはサポートしていません。これはCashierではなく、Braintreeの制限です。

ComposerComposer

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

"laravel/cashier-braintree": "~2.0"

サービスプロバイダService Provider

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

クレジットクーポンのプランPlan Credit Coupon

CashierをBraintreeで使用する前に、plan-creditディスカウントをBraintreeのコントロールパネルで定義する必要があります。このディスカウントは、年払いから月払い、もしくは月払いから年払いの変更時に代金を確実に按分するために使用されます。Before using Cashier with Braintree, you will need to define a plan-credit discount in your Braintree control panel. This discount will be used to properly prorate subscriptions that change from yearly to monthly billing, or from monthly to yearly billing.

ディスカウント値はBraintreeコントロールパネルで好きな値に設定できます。Cashierはクーポンを毎回適用するごとに、自身の定義済みカスタム値でディスカウント値をオーバーライドします。Braintreeは繰り返されるサブスクリプションに渡る、按分をネイティブにサポートしていないため、このクーポンが必要です。The discount amount configured in the Braintree control panel can be any value you wish, as Cashier will simply override the defined amount with our own custom amount each time we apply the coupon. This coupon is needed since Braintree does not natively support prorating subscriptions across subscription frequencies.

データベースマイグレーションDatabase Migrations

Cashierを使用する前に、データベースも準備する必要があります。usersテーブルにカラムをいくつか追加し、顧客のサブスクリプション情報を保存するために新しいsubscriptionsテーブルを作成します。Before using Cashier, we'll need to prepare the database[/docs/{{version}}/migrations]. We need to add several columns to your users table and create a new subscriptions table to hold all of our customer's subscriptions:

Schema::table('users', function ($table) {
    $table->string('braintree_id')->nullable();
    $table->string('paypal_email')->nullable();
    $table->string('card_brand')->nullable();
    $table->string('card_last_four')->nullable();
    $table->timestamp('trial_ends_at')->nullable();
});

Schema::create('subscriptions', function ($table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('name');
    $table->string('braintree_id');
    $table->string('braintree_plan');
    $table->integer('quantity');
    $table->timestamp('trial_ends_at')->nullable();
    $table->timestamp('ends_at')->nullable();
    $table->timestamps();
});

マイグレーションを作成したら、migrate Artisanコマンドを実行するだけです。Once the migrations have been created, simply run the migrate Artisan command.

BillableモデルBillable Model

次にBillableトレイをモデルに追加してください。Next, add the Billable trait to your model definition:

use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;
}

APIキーAPI Keys

次に、以下のオプションをservices.phpファイルで設定します。Next, You should configure the following options in your services.php file:

'braintree' => [
    'model'  => App\User::class,
    'environment' => env('BRAINTREE_ENV'),
    'merchant_id' => env('BRAINTREE_MERCHANT_ID'),
    'public_key' => env('BRAINTREE_PUBLIC_KEY'),
    'private_key' => env('BRAINTREE_PRIVATE_KEY'),
],

続いて以下のBraintree SDK呼び出しコードをAppServiceProviderサービスプロバイダのbootメソッドに追加します。Then you should add the following Braintree SDK calls to your AppServiceProvider service provider's boot method:

\Braintree_Configuration::environment(config('services.braintree.environment'));
\Braintree_Configuration::merchantId(config('services.braintree.merchant_id'));
\Braintree_Configuration::publicKey(config('services.braintree.public_key'));
\Braintree_Configuration::privateKey(config('services.braintree.private_key'));

通貨設定Currency Configuration

Cashierのデフォルト通貨は米ドル(USD)です。サービスプロバイダの一つで、bootメソッド中でCashier::useCurrencyメソッドを呼び出し、デフォルト通貨を変更可能です。useCurrencyメソッドは2つの文字列を引数に取ります。通貨と通貨記号です。The default Cashier currency is United States Dollars (USD). You can change the default currency by calling the Cashier::useCurrency method from within the boot method of one of your service providers. The useCurrency method accepts two string parameters: the currency and the currency's symbol:

use Laravel\Cashier\Cashier;

Cashier::useCurrency('eur', '€');

サブスクリプションSubscriptions

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

サブスクリプションを作成するには最初にbillableなモデルのインスタンスを取得しますが、通常はApp\Userのインスタンスでしょう。モデルインスタンスが獲得できたら、モデルのサブスクリプションを作成するために、newSubscriptionメソッドを使います。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 newSubscription method to create the model's subscription:

$user = User::find(1);

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

newSubscriptionメソッドの最初の引数は、サブスクリプションの名前です。アプリケーションでサブスクリプションを一つしか取り扱わない場合、mainprimaryと名づけましょう。2つ目の引数には、ユーザが購入したStripe/Braintreeのプランを指定します。この値はStripe/Braintreeのプランの識別子です。The first argument passed to the newSubscription method should be the name of the subscription. If your application only offers a single subscription, you might call this main or primary. The second argument is the specific Stripe / Braintree plan the user is subscribing to. This value should correspond to the plan's identifier in Stripe or Braintree.

createメソッドはサブスクリプションを開始すると同時に、カスタマーIDと関連する支払い情報をデータベースに保存します。The create method will begin the subscription as well as update your database with the customer ID and other relevant billing information.

ユーザ詳細情報の指定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->newSubscription('main', 'monthly')->create($creditCardToken, [
    'email' => $email,
]);

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

クーポンCoupons

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

$user->newSubscription('main', '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('main')) {
    //
}

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('main')) {
        // このユーザは支払っていない顧客
        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->subscription('main')->onTrial()) {
    //
}

subscribedToPlanメソッドは、そのユーザがStripe/BraintreeのプランIDで指定したプランを購入しているかを確認します。以下の例では、ユーザのmainサブスクリプションが、購入され有効なmonthlyプランであるかを確認しています。The subscribedToPlan method may be used to determine if the user is subscribed to a given plan based on a given Stripe / Braintree plan ID. In this example, we will determine if the user's main subscription is actively subscribed to the monthly plan:

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

キャンセルしたサブスクリプションの状態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->subscription('main')->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->subscription('main')->onGracePeriod()) {
    //
}

プラン変更Changing Plans

アプリケーションの購入済みユーザが新しいサブスクリプションプランへ変更したくなるのはよくあるでしょう。ユーザを新しいサブスクリプションに変更するには、swapメソッドへプランの識別子を渡します。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, pass the plan's identifier to the swap method:

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

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

ユーザが試用期間中の場合、試用期間は継続します。また、そのプランに「購入数」が存在している場合、購入個数も継続します。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.

プランを変更し、ユーザの現プランの試用期間をキャンセルする場合は、skipTrialメソッドを使用します。If you would like to swap plans and cancel any trial period the user is currently on, you may use the skipTrial method:

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

購入数Subscription Quantity

Note: note 購入数はStripe版のCashierでのみサポートしています。Braintreeには、Stripeの"quantity"(購入数)にあたる機能がありません。{note} Subscription quantities are only supported by the Stripe edition of Cashier. Braintree does not have a feature that corresponds to Stripe's "quantity".

購入数はサブスクリプションに影響をあたえることがあります。たとえば、あるアプリケーションで「ユーザごと」に毎月10ドル課金している場合です。購入数を簡単に上げ下げするには、incrementQuantitydecrementQuantityメソッドを使います。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 incrementQuantity and decrementQuantity methods:

$user = User::find(1);

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

// 現在の購入数を5個増やす
$user->subscription('main')->incrementQuantity(5);

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

// 現在の購入数を5個減らす
$user->subscription('main')->decrementQuantity(5);

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

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

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

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

ユーザが支払うサブスクリプションに対する税率を指定するには、BillableモデルへtaxPercentageメソッドを実装し、小数点以下が1桁以内で、0から100までの数値を返します。To specify the tax percentage a user pays on a subscription, implement the taxPercentage method on your billable model, and return a numeric value between 0 and 100, with no more than 2 decimal places.

public function taxPercentage() {
    return 20;
}

taxPercentageメソッドにより、モデルごとに税率を適用できるため、多くの州や国に渡るユーザベースで税率を決める場合に便利です。The taxPercentage method 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 and tax rates.

Note: note taxPercentageメソッドは、サブスクリプションの課金時のみに適用されます。Cashierで「一回のみ」の支払いを行う場合は、税率を自分で適用する必要があります。{note} The taxPercentage method only applies to subscription charges. If you use Cashier to make "one off" charges, you will need to manually specify the tax rate at that time.

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

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

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

サブスクリプションがキャンセルされるとCashierは自動的に、データベースのends_atカラムをセットします。このカラムはいつからsubscribedメソッドがfalseを返し始めればよいのか、判定するために使用されています。例えば、顧客が3月1日にキャンセルしたが、そのサブスクリプションが3月5日に終了するようにスケジュールされていれば、subscribedメソッドは3月5日になるまでtrueを返し続けます。When a subscription is cancelled, Cashier will automatically set the 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->subscription('main')->onGracePeriod()) {
    //
}

サブスクリプションを即時キャンセルしたい場合は、ユーザのサブスクリプションに対し、cancelNowメソッドを呼び出してください。If you wish to cancel a subscription immediately, call the cancelNow method on the user's subscription:

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

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

ユーザがキャンセルしたサブスクリプションを、再開したいときには、resumeメソッドを使用してください。サブスクリプションを再開するには、そのユーザに有効期間が残っている必要がありますIf a user has cancelled their subscription and you wish to resume it, use the resume method. The user must still be on their grace period in order to resume a subscription:

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

ユーザがサブスクリプションをキャンセルし、それからそのサブスクリプションを再開する場合、そのサブスクリプションの有効期日が完全に切れていなければすぐに課金されません。そのサブスクリプションはシンプルに再度有効になり、元々の支払いサイクルにより課金されます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.

クレジットカード変更Updating Credit Cards

顧客のクレジットカード情報を更新する場合は、updateCardメソッドを使います。このメソッドは、Stripeトークンを受け付け、新しいクレジットカードをデフォルトの支払先として登録します。The updateCard method may be used to update a customer's credit card information. This method accepts a Stripe token and will assign the new credit card as the default billing source:

$user->updateCard($creditCardToken);

サブスクリプションのトレイトSubscription Trials

カードの事前登録ありWith Credit Card Up Front

顧客へ試用期間を提供し、支払情報を事前に登録してもらう場合、サブスクリプションを作成するときにtrialDaysメソッドを使ってください。If you would like to offer trial periods to your customers while still collecting payment method information up front, You should use the trialDays method when creating your subscriptions:

$user = User::find(1);

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

このメソッドはデータベースのサブスクリプションレコードへ、試用期間の終了日を設定すると同時に、Stripe/Braintreeへこの期日が過ぎるまで、顧客へ課金を始めないように指示します。This method will set the trial period ending date on the subscription record within the database, as well as instruct Stripe / Braintree to not begin billing the customer until after this date.

Note: note 顧客のサブスクリプションが試用期間の最後の日までにキャンセルされないと、期限が切れると同時に課金されます。そのため、ユーザに試用期間の終了日を通知しておくべきでしょう。{note} If the customer's subscription is not cancelled before the trial ending date they will be charged as soon as the trial expires, so you should be sure to notify your users of their trial ending date.

ユーザが使用期間中であるかを判定するには、ユーザインスタンスに対しonTrialメソッドを使うか、サブスクリプションインスタンスに対してonTrialを使用してください。次の2つの例は、同じ目的を達します。You may determine if the user is within their trial period using either the onTrial method of the user instance, or the onTrial method of the subscription instance. The two examples below are identical:

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

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

カードの事前登録なしWithout Credit Card Up Front

事前にユーザの支払い方法の情報を登録してもらうことなく、試用期間を提供する場合は、そのユーザのレコードのtrial_ends_atに、試用の最終日を設定するだけです。典型的な使い方は、ユーザ登録時に設定する方法でしょう。If you would like to offer trial periods without collecting the user's payment method information up front, you may simply set the trial_ends_at column on the user record to your desired trial ending date. This is typically done during user registration:

$user = User::create([
    // 他のユーザプロパティの設定…
    'trial_ends_at' => Carbon::now()->addDays(10),
]);

Note: note モデル定義のtrial_ends_atに対する、日付ミューティタを付け加えるのを忘れないでください。{note} Be sure to add a date mutator[/docs/{{version}}/eloquent-mutators#date-mutators] for trial_ends_at to your model definition.

既存のサブスクリプションと関連付けが行われていないので、Cashierでは、このタイプの試用を「包括的な試用(generic trial)」と呼んでいます。Userインスタンスに対し、onTrialメソッドがtrueを返す場合、現在の日付はtrial_ends_atの値を過ぎていません。Cashier refers to this type of trial as a "generic trial", since it is not attached to any existing subscription. The onTrial method on the User instance will return true if the current date is not past the value of trial_ends_at:

if ($user->onTrial()) {
    // ユーザは試用期間中
}

特に、ユーザが「包括的な試用」期間中であり、まだサブスクリプションが作成されていないことを調べたい場合は、onGenericTrialメソッドが使用できます。You may also use the onGenericTrial method if you wish to know specifically that the user is within their "generic" trial period and has not created an actual subscription yet:

if ($user->onGenericTrial()) {
    // ユーザは「包括的」な試用期間中
}

ユーザに実際のサブスクリプションを作成する準備ができたら、通常はnewSubscriptionメソッドを使います。Once you are ready to create an actual subscription for the user, you may use the newSubscription method as usual:

$user = User::find(1);

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

StripeのWebフック処理Handling Stripe Webhooks

StripeとBraintree、両方共にWebフックによりアプリケーションへ様々なイベントを通知できます。StripeのWebフックを処理するには、CashierのWebフックコントローラへのルートを定義する必要があります。このコントローラは通知されるWebフックリクエストをすべて処理し、正しいコントローラメソッドをディスパッチします。Both Stripe and Braintree can notify your application of a variety of events via webhooks. To handle Stripe webhooks, define a route that points to Cashier's webhook controller. This controller will handle all incoming webhook requests and dispatch them to the proper controller method:

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

Note: note ルートを登録したら、Stripeコントロールパネル設定のWebフックURLも、合わせて設定してください。{note} Once you have registered your route, be sure to configure the webhook URL in your Stripe control panel settings.

このコントローラはデフォルトで、(Stripeの設定により決まる)課金の失敗が多すぎる場合、サブスクリプションを自動的にキャンセル処理します。しかしながら、処理したいWebフックイベントをどれでも処理できるようにするために、このコントローラを拡張する方法を以降で学びます。By default, this controller will automatically handle cancelling subscriptions that have too many failed charges (as defined by your Stripe settings); however, as we'll soon discover, you can extend this controller to handle any webhook event you like.

WebフックとCSRF保護Webhooks & CSRF Protection

StripeのWebフックでは、Laravelの CSRFバリデーションをバイパスする必要があるため、VerifyCsrfTokenミドルウェアのURIを例外としてリストしておくか、ルート定義をwebミドルウェアグループのリストから外しておきましょう。Since Stripe webhooks need to bypass Laravel's CSRF protection[/docs/{{version}}/routing#csrf-protection], be sure to list the URI as an exception in your VerifyCsrfToken middleware or list the route outside of the web middleware group:

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

Webフックハンドラの定義Defining Webhook Event Handlers

Cashierは課金の失敗時にサブスクリプションを自動的に処理しますが、他にもStripeのWebフックイベントを処理したい場合は、Webフックコントローラをシンプルに拡張します。メソッド名はCashierの命名規則に沿う必要があります。メソッドはhandleのプレフィックスで始まり、処理したいStripeのWebフックの名前を「キャメルケース」にします。たとえば、invoice.payment_succeeded Webフックを処理する場合は、handleInvoicePaymentSucceededメソッドをコントローラに追加します。Cashier automatically handles subscription cancellation on failed charges, but 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\Http\Controllers\WebhookController as CashierController;

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

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

顧客のクレジットカードが有効期限切れだったら? 心配いりません。CashierのWebフックコントローラで、顧客のサブスクリプションを簡単にキャンセルできます。前記と同じように、コントローラのルートを指定するだけです。What if a customer's credit card expires? No worries - the Cashier webhook controller that can easily cancel the customer's subscription for you. As noted above, all you need to do is point a route to the controller:

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

これだけです! 課金の失敗はコントローラにより捉えられ、処理されます。コントローラはStripeによりサブスクリプションが不能だと判断されると(通常は課金に3回失敗時)、その顧客のサブスクリプションをキャンセルします。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).

BraintreeのWebフック処理Handling Braintree Webhooks

StripeとBraintree、両方共にWebフックによりアプリケーションへ様々なイベントを通知できます。BraintreeのWebフックを処理するには、CashierのWebフックコントローラへのルートを定義する必要があります。このコントローラは通知されるWebフックリクエストをすべて処理し、正しいコントローラメソッドをディスパッチします。Both Stripe and Braintree can notify your application of a variety of events via webhooks. To handle Braintree webhooks, define a route that points to Cashier's webhook controller. This controller will handle all incoming webhook requests and dispatch them to the proper controller method:

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

Note: note ルートを登録したら、Braintreeコントロールパネル設定のWebフックURLも、合わせて設定してください。{note} Once you have registered your route, be sure to configure the webhook URL in your Braintree control panel settings.

このコントローラはデフォルトで、(Braintreeの設定により決まる)課金の失敗が多すぎる場合、サブスクリプションを自動的にキャンセル処理します。しかしながら、処理したいWebフックイベントをどれでも処理できるようにするために、このコントローラを拡張する方法を以降で学びます。By default, this controller will automatically handle cancelling subscriptions that have too many failed charges (as defined by your Braintree settings); however, as we'll soon discover, you can extend this controller to handle any webhook event you like.

WebフックとCSRF保護Webhooks & CSRF Protection

BraintreeのWebフックでは、Laravelの CSRFバリデーションをバイパスする必要があるため、VerifyCsrfTokenミドルウェアのURIを例外としてリストしておくか、ルート定義をwebミドルウェアグループのリストから外しておきましょう。Since Braintree webhooks need to bypass Laravel's CSRF protection[/docs/{{version}}/routing#csrf-protection], be sure to list the URI as an exception in your VerifyCsrfToken middleware or list the route outside of the web middleware group:

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

Webフックハンドラの定義Defining Webhook Event Handlers

Braintreeは課金の失敗時にサブスクリプションを自動的に処理しますが、他にもStripeのWebフックイベントを処理したい場合は、Webフックコントローラをシンプルに拡張します。メソッド名はCashierの命名規則に沿う必要があります。メソッドはhandleのプレフィックスで始まり、処理したいStripeのWebフックの名前を「キャメルケース」にします。たとえば、dispute_opened Webフックを処理する場合は、handleDisputeOpenedメソッドをコントローラに追加します。Cashier automatically handles subscription cancellation on failed charges, but if you have additional Braintree 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 Braintree webhook you wish to handle. For example, if you wish to handle the dispute_opened webhook, you should add a handleDisputeOpened method to the controller:

<?php

namespace App\Http\Controllers;

use Braintree\WebhookNotification;
use Laravel\Cashier\Http\Controllers\WebhookController as CashierController;

class WebhookController extends CashierController
{
    /**
     * Braintree Webフックの処理
     *
     * @param  WebhookNotification  $webhook
     * @return Response
     */
    public function handleDisputeOpened(WebhookNotification $notification)
    {
        // イベントの処理
    }
}

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

顧客のクレジットカードが有効期限切れだったら? 心配いりません。Cashierは顧客のサブスクリプションを簡単にキャンセルできる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(
    'braintree/webhook',
    '\Laravel\Cashier\Http\Controllers\WebhookController@handleWebhook'
);

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

一回だけの課金Single Charges

課金のみSimple Charge

Note: note Stripeを使用している場合、chargeメソッドにはアプリケーションで使用している通貨の最低単位で金額を指定しますが、Braintreeのchargeメソッドには、ドル単位の金額を指定します。{note} When using Stripe, the charge method accepts the amount you would like to charge in the lowest denominator of the currency used by your application. However, when using Braintree, you should pass the full dollar amount to the charge method:

すでに何かを購入している顧客のクレジットカードに、「一回だけ」の課金をしたい場合は、billableモデルのインスタンスに対し、chargeメソッドを使います。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.

// Stripeはセント単位で課金する
$user->charge(100);

// Braintreeはドル単位で課金する
$user->charge(1);

chargeメソッドは第2引数に配列を受け付け、裏で作成されるStripe/Braintreeの課金作成に対するオプションを指定できます。StripeとBraintreeの課金作成時に使用できるオプションについては、ドキュメントを参照してください。The charge method accepts an array as its second argument, allowing you to pass any options you wish to the underlying Stripe / Braintree charge creation. Consult the Stripe or Braintree documentation regarding the options available to you when creating charges:

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

chargeメソッドは、課金に失敗した場合に例外を投げます。課金に成功すると、メソッドはtripe/Braintreeレスポンスをそのまま返します。The charge method will throw an exception if the charge fails. If the charge is successful, the full Stripe / Braintree response will be returned from the method:

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

インボイス付き課金Charge With Invoice

一回だけ課金をしつつ、顧客へ発行するPDFのレシートとしてインボイスも生成したいことがあります。invoiceForメソッドは、まさにそのために存在しています。例として、「一回だけ」の料金を5ドル課金してみましょう。Sometimes you may need to make a one-time charge but also generate an invoice for the charge so that you may offer a PDF receipt to your customer. The invoiceFor method lets you do just that. For example, let's invoice the customer $5.00 for a "One Time Fee":

// Stripeはセント単位で課金する
$user->invoiceFor('One Time Fee', 500);

// Braintreeはドル単位で課金する
$user->invoiceFor('One Time Fee', 5);

金額は即時にユーザのクレジットカードへ課金されます。invoiceForメソッドは第3引数として配列を受け付け、裏で作成されるStripe/Braintreeの課金オプションを指定できます。The invoice will be charged immediately against the user's credit card. The invoiceFor method also accepts an array as its third argument, allowing you to pass any options you wish to the underlying Stripe / Braintree charge creation:

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

Note: note invoiceForメソッドは、課金失敗時にリトライするStripeインボイスを生成します。リトライをしてほしくない場合は、最初に課金に失敗した時点で、Stripe APIを使用し、生成したインボイスを閉じる必要があります。{note} The invoiceFor method will create a Stripe invoice which will retry failed billing attempts. If you do not want invoices to retry failed charges, you will need to close them using the Stripe API after the first failed charge.

インボイスInvoices

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

$invoices = $user->invoices();

// 結果にペンディング中のインボイスも含める
$invoices = $user->invoicesIncludingPending();

顧客へインボイスを一覧表示するとき、そのインボイスに関連する情報を表示するために、インボイスのヘルパメソッドを表示に利用できます。ユーザが簡単にダウンロードできるように、テーブルで全インボイスを一覧表示する例を見てください。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->date()->toFormattedDateString() }}</td>
            <td>{{ $invoice->total() }}</td>
            <td><a href="/user/invoice/{{ $invoice->id }}">Download</a></td>
        </tr>
    @endforeach
</table>

インボイスPDF生成Generating Invoice PDFs

インボイスPDFを生成する前に、dompdf PHPライブラリーをインストールしておく必要があります。Before generating invoice PDFs, you need to install the dompdf PHP library:

composer require dompdf/dompdf

ルートやコントローラの中でdownloadInvoiceメソッドを使うと、そのインボイスのPDFダウンロードを生成できます。このメソッドはブラウザへダウンロードのHTTPレスポンスを正しく行うHTTPレスポンスを生成します。Then, 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:

use Illuminate\Http\Request;

Route::get('user/invoice/{invoice}', function (Request $request, $invoiceId) {
    return $request->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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作