イントロダクションIntroduction
Laravel Cashier BraintreeはBraintree'sによるサブスクリプション(定期課金)サービスの読みやすく、スラスラと記述できるインターフェイスを提供します。これにより書くのが恐ろしくなるような、サブスクリプション支払いのための決まりきったコードのほとんどが処理できます。基本的なサブスクリプション管理に加え、Cashierはクーポン、サブスクリプションの変更、サブスクリプション数、キャンセル猶予期間、さらにインボイスのPDF発行まで行います。Laravel Cashier Braintree provides an expressive, fluent interface to Braintree's[https://www.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} These are the docs for the Cashier integration with Braintree. You may find the Stripe integration docs here[/docs/{{version}}/billing].
このドキュメントはCashierのBraintree統合について説明しています。Stripeを使用する場合は、
Note: {note} If you're only performing "one-off" charges and do not offer subscriptions, you should not use Cashier. Instead, use the Braintree SDK directly.
サブスクリプションを提供せず、「一回だけ」の支払いを取り扱う場合は、Cashierを使用してはいけません。BraintreeのSDKを直接使用してください。
注意事項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:
インストールInstallation
First, require the Cashier package for Braintree with Composer:First, require the Cashier package for Braintree with Composer:
composer require laravel/cashier-braintree
設定Configuration
クレジットクーポンのプラン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 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 (Blueprint $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 (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('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, 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
最後に、Stripeキーを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'),
],
それから、AppServiceProvider
サービスプロバイダのboot
メソッドへ、以下のBraintree SDKの呼び出しを追加します。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', 'premium')->create($token);
newSubscription
メソッドの最初の引数は、サブスクリプションの名前です。アプリケーションでサブスクリプションを一つしか取り扱わない場合、main
かprimary
と名づけましょう。2つ目の引数はユーザーが購入しようとしているサブスクリプションのプランを指定します。この値は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 plan the user is subscribing to. This value should correspond to the plan's identifier in Braintree.
create
メソッドはクレジットカード/ソーストークンを引数にとり、サブスクリプションを開始すると同時に、カスタマーIDと関連する支払い情報をデータベースに保存します。The create
method, which accepts a credit card / source token, 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($token, [
'email' => $email,
]);
Braintreeがサポートする追加のフィールドについてのさらなる情報は、Braintreeドキュメントを確認してください。To learn more about the additional fields supported by Braintree, check out 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($token);
サブスクリプション状態の確認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
メソッドは、そのユーザーがプランIDで指定したプランを購入しているかを確認します。以下の例では、ユーザーのmain
サブスクリプションが、購入され有効なmonthly
プランであるかを確認しています。The subscribedToPlan
method may be used to determine if the user is subscribed to a given plan based on a given 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')) {
//
}
recurring
メソッドはユーザーが現在サブスクリプションを購入中で、試用期間を過ぎていることを判断するために使用します。The recurring
method may be used to determine if the user is currently subscribed and is no longer within their trail period:
if ($user->subscription('main')->recurring()) {
//
}
キャンセルしたサブスクリプションの状態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
メソッドは、この期間中、まだtrue
を返すことに注目して下さい。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()) {
//
}
ユーザーがサブスクリプションをキャンセルし、「猶予期間」を過ぎていることを調べるには、ended
メソッドを使ってください。To determine if the user has cancelled their subscription is no longer within their "grace period", you may use the ended
method:
if ($user->subscription('main')->ended()) {
//
}
プラン変更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 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:
taxPercentage
メソッドは、サブスクリプションの課金時のみに適用されます。Cashierで「一回のみ」の支払いを行う場合は、税率を自分で適用する必要があります。{note} ThetaxPercentage
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, 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 be re-activated, and they will be billed on the original billing cycle.
サブスクリプションのトレイト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($token);
このメソッドはデータベースのサブスクリプションレコードへ、試用期間の終了日を設定すると同時に、Braintreeへこの期日が過ぎるまで、顧客へ課金を始めないように指示します。This method will set the trial period ending date on the subscription record within the database, as well as instruct Braintree to not begin billing the customer until after this date.
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 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' => now()->addDays(10),
]);
Note:
モデル定義のtrial_ends_at
に対する、日付ミューテタを付け加えるのを忘れないでください。{note} Be sure to add a date mutator[/docs/{{version}}/eloquent-mutators#date-mutators] fortrial_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($token);
顧客Customers
顧客の生成Creating Customers
時にサブスクリプションの定期購入を始めなくても、Braintree顧客を生成したい場合があります。それには、createAsBraintreeCustomer
メソッドを使用します。Occasionally, you may wish to create a Braintree customer without beginning a subscription. You may accomplish this using the createAsBraintreeCustomer
method:
$user->createAsBraintreeCustomer();
Braintreeで作った顧客に対し、後からサブスクリプションの定期購入を開始可能です。Once the customer has been created in Braintree, you may begin a subscription at a later date.
カードCards
クレジットカードの更新Updating Credit Cards
顧客のクレジットカード情報を更新するには、updateCard
メソッドを使用します。このメソッドはBraintreeトークンを引数に取り、新しいクレジットカードをデフォルトの支払先に設定します。The updateCard
method may be used to update a customer's credit card information. This method accepts a Braintree token and will assign the new credit card as the default billing source:
$user->updateCard($token);
Webフックの処理Handling Webhooks
BraintreeはWebフックにより、アプリケーションへ様々なイベントを通知できます。Webフックを処理するには、CashierのWebフックコントローラへのルートを定義する必要があります。このコントローラは受信したWebフックリクエストをすべて処理し、正しいコントローラメソッドをディスパッチします。Braintree can notify your application of a variety of events via webhooks. To handle 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} Once you have registered your route, be sure to configure the webhook URL in your Braintree control panel settings.
ルートを登録したら、Braintreeコントロールパネル設定のWebフックURLも、合わせて設定してください。
このコントローラはデフォルトで、(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
Webフックでは、Laravelの CSRFバリデーションをバイパスする必要があるため、VerifyCsrfToken
ミドルウェアのURIを例外としてリストしておくか、ルート定義をweb
ミドルウェアグループのリストから外しておきましょう。Since webhooks need to bypass Laravel's CSRF protection[/docs/{{version}}/csrf], 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
Cashierは課金の失敗時に、サブスクリプションを自動的にキャンセル処理しますが、他のWebフックイベントを処理したい場合は、Webフックコントローラを拡張します。メソッド名はCashierが期待する命名規則に沿う必要があります。特にメソッドはhandle
のプレフィックスで始まり、処理したいWebフックの名前を「キャメルケース」にします。たとえば、dispute_opened
Webフックを処理する場合は、handleDisputeOpened
メソッドをコントローラに追加します。Cashier automatically handles subscription cancellation on failed charges, but if you have additional webhook events you would like to handle, 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 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
{
/**
* 新しいクレーム処理
*
* @param \Braintree\WebhookNotification $webhook
* @return \Symfony\Component\HttpFoundation\Responses
*/
public function handleDisputeOpened(WebhookNotification $webhook)
{
// Webフックの処理…
}
}
サブスクリプション不可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:
charge
メソッドには、金額をそのまま渡します。{note} You should pass the full dollar amount to thecharge
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.
$user->charge(1);
charge
メソッドは第2引数に配列を受け付け、裏で動いている課金作成に対するオプションを指定できます。課金作成時に使用できるオプションについては、Stripeのドキュメントを参照してください。The charge
method accepts an array as its second argument, allowing you to pass any options you wish to the underlying charge creation. Consult the Braintree documentation regarding the options available to you when creating charges:
$user->charge(1, [
'custom_option' => $value,
]);
charge
メソッドは、課金に失敗した場合に例外を投げます。課金に成功すると、メソッドはBraintreeレスポンスをそのまま返します。The charge
method will throw an exception if the charge fails. If the charge is successful, the full Braintree response will be returned from the method:
try {
$response = $user->charge(1);
} 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":
$user->invoiceFor('One Time Fee', 5);
金額は即時にユーザーのクレジットカードへ課金されます。invoiceFor
メソッドは第3引数に配列を受け付けます。この配列はインボイスアイテムへの支払いオプションを含みます。第4引数も配列で、インボイス自身に対する支払いオプションを指定します。invoiceFor
メソッドを呼び出すときには、description
オプションを含めるべきでしょう。The invoice will be charged immediately against the user's credit card. The invoiceFor
method also accepts an array as its third argument. This array contains the billing options for the invoice item. You must include a description
option when calling the invoiceFor
method:
$user->invoiceFor('One Time Fee', 5, [
'description' => 'your invoice description here',
]);
インボイス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
ルートやコントローラの中で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:
use Illuminate\Http\Request;
Route::get('user/invoice/{invoice}', function (Request $request, $invoiceId) {
return $request->user()->downloadInvoice($invoiceId, [
'vendor' => 'Your Company',
'product' => 'Your Product',
]);
});