イントロダクション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パッケージを追加します。First, add the Cashier package to
your composer.json
file:
"laravel/cashier": "~5.0"(2015年2月18日以降のStripe API、およびStripe SDK 2.0まで)
"laravel/cashier": "~4.0"(2015年2月18日以降のStripe API)
"laravel/cashier": "~3.0"(2015年2月16日までのStripe API)
サービスプロバイダーService Provider
次に、app
設定ファイルへ、Laravel\Cashier\CashierServiceProvider
を登録します。Next, register the
Laravel\Cashier\CashierServiceProvider
in your app
configuration
file.
マイグレーションMigration
キャッシャーを使用する前に、データベースにいくつかカラムを追加する必要があります。心配ありません。cashier:table
Artisanコマンドで、必要なカラムを追加するマイグレーションが生成されます。例えば、usersテーブルにカラムを追加するには、php
artisan cashier:table
users
を実行します。マイグレーションを生成したら、後はmigrate
コマンドを実行するだけです。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 use php artisan cashier:table
users
. 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'];
}
StripeキーStripe Key
最後に、services.php
設定ファイルへStripeキーを設置します。Finally, set your Stripe key in
your services.php
config
file:
'stripe' => [
'model' => 'User',
'secret' => env('STRIPE_API_SECRET'),
],
初期設定(bootstrap)ファイルや、AppServiceProvider
のようなサービスプロバイダーで指定する方法もあります。Alternatively you can store it in
one of your bootstrap files or service providers,
such as the
AppServiceProvider
:
User::setStripeKey('stripe-key');
プランの購読Subscribing To A Plan
モデルインスタンスを取得したら、そのユーザーに指定したStripeプランを簡単に購読してもらえます。Once you have a model instance, you can easily subscribe that user to a given Stripe plan:
$user = User::find(1);
$user->subscription('monthly')->create($creditCardToken);
購読の作成時に、クーポンを適用したい場合は、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);
subscription
メソッドは、自動的にStripeの購読を作成すると同時に、StripeのカスタマーIDと関連する支払い情報をデータベースに保存します。Stripeでプランの試用期間を設定している場合、試用終了日も自動的に、ユーザーのレコードに設定されます。The subscription
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 your plan has a trial period that is not configured in Stripe, you must set the trial end date manually after subscribing:
$user->trial_ends_at = Carbon::now()->addDays(14);
$user->save();
ユーザーの詳細情報を指定するSpecifying Additional User Details
ユーザーに関する詳細情報を追加したい場合は、create
メソッドの第2引数に渡すことができます。If you would like to specify
additional customer details, you may do so by
passing them as 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].
一回だけの課金Single Charges
定期購読している顧客のクレジットカードに対し、「一回限り」の課金を行いたい場合は、charge
メソッドを使用してください。If you would like to make a
"one off" charge against a subscribed
customer's credit card, you may use the
charge
method:
$user->charge(100);
charge
メソッドは通過の最低単位の課金を引数に取ります。ですから、上記の例は100セント(1ドル)をクレジットカードへ課金します。The charge
method
accepts the amount you would like to charge in the
lowest denominator of the currency.
So, for example, the example above will charge 100
cents, or $1.00, against the user's credit
card.
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.
カードの前払いなしNo Card Up Front
アプリケーションで、カードによる前払いなしの試用期間を提供する場合、モデルのcardUpFront
プロパティーをfalse
に設定してください。If your application offers a
free-trial with no credit-card up front, set the
cardUpFront
property on your model to
false
:
protected $cardUpFront = false;
アカウント作成時に、試用期間の最終日をモデルへセットするのをお忘れなく。On account creation, be sure to set the trial end date on the model:
$user->trial_ends_at = Carbon::now()->addDays(14);
$user->save();
購読の変更Swapping Subscriptions
ユーザーの購読を新しいものへ変更する場合、swap
メソッドを使用してください。To swap a user to a new
subscription, use the swap
method:
$user->subscription('premium')->swap();
ユーザーが試用期間中の場合、試用期間は通常通りに続きます。また、その購読に"quantity"(購読数)が存在する場合、その個数も維持されます。If the user is on trial, the trial will be maintained as normal. Also, if a "quantity" exists for the subscription, that quantity will also be maintained.
購読数Subscription Quantity
購読数により、購読が影響を受けることがあります。例えば、あなたのアプリケーションで、一つのアカウントごとに一月10ドル課金しているとしましょう。increment
とdecrement
メソッドで、簡単に購読数を増減できます。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);
購読の税金Subscription Tax
キャッシャーでは、Stripeに送る「税率(tax_percent
)」を上書きするのも簡単です。購読に対する顧客の支払いの税率を指定するには、モデルにgetTaxPercent
メソッドを実装し、小数点以下の桁数が2桁以内で0から100までの数値を返します。With Cashier, it's easy to
override the tax_percent
value sent to
Stripe. To specify the tax percentage a user pays on
a subscription, implement the
getTaxPercent
method on your 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 A Subscription
購読のキャンセルも、お茶の子さいさいです。Cancelling a subscription is a walk in the park:
$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 on 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.
購読の再開Resuming A Subscription
ユーザーがキャンセルした購読を、再開したいときには、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. Their subscription will simply be re-activated, and they will be billed on the original billing cycle.
購読状況のチェックChecking Subscription Status
ユーザーがアプリケーションで購入しているかを調べるには、subscribed
メソッドを使います。To verify that a user is
subscribed to your application, use the
subscribed
method:
if ($user->subscribed())
{
//
}
subscribed
メソッドは、ルートミドルウェアにとても便利でしょう。The subscribed
method makes a great candidate for a route
middleware[/docs/{{version}}/middleware]:
public function handle($request, Closure $next)
{
if ($request->user() && ! $request->user()->subscribed())
{
return redirect('billing');
}
return $next($request);
}
また試用期間を採用している場合、そのユーザーが試用期間中であるかを判定するために、onTrial
メソッドが使用できます。You may also determine if the
user is still within their trial period (if
applicable) using the onTrial
method:
if ($user->onTrial())
{
//
}
そのユーザーが一度購読し、その後キャンセルしたかを判定するためには、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
scheduled to end 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())
{
//
}
onPlan
メソッドにより、そのユーザーが指定されたIDのプランを購入しているかを判定できます。The onPlan
method
may be used to determine if the user is subscribed
to a given plan based on its ID:
if ($user->onPlan('monthly'))
{
//
}
購読不能時の処理Handling 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回失敗時)、その顧客の購読をキャンセルします。この場合のURI、stripe/webhook
はただの例にすぎません。Stripe設定で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). The
stripe/webhook
URI in this example is
just for example. You will need to configure the URI
in your Stripe settings.
他のStripe Webフックの処理Handling Other Stripe 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 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.
class WebhookController extends Laravel\Cashier\WebhookController {
public function handleInvoicePaymentSucceeded($payload)
{
// Handle The Event
}
}
**注意:**データベースの中の購読情報を追加で更新すると、WebフックコントローラーはStripe APIを使用し、その購読をキャンセルしようとします。Note: In addition to updating the subscription information in your database, the Webhook controller will also cancel the subscription via the Stripe API.
インボイスInvoices
invoices
メソッドにより、ユーザーのインボイスの配列を簡単に取得できます。You can easily retrieve an array
of a user's invoices using the invoices
method:
$invoices = $user->invoices();
顧客に対し、インボイスを一覧表示する場合、そのインボイスに関連する情報を表示するために、以下のヘルパメソッドが使用できます。When listing the invoices for the customer, you may use these helper methods to display the relevant invoice information:
{{ $invoice->id }}
{{ $invoice->dateString() }}
{{ $invoice->dollars() }}
downloadInvoice
メソッドで、そのインボイスのPDFダウンロードを生成できます。そうです、これも本当に簡単です。Use the
downloadInvoice
method to generate a
PDF download of the invoice. Yes, it's really this
easy:
return $user->downloadInvoice($invoice->id, [
'vendor' => 'Your Company',
'product' => 'Your Product',
]);