イントロダクションIntroduction
Laravel Cashier Stripeは、Stripeのサブスクリプション課金サービスに対する表現力豊かで流暢なインターフェイスを提供します。それはあなたが書くことを恐れている定型的なサブスクリプション請求コードのほとんどすべてを処理します。キャッシャーは、基本的なサブスクリプション管理に加えて、クーポン、サブスクリプションの交換、サブスクリプションの「数量」、キャンセルの猶予期間を処理し、請求書のPDFを生成することもできます。Laravel Cashier Stripe[https://github.com/laravel/cashier-stripe] 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.
CashierのアップデートUpgrading Cashier
キャッシャーの新しいバージョンにアップグレードするときは、アップグレードガイドを注意深く確認することが重要です。When upgrading to a new version of Cashier, it's important that you carefully review the upgrade guide[https://github.com/laravel/cashier-stripe/blob/master/UPGRADE.md].
Warning! 重大な変更を防ぐために、Cashierは固定のStripe APIバージョンを使用します。Cashier15はStripe APIバージョン
2023-10-16
を利用しています。Stripe APIバージョンは、新しいStripe機能と改善点を利用するために、マイナーリリースで更新されます。[!WARNING]
To prevent breaking changes, Cashier uses a fixed Stripe API version. Cashier 15 utilizes Stripe API version2023-10-16
. The Stripe API version will be updated on minor releases in order to make use of new Stripe features and improvements.
インストールInstallation
まず、Composerパッケージマネージャを使用して、StripeのCashierパッケージをインストールします。First, install the Cashier package for Stripe using the Composer package manager:
composer require laravel/cashier
パッケージをインストールしたら、vendor:publish
Artisanコマンドを使用してCashierのマイグレーションをリソース公開します。After installing the package,
publish Cashier's migrations using the
vendor:publish
Artisan
command:
php artisan vendor:publish --tag="cashier-migrations"
Then, migrate your database:Then, migrate your database:
php artisan migrate
Cashierのマイグレーションは、users
テーブルにいくつかのカラムを追加します。また、新たにsubscriptions
テーブルも作成し、顧客のすべてのサブスクリプションを保持し、複数の価格を持つサブスクリプションのためにsubscription_items
テーブルを作成します。Cashier's migrations will add
several columns to your users
table.
They will also create a new
subscriptions
table to hold all of your
customer's subscriptions and a
subscription_items
table for
subscriptions with multiple prices.
お望みであれば、vendor:publish
Artisanコマンドを使って、Cashierの設定ファイルをリソース公開することもできます。If you wish, you can also publish
Cashier's configuration file using the
vendor:publish
Artisan
command:
php artisan vendor:publish --tag="cashier-config"
最後に、CashierがすべてのStripeイベントを適切に処理できるように、Cashierのウェブフック処理を設定するのを忘れないでください。Lastly, to ensure Cashier properly handles all Stripe events, remember to configure Cashier's webhook handling[#handling-stripe-webhooks].
Warning! Stripeは、Stripe識別子の格納に使用するカラムでは、大文字と小文字を区別することを推奨しています。したがって、MySQLを使用する場合は、
stripe_id
列の列照合順序を確実にutf8_bin
へ設定する必要があります。これに関する詳細は、Stripeドキュメントにあります。[!WARNING]
Stripe recommends that any column used for storing Stripe identifiers should be case-sensitive. Therefore, you should ensure the column collation for thestripe_id
column is set toutf8_bin
when using MySQL. More information regarding this can be found in the Stripe documentation[https://stripe.com/docs/upgrades#what-changes-does-stripe-consider-to-be-backwards-compatible].
設定Configuration
BillableモデルBillable Model
Cashierを使用する前に、Billableなモデルの定義へBillable
トレイトを追加してください。通常、これはApp\Models\User
モデルになるでしょう。このトレイトはサブスクリプションの作成、クーポンの適用、支払い方法情報の更新など、一般的な請求タスクを実行できるようにするさまざまなメソッドを提供します。Before using Cashier, add the
Billable
trait to your billable model
definition. Typically, this will be the
App\Models\User
model. This trait
provides various methods to allow you to perform
common billing tasks, such as creating
subscriptions, applying coupons, and updating
payment method information:
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Billable;
}
CashierはLaravelに同梱されているApp\Models\User
クラスをBillableなモデルとして想定しています。これを変更したい場合は、useCustomerModel
メソッドで別のモデルを指定します。このメソッドは通常、AppServiceProvider
クラスのboot
メソッドで呼び出します。Cashier assumes your billable
model will be the App\Models\User
class
that ships with Laravel. If you wish to change this
you may specify a different model via the
useCustomerModel
method. This method
should typically be called in the boot
method of your AppServiceProvider
class:
use App\Models\Cashier\User;
use Laravel\Cashier\Cashier;
/**
* アプリケーション全サービスの初期起動処理
*/
public function boot(): void
{
Cashier::useCustomerModel(User::class);
}
Warning! Laravelが提供する
App\Models\User
モデル以外のモデルを使用する場合は、提供しているCashierマイグレーションをリソース公開し、代替モデルのテーブル名と一致するように変更する必要があります。[!WARNING]
If you're using a model other than Laravel's suppliedApp\Models\User
model, you'll need to publish and alter the Cashier migrations[#installation] provided to match your alternative model's table name.
APIキーAPI Keys
次に、アプリケーションの.env
ファイルでStripeAPIキーを設定する必要があります。StripeAPIキーはStripeコントロールパネルから取得できます。Next, you should configure your
Stripe API keys in your application's
.env
file. You can retrieve your Stripe
API keys from the Stripe control panel:
STRIPE_KEY=your-stripe-key
STRIPE_SECRET=your-stripe-secret
STRIPE_WEBHOOK_SECRET=your-stripe-webhook-secret
Warning! アプリケーションの
.env
ファイルで、STRIPE_WEBHOOK_SECRET
環境変数を確実に定義してください。この変数は、受け取ったWebhookが実際にStripeから送られたものであることを確認するために使用します。[!WARNING]
You should ensure that theSTRIPE_WEBHOOK_SECRET
environment variable is defined in your application's.env
file, as this variable is used to ensure that incoming webhooks are actually from Stripe.
通貨設定Currency Configuration
デフォルトのCashier通貨は米ドル(USD)です。アプリケーションの.env
ファイル内でCASHIER_CURRENCY
環境変数を設定することにより、デフォルトの通貨を変更できます。The default Cashier currency is
United States Dollars (USD). You can change the
default currency by setting the
CASHIER_CURRENCY
environment variable
within your application's .env
file:
CASHIER_CURRENCY=eur
Cashierの通貨の設定に加え、請求書に表示するの金額の値をフォーマットするときに使用するロケールを指定することもできます。内部的には、CashierはPHPのNumberFormatter
クラスを利用して通貨ロケールを設定します。In addition to configuring
Cashier's currency, you may also specify a locale to
be used when formatting money values for display on
invoices. Internally, Cashier utilizes PHP's
NumberFormatter
class[https://www.php.net/manual/en/class.numberformatter.php]
to set the currency locale:
CASHIER_CURRENCY_LOCALE=nl_BE
Warning!
en
以外のロケールを使用するは、ext-intl
PHP拡張機能をサーバへ確実にインストール・設定してください。[!WARNING]
In order to use locales other thanen
, ensure theext-intl
PHP extension is installed and configured on your server.
税設定Tax Configuration
Stripe
Taxのおかげで、Stripeが生成するすべての請求書の税金を自動的に計算可能になりました。税金の自動計算を有効にするには、アプリケーションのApp\Providers\AppServiceProvider
クラスのboot
メソッドでcalculateTaxes
メソッドを実行します。Thanks to Stripe
Tax[https://stripe.com/tax], it's possible
to automatically calculate taxes for all invoices
generated by Stripe. You can enable automatic tax
calculation by invoking the
calculateTaxes
method in the
boot
method of your application's
App\Providers\AppServiceProvider
class:
use Laravel\Cashier\Cashier;
/**
* アプリケーション全サービスの初期起動処理
*/
public function boot(): void
{
Cashier::calculateTaxes();
}
税計算を有効にすると、新規サブスクリプションや単発の請求書が作成された場合、自動的に税計算が行われます。Once tax calculation has been enabled, any new subscriptions and any one-off invoices that are generated will receive automatic tax calculation.
この機能を正常に動作させるためには、顧客の氏名、住所、課税IDなどの請求情報がStripeに同期されている必要があります。そのために、Cashierが提供する顧客データの同期や課税IDのメソッドを使用できます。For this feature to work properly, your customer's billing details, such as the customer's name, address, and tax ID, need to be synced to Stripe. You may use the customer data synchronization[#syncing-customer-data-with-stripe] and Tax ID[#tax-ids] methods offered by Cashier to accomplish this.
一回限りの課金や一回限りの支払いでは税金が計算されません。[!WARNING]
Warning!
No tax is calculated for single charges[#single-charges] or single charge checkouts[#single-charge-checkouts].
ログLogging
Cashierを使用すると、StripeのFatalエラーをログに記録するときに使用するログチャネルを指定できます。アプリケーションの.env
ファイル内でCASHIER_LOGGER
環境変数を定義することにより、ログチャネルを指定できます。Cashier allows you to specify the
log channel to be used when logging fatal Stripe
errors. You may specify the log channel by defining
the CASHIER_LOGGER
environment variable
within your application's .env
file:
CASHIER_LOGGER=stack
StripeへのAPI呼び出しで発生した例外は、アプリケーションのデフォルトログチャンネルにより記録されます。Exceptions that are generated by API calls to Stripe will be logged through your application's default log channel.
カスタムモデルの使用Using Custom Models
独自のモデルを定義し対応するCashierモデルを拡張することにより、Cashierが内部で使用するモデルを自由に拡張できます。You are free to extend the models used internally by Cashier by defining your own model and extending the corresponding Cashier model:
use Laravel\Cashier\Subscription as CashierSubscription;
class Subscription extends CashierSubscription
{
// ...
}
モデルを定義した後、Laravel\Cashier\Cashier
クラスを介してカスタムモデルを使用するようにCashierへ指示します。通常、アプリケーションのApp\Providers\AppServiceProvider
クラスのboot
メソッドで、カスタムモデルをCashierへ通知する必要があります。After defining your model, you
may instruct Cashier to use your custom model via
the Laravel\Cashier\Cashier
class.
Typically, you should inform Cashier about your
custom models in the boot
method of
your application's
App\Providers\AppServiceProvider
class:
use App\Models\Cashier\Subscription;
use App\Models\Cashier\SubscriptionItem;
/**
* アプリケーション全サービスの初期起動処理
*/
public function boot(): void
{
Cashier::useSubscriptionModel(Subscription::class);
Cashier::useSubscriptionItemModel(SubscriptionItem::class);
}
クイックスタートQuickstart
プロダクトの販売Selling Products
CashierのWebフック処理を設定する必要もあります。[!NOTE]
Note: Stripeチェックアウトを利用する前に、Stripeダッシュボードにより、固定価格で商品を定義してください。さらに、
Before utilizing Stripe Checkout, you should define Products with fixed prices in your Stripe dashboard. In addition, you should configure Cashier's webhook handling[#handling-stripe-webhooks].
アプリケーションで商品や定期購入の課金を提供するのは、敷居が高いかもしれません。しかし、CashierとStripe Checkoutのおかげで、モダンで堅牢な決済統合を簡単に構築できます。Offering product and subscription billing via your application can be intimidating. However, thanks to Cashier and Stripe Checkout[https://stripe.com/payments/checkout], you can easily build modern, robust payment integrations.
定期的でない、1回限りの課金を行う商品を顧客に提供するには、Cashierを利用して顧客をStripe Checkoutへ誘導します。そこで顧客は、支払いの詳細を入力し、購入を確認します。Checkoutで支払いが完了すると、顧客をアプリケーション内の選択した成功URLへリダイレクトします。To charge customers for non-recurring, single-charge products, we'll utilize Cashier to direct customers to Stripe Checkout, where they will provide their payment details and confirm their purchase. Once the payment has been made via Checkout, the customer will be redirected to a success URL of your choosing within your application:
use Illuminate\Http\Request;
Route::get('/checkout', function (Request $request) {
$stripePriceId = 'price_deluxe_album';
$quantity = 1;
return $request->user()->checkout([$stripePriceId => $quantity], [
'success_url' => route('checkout-success'),
'cancel_url' => route('checkout-cancel'),
]);
})->name('checkout');
Route::view('checkout.success')->name('checkout-success');
Route::view('checkout.cancel')->name('checkout-cancel');
上の例でわかるように、Cashierが提供するcheckout
メソッドを利用して、指定した「価格識別子」で顧客をStripe
Checkoutへリダイレクトします。Stripeを使用する場合、「価格」は特定の商品に対して定義した価格を意味します。As you can see in the example
above, we will utilize Cashier's provided
checkout
method to redirect the
customer to Stripe Checkout for a given "price
identifier". When using Stripe,
"prices" refer to defined prices for
specific
products[https://stripe.com/docs/products-prices/how-products-and-prices-work].
必要に応じて、checkout
メソッドは自動的にStripeに顧客を作成し、Stripeの顧客レコードをアプリケーションのデータベースの対応するユーザーと接続します。チェックアウトセッションの完了後、顧客を成功またはキャンセル専用のページへリダイレクトし、そこで顧客に情報メッセージを表示できます。If necessary, the
checkout
method will automatically
create a customer in Stripe and connect that Stripe
customer record to the corresponding user in your
application's database. After completing the
checkout session, the customer will be redirected to
a dedicated success or cancellation page where you
can display an informational message to the
customer.
Stripe Checkoutへのメタデータ提供Providing Meta Data to Stripe Checkout
商品を販売する場合、自分のアプリケーションで定義したCart
とOrder
モデルを使用して、完了した注文と購入した商品を追跡するのが一般的です。顧客が購入を完了するためStripe
Checkoutへリダイレクトする場合、顧客がアプリケーションへリダイレクトされ戻ったときに、完了した購入と対応する注文を関連付けできるように、既存の注文識別子を提供する必要が起きるでしょう。When selling products, it's
common to keep track of completed orders and
purchased products via Cart
and
Order
models defined by your own
application. When redirecting customers to Stripe
Checkout to complete a purchase, you may need to
provide an existing order identifier so that you can
associate the completed purchase with the
corresponding order when the customer is redirected
back to your application.
これを行うには、metadata
の配列をcheckout
メソッドへ渡してください。ユーザーがチェックアウト処理を開始したときに、保留中のOrder
をアプリケーション内に作成するとしましょう。この例のCart
とOrder
モデルは一例であり、Cashierが提供するものではないことを忘れないでください。こうしたコンセプトはあなたのアプリケーションのニーズに基づいて自由に実装してもらえます。To accomplish this, you may
provide an array of metadata
to the
checkout
method. Let's imagine that a
pending Order
is created within our
application when a user begins the checkout process.
Remember, the Cart
and
Order
models in this example are
illustrative and not provided by Cashier. You are
free to implement these concepts based on the needs
of your own application:
use App\Models\Cart;
use App\Models\Order;
use Illuminate\Http\Request;
Route::get('/cart/{cart}/checkout', function (Request $request, Cart $cart) {
$order = Order::create([
'cart_id' => $cart->id,
'price_ids' => $cart->price_ids,
'status' => 'incomplete',
]);
return $request->user()->checkout($order->price_ids, [
'success_url' => route('checkout-success').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('checkout-cancel'),
'metadata' => ['order_id' => $order->id],
]);
})->name('checkout');
上例でわかるように、ユーザーがチェックアウト処理を開始するときに、カート/注文に関連するStripeの価格識別子をすべてcheckout
メソッドへ提供しています。もちろん、顧客がアイテムを追加した際にこうしたアイテムを「ショッピングカート」や注文と関連付けるのはアプリケーションの役割です。さらに、注文のIDをmetadata
配列経由で、Stripe
Checkoutセッションへ提供しています。最後に、チェックアウト成功ルートへ、CHECKOUT_SESSION_ID
テンプレート変数を追加しました。Stripeが顧客をアプリケーションにリダイレクトするとき、このテンプレート変数へcheckoutセッションIDが自動的に入力されます。As you can see in the example
above, when a user begins the checkout process, we
will provide all of the cart / order's associated
Stripe price identifiers to the
checkout
method. Of course, your
application is responsible for associating these
items with the "shopping cart" or order as
a customer adds them. We also provide the order's ID
to the Stripe Checkout session via the
metadata
array. Finally, we have added
the CHECKOUT_SESSION_ID
template
variable to the Checkout success route. When Stripe
redirects customers back to your application, this
template variable will automatically be populated
with the Checkout session ID.
次に、チェックアウト成功ルートを作成しましょう。これは、Stripe Checkout経由で購入が完了した後に、ユーザーをリダイレクトするルートです。このルート内で、Stripe CheckoutのセッションIDと関連するStripe Checkoutインスタンスを取得し、提供しておいたメタデータへアクセスし、それに応じた顧客の注文を更新します:Next, let's build the Checkout success route. This is the route that users will be redirected to after their purchase has been completed via Stripe Checkout. Within this route, we can retrieve the Stripe Checkout session ID and the associated Stripe Checkout instance in order to access our provided meta data and update our customer's order accordingly:
use App\Models\Order;
use Illuminate\Http\Request;
use Laravel\Cashier\Cashier;
Route::get('/checkout/success', function (Request $request) {
$sessionId = $request->get('session_id');
if ($sessionId === null) {
return;
}
$session = Cashier::stripe()->checkout->sessions->retrieve($sessionId);
if ($session->payment_status !== 'paid') {
return;
}
$orderId = $session['metadata']['order_id'] ?? null;
$order = Order::findOrFail($orderId);
$order->update(['status' => 'completed']);
return view('checkout-success', ['order' => $order]);
})->name('checkout-success');
Checkoutオブジェクトに含まれるデータの詳細については、Stripeのドキュメントを参照してください。Please refer to Stripe's documentation for more information on the data contained by the Checkout session object[https://stripe.com/docs/api/checkout/sessions/object].
サブスクリプションの販売Selling Subscriptions
CashierのWebフック処理を設定する必要もあります。[!NOTE]
Note: Stripeチェックアウトを利用する前に、Stripeダッシュボードにより、固定価格で商品を定義してください。さらに、
Before utilizing Stripe Checkout, you should define Products with fixed prices in your Stripe dashboard. In addition, you should configure Cashier's webhook handling[#handling-stripe-webhooks].
アプリケーションで商品や定期購入の課金を提供するのは、敷居が高いかもしれません。しかし、CashierとStripe Checkoutのおかげで、モダンで堅牢な決済統合を簡単に構築できます。Offering product and subscription billing via your application can be intimidating. However, thanks to Cashier and Stripe Checkout[https://stripe.com/payments/checkout], you can easily build modern, robust payment integrations.
CashierとStripe
Checkoutを使ったサブスクリプションの販売方法を学ぶために、基本的な月額プラン(price_basic_monthly
)と年間プラン(price_basic_yearly
)を持つ定期購入サービスの簡単なシナリオを考えてみましょう。これら2つの価格は、Stripeダッシュボードの「ベーシック」商品(pro_basic
)にグループ化できます。さらに、エキスパート(Expert)プラン(pro_expert
)として提供しているサブスクリプションサービスも、提供しましょう。To learn how to sell
subscriptions using Cashier and Stripe Checkout,
let's consider the simple scenario of a subscription
service with a basic monthly
(price_basic_monthly
) and yearly
(price_basic_yearly
) plan. These two
prices could be grouped under a "Basic"
product (pro_basic
) in our Stripe
dashboard. In addition, our subscription service
might offer an Expert plan as
pro_expert
.
まず、顧客がどのように私たちのサービスを購読できるようにするか見つけましょう。もちろん、顧客がアプリケーションの価格ページで、ベーシックプランの「購入する」ボタンをクリックすることは想像できます。このボタンまたはリンクは、選んだプランのStripe Checkoutセッションを作成するLaravelルートへ、ユーザーを誘導する必要があります。First, let's discover how a customer can subscribe to our services. Of course, you can imagine the customer might click a "subscribe" button for the Basic plan on our application's pricing page. This button or link should direct the user to a Laravel route which creates the Stripe Checkout session for their chosen plan:
use Illuminate\Http\Request;
Route::get('/subscription-checkout', function (Request $request) {
return $request->user()
->newSubscription('default', 'price_basic_monthly')
->trialDays(5)
->allowPromotionCodes()
->checkout([
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
上例でわかるように、顧客をStripe
Checkoutセッションへリダイレクトし、ベーシックプランに加入できるようにしています。チェックアウトまたはキャンセルが成功すると、顧客はcheckout
にリダイレクトされます。(支払い方法によっては処理に数秒かかるものもあるため)実際にサブスクリプションが購読開始されたことを知るには、CashierのWebフック処理を設定する必要があります。As you can see in the example
above, we will redirect the customer to a Stripe
Checkout session which will allow them to subscribe
to our Basic plan. After a successful checkout or
cancellation, the customer will be redirected back
to the URL we provided to the checkout
method. To know when their subscription has actually
started (since some payment methods require a few
seconds to process), we'll also need to configure
Cashier's webhook
handling[#handling-stripe-webhooks].
顧客が購読を開始できるようにしたので、購読済みのユーザーだけがアクセスできるように、アプリケーションの特定の部分を制限する必要があります。もちろん、CashierのBillable
トレイトが提供するsubscribed
メソッドにより、いつでもユーザーの現在の購読ステータスを判定できます。Now that customers can start
subscriptions, we need to restrict certain portions
of our application so that only subscribed users can
access them. Of course, we can always determine a
user's current subscription status via the
subscribed
method provided by Cashier's
Billable
trait:
@if ($user->subscribed())
<p>You are subscribed.</p
endif
ユーザーが特定の商品や価格を購読しているかどうかも簡単に判断できます。We can even easily determine if a user is subscribed to specific product or price:
@if ($user->subscribedToProduct('pro_basic'))
<p>You are subscribed to our Basic product.</p>
endif
@if ($user->subscribedToPrice('price_basic_monthly'))
<p>You are subscribed to our monthly Basic plan.</p>
endif
サブスクリプション後続済みミドルウェアの構築Building a Subscribed Middleware
ミドルウェアを作成して、受信リクエストが購読済みユーザーからのものであることを判断できると便利です。このミドルウェアを定義すると、購読していないユーザーがあるルートにアクセスできないように、簡単にルートへ割り当てできますFor convenience, you may wish to create a middleware[/docs/{{version}}/middleware] which determines if the incoming request is from a subscribed user. Once this middleware has been defined, you may easily assign it to a route to prevent users that are not subscribed from accessing the route:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class Subscribed
{
/**
* 受信リクエストの処理
*/
public function handle(Request $request, Closure $next): Response
{
if (! $request->user()?->subscribed()) {
// ユーザーを支払いページへリダイレクトし、サブスクリプションを購入するか尋ねる
return redirect('/billing');
}
return $next($request);
}
}
ミドルウェアを定義したら、それをルートに割り当てます。Once the middleware has been defined, you may assign it to a route:
use App\Http\Middleware\Subscribed;
Route::get('/dashboard', function () {
// ...
})->middleware([Subscribed::class]);
顧客に支払いプランを管理させるAllowing Customers to Manage Their Billing Plan
もちろん、顧客がサブスクリプションプランを別の製品や「試用期間サービス」に変更したい場合もあり得ます。これを可能にする最も簡単な方法は、お客様をStripeの顧客支払いポータルへ誘導する方法です。このポータルは、ユーザーインターフェイスを提供し、顧客が請求書をダウンロードしたり、支払い方法を更新したり、サブスクリプションプランを変更したりできるようにします。Of course, customers may want to change their subscription plan to another product or "tier". The easiest way to allow this is by directing customers to Stripe's Customer Billing Portal[https://stripe.com/docs/no-code/customer-portal], which provides a hosted user interface that allows customers to download invoices, update their payment method, and change subscription plans.
まず、アプリケーションでユーザーを支払いポータルセッションへ導くためのLaravelルートへ誘導するリンクまたはボタンを定義します:First, define a link or button within your application that directs users to a Laravel route which we will utilize to initiate a Billing Portal session:
<a href="{{ route('billing') }}">
Billing
</a>
次に、Stripe顧客支払いポータルセッションを開始し、ユーザーをこのポータルへリダイレクトするルートを定義します。redirectToBillingPortal
メソッドは、ポータルを終了したときに、ユーザーが戻るべきURLを引数に取ります。Next, let's define the route that
initiates a Stripe Customer Billing Portal session
and redirects the user to the Portal. The
redirectToBillingPortal
method accepts
the URL that users should be returned to when
exiting the Portal:
use Illuminate\Http\Request;
Route::get('/billing', function (Request $request) {
return $request->user()->redirectToBillingPortal(route('dashboard'));
})->middleware(['auth'])->name('billing');
[!NOTE]
Note: CashierのWebフック処理を設定している限り、CashierはStripeから受信するWebフックを調べ、アプリケーションのCashier関連データベーステーブルを自動的に同期します。例えば、ユーザーがStripeの顧客支払いポータル経由で定期購入をキャンセルすると、Cashierは対応するWebフックを受信し、アプリケーションのデータベースで定期購入を「キャンセル」としてマークします。
As long as you have configured Cashier's webhook handling, Cashier will automatically keep your application's Cashier-related database tables in sync by inspecting the incoming webhooks from Stripe. So, for example, when a user cancels their subscription via Stripe's Customer Billing Portal, Cashier will receive the corresponding webhook and mark the subscription as "cancelled" in your application's database.
顧客Customers
顧客の取得Retrieving Customers
Cashier::findBillable
メソッドを使用して、StripeIDで顧客を取得できます。このメソッドは、Billableなモデルのインスタンスを返します。You can retrieve a customer by
their Stripe ID using the
Cashier::findBillable
method. This
method will return an instance of the billable
model:
use Laravel\Cashier\Cashier;
$user = Cashier::findBillable($stripeId);
顧客の作成Creating Customers
まれに、サブスクリプションを開始せずにStripeの顧客を作成したいことも起きるでしょう。これは、createAsStripeCustomer
メソッドを使用して実行できます。Occasionally, you may wish to
create a Stripe customer without beginning a
subscription. You may accomplish this using the
createAsStripeCustomer
method:
$stripeCustomer = $user->createAsStripeCustomer();
Stripeで顧客を作成しておき、あとからサブスクリプションを開始できます。オプションの$options
配列を指定して、追加のStripeAPIでサポートされている顧客作成パラメーターを渡せます。Once the customer has been
created in Stripe, you may begin a subscription at a
later date. You may provide an optional
$options
array to pass in any
additional customer creation parameters that are
supported by the Stripe
API[https://stripe.com/docs/api/customers/create]:
$stripeCustomer = $user->createAsStripeCustomer($options);
BillableなモデルのStripe顧客オブジェクトを返す場合は、asStripeCustomer
メソッドを使用できます。You may use the
asStripeCustomer
method if you want to
return the Stripe customer object for a billable
model:
$stripeCustomer = $user->asStripeCustomer();
createOrGetStripeCustomer
メソッドは、特定のBillableモデルのStripe顧客オブジェクトを取得したいが、BillableモデルがすでにStripe内の顧客であるかわからない場合に使用できます。このメソッドは、Stripeに新しい顧客がまだ存在しない場合、新しい顧客を作成します。The
createOrGetStripeCustomer
method may be
used if you would like to retrieve the Stripe
customer object for a given billable model but are
not sure whether the billable model is already a
customer within Stripe. This method will create a
new customer in Stripe if one does not already
exist:
$stripeCustomer = $user->createOrGetStripeCustomer();
顧客の更新Updating Customers
たまに、Stripeの顧客を追加情報と一緒に直接更新したい状況が起こるでしょう。これは、updateStripeCustomer
メソッドを使用して実行できます。このメソッドは、StripeAPIでサポートされている顧客更新オプションの配列を引数に取ります。Occasionally, you may wish to
update the Stripe customer directly with additional
information. You may accomplish this using the
updateStripeCustomer
method. This
method accepts an array of customer update
options supported by the Stripe
API[https://stripe.com/docs/api/customers/update]:
$stripeCustomer = $user->updateStripeCustomer($options);
残高Balances
Stripeでは、顧客の「残高」に入金または引き落としができます。後日新しい請求書に基づき、この残高は入金もしくは引き落としされます。顧客の合計残高を確認するには、Billableモデルに用意してあるbalance
メソッドを使用します。balance
メソッドは、顧客の通貨建てで残高をフォーマットした文字列で返します。Stripe allows you to credit or
debit a customer's "balance". Later, this
balance will be credited or debited on new invoices.
To check the customer's total balance you may use
the balance
method that is available on
your billable model. The balance
method
will return a formatted string representation of the
balance in the customer's currency:
$balance = $user->balance();
顧客の残高から引き落とすには、creditBalance
メソッドに値を指定します。また、必要に応じて、説明を指定することもできます。To credit a customer's balance,
you may provide a value to the
creditBalance
method. If you wish, you
may also provide a description:
$user->creditBalance(500, 'Premium customer top-up.');
debitBalance
メソッドへ値を渡すと、顧客の残高へ入金します。Providing a value to the
debitBalance
method will debit the
customer's balance:
$user->debitBalance(300, 'Bad usage penalty.');
applyBalance
メソッドは、その顧客に対する新しい顧客残高トランザクションを作成します。これらのトランザクションレコードはbalanceTransactions
メソッドを使って取得でき、顧客に確認してもらうため入金と引き落としのログを提供するのに便利です。The applyBalance
method will create new customer balance transactions
for the customer. You may retrieve these transaction
records using the balanceTransactions
method, which may be useful in order to provide a
log of credits and debits for the customer to
review:
// 全トランザクションの取得
$transactions = $user->balanceTransactions();
foreach ($transactions as $transaction) {
// トランザクションの金額
$amount = $transaction->amount(); // $2.31
// 利用できるなら、関連するインボイスの取得
$invoice = $transaction->invoice();
}
税金IDTax IDs
Cashierでは、顧客の税金IDを簡単に管理できます。例えば、taxIds
メソッドを使って、顧客に割り当てられている全ての税金IDをコレクションとして取得できます。Cashier offers an easy way to
manage a customer's tax IDs. For example, the
taxIds
method may be used to retrieve
all of the tax
IDs[https://stripe.com/docs/api/customer_tax_ids/object]
that are assigned to a customer as a
collection:
$taxIds = $user->taxIds();
識別子により、顧客の特定の税金IDを取得することもできます。You can also retrieve a specific tax ID for a customer by its identifier:
$taxId = $user->findTaxId('txi_belgium');
有効なタイプと値をcreateTaxId
メソッドへ渡し、新しい税金IDを作成できます。You may create a new Tax ID by
providing a valid
type[https://stripe.com/docs/api/customer_tax_ids/object#tax_id_object-type]
and value to the createTaxId
method:
$taxId = $user->createTaxId('eu_vat', 'BE0123456789');
createTaxId
メソッドは、VAT IDを顧客のアカウントへ即座に追加します。VAT
IDの検証はStripeも行いますが、これは非同期のプロセスです。検証の更新を通知するには、customer.tax_id.updated
Webフックイベントを購読し、VAT
IDのverification
パラメータを検査します。Webフックの取り扱いについては、Webフックの処理の定義に関するドキュメントを参照してください。The createTaxId
method will immediately add the VAT ID to the
customer's account. Verification of VAT IDs is
also done by
Stripe[https://stripe.com/docs/invoicing/customer/tax-ids#validation];
however, this is an asynchronous process. You can be
notified of verification updates by subscribing to
the customer.tax_id.updated
webhook
event and inspecting the VAT IDs
verification
parameter[https://stripe.com/docs/api/customer_tax_ids/object#tax_id_object-verification].
For more information on handling webhooks, please
consult the documentation on defining webhook
handlers[#handling-stripe-webhooks].
deleteTaxId
メソッドを使って税金IDを削除できます。You may delete a tax ID using the
deleteTaxId
method:
$user->deleteTaxId('txi_belgium');
顧客データをStripeと同期するSyncing Customer Data With Stripe
通常、アプリケーションのユーザーが氏名、メールアドレス、その他のStripeも保存している情報を更新した場合、その更新をStripeへ通知する必要があります。それにより、Stripeの情報とアプリケーションの情報が同期されます。Typically, when your application's users update their name, email address, or other information that is also stored by Stripe, you should inform Stripe of the updates. By doing so, Stripe's copy of the information will be in sync with your application's.
これを自動化するには、Billableモデルにイベントリスナを定義して、モデルのupdated
イベントに対応させます。そして、イベントリスナの中で、モデルのsyncStripeCustomerDetails
メソッドを呼び出します。To automate this, you may define
an event listener on your billable model that reacts
to the model's updated
event. Then,
within your event listener, you may invoke the
syncStripeCustomerDetails
method on the
model:
use App\Models\User;
use function Illuminate\Events\queueable;
/**
* モデルの「起動(booted)」メソッド
*/
protected static function booted(): void
{
static::updated(queueable(function (User $customer) {
if ($customer->hasStripeId()) {
$customer->syncStripeCustomerDetails();
}
}));
}
これで、顧客モデルが更新されるたびに、その情報がStripeと同期されます。便利なように、Cashierは顧客の初回作成時、自動的に顧客の情報をStripeと同期します。Now, every time your customer model is updated, its information will be synced with Stripe. For convenience, Cashier will automatically sync your customer's information with Stripe on the initial creation of the customer.
Cashierが提供する様々なメソッドをオーバーライドすることで、顧客情報をStripeに同期する際に使用するカラムをカスタマイズすることができます。例として、stripeName
メソッドをオーバーライドして、Cashierが顧客情報をStripeに同期する際に、顧客の「名前」とみなす属性をカスタマイズしてみましょう。You may customize the columns
used for syncing customer information to Stripe by
overriding a variety of methods provided by Cashier.
For example, you may override the
stripeName
method to customize the
attribute that should be considered the customer's
"name" when Cashier syncs customer
information to Stripe:
/**
* ストライプと同期する顧客名の取得
*/
public function stripeName(): string|null
{
return $this->company_name;
}
同様に、stripeEmail
、stripePhone
、stripeAddress
、stripePreferredLocales
メソッドをオーバーライドできます。これらのメソッドは、Stripe顧客オブジェクトの更新の際に、対応する顧客パラメータへ情報を同期します。顧客情報の同期プロセスを完全にコントロールしたい場合は、syncStripeCustomerDetails
メソッドをオーバーライドできます。Similarly, you may override the
stripeEmail
, stripePhone
,
stripeAddress
, and
stripePreferredLocales
methods. These
methods will sync information to their corresponding
customer parameters when updating the Stripe
customer
object[https://stripe.com/docs/api/customers/update].
If you wish to take total control over the customer
information sync process, you may override the
syncStripeCustomerDetails
method.
請求ポータルBilling Portal
Stripeは、請求ポータルを設定する簡単な方法を提供しており、顧客はサブスクリプション、支払い方法を管理し、請求履歴を表示できます。コントローラまたはルートからBillableモデルでredirectToBillingPortal
メソッドを呼び出すことにより、ユーザーをカスタマーポータルへリダイレクトできます。Stripe offers an easy way to
set up a billing
portal[https://stripe.com/docs/billing/subscriptions/customer-portal]
so that your customer can manage their subscription,
payment methods, and view their billing history. You
can redirect your users to the billing portal by
invoking the redirectToBillingPortal
method on the billable model from a controller or
route:
use Illuminate\Http\Request;
Route::get('/billing-portal', function (Request $request) {
return $request->user()->redirectToBillingPortal();
});
デフォルトでは、ユーザーがサブスクリプションの管理を終了すると、Stripe課金ポータル内のリンクを介してアプリケーションのhome
ルートに戻ります。redirectToBillingPortal
メソッドに引数としてURLを渡すことにより、ユーザーを戻す必要のあるカスタムURLを指定できます。By default, when the user is
finished managing their subscription, they will be
able to return to the home
route of
your application via a link within the Stripe
billing portal. You may provide a custom URL that
the user should return to by passing the URL as an
argument to the redirectToBillingPortal
method:
use Illuminate\Http\Request;
Route::get('/billing-portal', function (Request $request) {
return $request->user()->redirectToBillingPortal(route('billing'));
});
HTTPリダイレクトレスポンスを生成せずに、カスタマーポータルへのURLを生成したい場合は、billingPortalUrl
メソッドを呼び出してください。If you would like to generate the
URL to the billing portal without generating an HTTP
redirect response, you may invoke the
billingPortalUrl
method:
$url = $request->user()->billingPortalUrl(route('billing'));
支払い方法Payment Methods
支払い方法の保存Storing Payment Methods
Stripeでサブスクリプションを作成したり、「1回限りの」料金を実行したりするには、支払い方法を保存し、Stripeからその識別子を取得する必要があります。これを実現するアプローチは、支払方法をサブスクリプションにするか、単一料金にするかにより異なるため、以降で両方とも説明します。In order to create subscriptions or perform "one-off" charges with Stripe, you will need to store a payment method and retrieve its identifier from Stripe. The approach used to accomplish this differs based on whether you plan to use the payment method for subscriptions or single charges, so we will examine both below.
サブスクリプションの支払い方法Payment Methods for Subscriptions
サブスクリプションで将来使用するときのため顧客のクレジットカード情報を保存する場合、Stripeの"Setup
Intents"
APIを使用して、顧客の支払い方法の詳細を安全に収集する必要があります。"Setup
Intent"は、顧客の支払い方法により課金する意図をStripeに示します。CashierのBillable
トレイトには、新しいSetup
Intentsを簡単に作成するためのcreateSetupIntent
メソッドを用意しています。顧客の支払い方法の詳細を収集するフォームをレンダするルートまたはコントローラからこのメソッドを呼び出す必要があります。When storing a customer's credit
card information for future use by a subscription,
the Stripe "Setup Intents" API must be
used to securely gather the customer's payment
method details. A "Setup Intent" indicates
to Stripe the intention to charge a customer's
payment method. Cashier's Billable
trait includes the createSetupIntent
method to easily create a new Setup Intent. You
should invoke this method from the route or
controller that will render the form which gathers
your customer's payment method details:
return view('update-payment-method', [
'intent' => $user->createSetupIntent()
]);
Setup Intentsを作成してビューに渡したら、支払い方法を収集する要素にそのシークレットを添付する必要があります。たとえば、次の「支払い方法の更新」フォームについて考えてみます。After you have created the Setup Intent and passed it to the view, you should attach its secret to the element that will gather the payment method. For example, consider this "update payment method" form:
<input id="card-holder-name" type="text">
<!-- ストライプ要素のプレースホルダ -->
<div id="card-element"></div>
<button id="card-button" data-secret="{{ $intent->client_secret }}">
Update Payment Method
</button>
次に、Stripe.jsライブラリを使用して、Stripe要素をフォームに添付し、顧客の支払いの詳細を安全に収集します。Next, the Stripe.js library may be used to attach a Stripe Element[https://stripe.com/docs/stripe-js] to the form and securely gather the customer's payment details:
<script src="https://js.stripe.com/v3/"></script>
<script>
const stripe = Stripe('stripe-public-key');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
</script>
次に、カードを確認し、StripeのconfirmCardSetup
メソッドを使用してStripeから安全な「支払い方法識別子」を取得します。Next, the card can be verified
and a secure "payment method identifier"
can be retrieved from Stripe using Stripe's
confirmCardSetup
method[https://stripe.com/docs/js/setup_intents/confirm_card_setup]:
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
const clientSecret = cardButton.dataset.secret;
cardButton.addEventListener('click', async (e) => {
const { setupIntent, error } = await stripe.confirmCardSetup(
clientSecret, {
payment_method: {
card: cardElement,
billing_details: { name: cardHolderName.value }
}
}
);
if (error) {
// "error.message"をユーザーに表示…
} else {
// カードは正常に検証された…
}
});
Stripeがカードを検証したあとに、結果のsetupIntent.payment_method
識別子をLaravelアプリケーションに渡し、顧客にアタッチします。支払い方法は、新しい支払い方法として追加またはデフォルトの支払い方法の更新に使用のいずれかです。すぐに支払い方法識別子を使用して新しいサブスクリプションを作成することもできます。After the card has been verified
by Stripe, you may pass the resulting
setupIntent.payment_method
identifier
to your Laravel application, where it can be
attached to the customer. The payment method can
either be added as a new payment
method[#adding-payment-methods] or used
to update the default payment
method[#updating-the-default-payment-method].
You can also immediately use the payment method
identifier to create a new
subscription[#creating-subscriptions].
Stripeが提供しているこの概要を確認してください。[!NOTE]
Note: Setup Intentsと顧客の支払いの詳細の収集について詳しく知りたい場合は、
If you would like more information about Setup Intents and gathering customer payment details please review this overview provided by Stripe[https://stripe.com/docs/payments/save-and-reuse#php].
一回限りの支払いの支払い方法Payment Methods for Single Charges
もちろん、顧客の支払い方法に対して1回請求を行う場合、支払い方法IDを使用する必要があるのは1回だけです。Stripeの制約により、顧客が保存したデフォルトの支払い方法を単一の請求に使用することはできません。Stripe.jsライブラリを使用して、顧客が支払い方法の詳細を入力できるようにする必要があります。たとえば、次のフォームについて考えてみます。Of course, when making a single charge against a customer's payment method, we will only need to use a payment method identifier once. Due to Stripe limitations, you may not use the stored default payment method of a customer for single charges. You must allow the customer to enter their payment method details using the Stripe.js library. For example, consider the following form:
<input id="card-holder-name" type="text">
<!-- ストライプ要素のプレースホルダ -->
<div id="card-element"></div>
<button id="card-button">
Process Payment
</button>
このようなフォームを定義した後、Stripe.jsライブラリを使用してStripe要素をフォームに添付し、顧客の支払いの詳細を安全に収集します。After defining such a form, the Stripe.js library may be used to attach a Stripe Element[https://stripe.com/docs/stripe-js] to the form and securely gather the customer's payment details:
<script src="https://js.stripe.com/v3/"></script>
<script>
const stripe = Stripe('stripe-public-key');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
</script>
次にカードを確認し、StripeのcreatePaymentMethod
メソッドを使用してStripeから安全な「支払い方法識別子」を取得します。Next, the card can be verified
and a secure "payment method identifier"
can be retrieved from Stripe using Stripe's
createPaymentMethod
method[https://stripe.com/docs/stripe-js/reference#stripe-create-payment-method]:
const cardHolderName = document.getElementById('card-holder-name');
const cardButton = document.getElementById('card-button');
cardButton.addEventListener('click', async (e) => {
const { paymentMethod, error } = await stripe.createPaymentMethod(
'card', cardElement, {
billing_details: { name: cardHolderName.value }
}
);
if (error) {
// "error.message"をユーザーに表示…
} else {
// カードは正常に検証された…
}
});
カードが正常に確認されたら、paymentMethod.id
をLaravelアプリケーションに渡して、一回限りの請求を処理できます。If the card is verified
successfully, you may pass the
paymentMethod.id
to your Laravel
application and process a single
charge[#simple-charge].
支払い方法の取得Retrieving Payment Methods
BillableなモデルインスタンスのpaymentMethods
メソッドは、Laravel\Cashier\PaymentMethod
インスタンスのコレクションを返します。The paymentMethods
method on the billable model instance returns a
collection of
Laravel\Cashier\PaymentMethod
instances:
$paymentMethods = $user->paymentMethods();
このメソッドはデフォルトで、すべてのタイプの支払い方法を返します。特定のタイプの支払い方法を取得するには、type
をメソッドの引数に渡してください。By default, this method will
return payment methods of every type. To retrieve
payment methods of a specific type, you may pass the
type
as an argument to the
method:
$paymentMethods = $user->paymentMethods('sepa_debit');
顧客のデフォルトの支払い方法を取得するには、defaultPaymentMethod
メソッドを使用します。To retrieve the customer's
default payment method, the
defaultPaymentMethod
method may be
used:
$paymentMethod = $user->defaultPaymentMethod();
findPaymentMethod
メソッドを使用して、Billableモデルに関連付けている特定の支払い方法を取得できます。You can retrieve a specific
payment method that is attached to the billable
model using the findPaymentMethod
method:
$paymentMethod = $user->findPaymentMethod($paymentMethodId);
支払い方法の存在Payment Method Presence
Billableなモデルのアカウントにデフォルトの支払い方法が関連付けられているかどうかを確認するには、hasDefaultPaymentMethod
メソッドを呼び出します。To determine if a billable model
has a default payment method attached to their
account, invoke the
hasDefaultPaymentMethod
method:
if ($user->hasDefaultPaymentMethod()) {
// ...
}
hasPaymentMethod
メソッドを使用して、Billableなモデルのアカウントに少なくとも1つの支払い方法が関連付けられているかを判定できます。You may use the
hasPaymentMethod
method to determine if
a billable model has at least one payment method
attached to their account:
if ($user->hasPaymentMethod()) {
// ...
}
このメソッドはBillableモデルになにかの支払い方法があるかを判定します。モデルに特定のタイプの支払い方法が存在するかを判定するために、type
をメソッドの引数として渡すこともできます。This method will determine if the
billable model has any payment method at all. To
determine if a payment method of a specific type
exists for the model, you may pass the
type
as an argument to the
method:
if ($user->hasPaymentMethod('sepa_debit')) {
// ...
}
デフォルト支払い方法の変更Updating the Default Payment Method
updateDefaultPaymentMethod
メソッドは、顧客のデフォルトの支払い方法情報を更新するために使用します。このメソッドは、Stripe支払い方法識別子を受け入れ、新しい支払い方法をデフォルトの請求支払い方法として割り当てます。The
updateDefaultPaymentMethod
method may
be used to update a customer's default payment
method information. This method accepts a Stripe
payment method identifier and will assign the new
payment method as the default billing payment
method:
$user->updateDefaultPaymentMethod($paymentMethod);
デフォルトの支払い方法情報をStripeの顧客のデフォルトの支払い方法情報と同期するには、updateDefaultPaymentMethodFromStripe
メソッドを使用できます。To sync your default payment
method information with the customer's default
payment method information in Stripe, you may use
the
updateDefaultPaymentMethodFromStripe
method:
$user->updateDefaultPaymentMethodFromStripe();
[!WARNING]
Warning! 顧客のデフォルトの支払い方法は、新しいサブスクリプションの請求と作成にのみ使用できます。Stripeの制約により、1回だけの請求には使用できません。
The default payment method on a customer can only be used for invoicing and creating new subscriptions. Due to limitations imposed by Stripe, it may not be used for single charges.
支払い方法の追加Adding Payment Methods
新しい支払い方法を追加するには、支払い方法IDを渡して、BillableモデルでaddPaymentMethod
メソッドを呼び出してください。To add a new payment method, you
may call the addPaymentMethod
method on
the billable model, passing the payment method
identifier:
$user->addPaymentMethod($paymentMethod);
支払い方法の保存に関するドキュメントを確認してください。[!NOTE]
Note: 支払い方法の識別子を取得する方法については、
To learn how to retrieve payment method identifiers please review the payment method storage documentation[#storing-payment-methods].
支払い方法の削除Deleting Payment Methods
支払い方法を削除するには、削除したいLaravel\Cashier\PaymentMethod
インスタンスでdelete
メソッドを呼び出してください。To delete a payment method, you
may call the delete
method on the
Laravel\Cashier\PaymentMethod
instance
you wish to delete:
$paymentMethod->delete();
deletePaymentMethod
メソッドは、Billableモデルから特定の支払い方法を削除します。The
deletePaymentMethod
method will delete
a specific payment method from the billable
model:
$user->deletePaymentMethod('pm_visa');
deletePaymentMethods
メソッドは、Billableなモデルのすべての支払い方法情報を削除します。The
deletePaymentMethods
method will delete
all of the payment method information for the
billable model:
$user->deletePaymentMethods();
このメソッドはデフォルトで、すべてのタイプの支払い方法を削除します。特定のタイプの支払い方法を削除するには、メソッドの引数にtype
を渡してください。By default, this method will
delete payment methods of every type. To delete
payment methods of a specific type you can pass the
type
as an argument to the
method:
$user->deletePaymentMethods('sepa_debit');
[!WARNING]
Warning! ユーザーがアクティブなサブスクリプションを持っている場合、アプリケーションはユーザーがデフォルトの支払い方法を削除することを許してはいけません。
If a user has an active subscription, your application should not allow them to delete their default payment method.
サブスクリプションSubscriptions
サブスクリプションは、顧客に定期的な支払いを設定する方法を提供します。Cashierが管理するStripeサブスクリプションは、複数価格のサブスクリプション、サブスクリプション数量、トライアルなどをサポートします。Subscriptions provide a way to set up recurring payments for your customers. Stripe subscriptions managed by Cashier provide support for multiple subscription prices, subscription quantities, trials, and more.
サブスクリプションの作成Creating Subscriptions
サブスクリプションを作成するには、最初にBillableなモデルのインスタンスを取得します。これは通常、App\Models\User
のインスタンスになります。モデルインスタンスを取得したら、newSubscription
メソッドを使用してモデルのサブスクリプションを作成できます。To create a subscription, first
retrieve an instance of your billable model, which
typically will be an instance of
App\Models\User
. Once you have
retrieved the model instance, you may use the
newSubscription
method to create the
model's subscription:
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription(
'default', 'price_monthly'
)->create($request->paymentMethodId);
// ...
});
newSubscription
メソッドへ渡す最初の引数は、サブスクリプションの内部タイプです。アプリケーションが単一サブスクリプションのみ提供している場合は、これをdefault
やprimary
と名付けることが多いでしょう。このサブスクリプションタイプは、アプリケーション内部でのみ使用するものであり、ユーザーに表示するものではありません。また、スペースを含んではならず、サブスクリプションを作成した後は決して変更してはいけません。2番目の引数は、ユーザーが購読している価格の指定です。この値は、Stripeにおける価格の識別子に対応していなければなりません。The first argument passed to the
newSubscription
method should be the
internal type of the subscription. If your
application only offers a single subscription, you
might call this default
or
primary
. This subscription type is only
for internal application usage and is not meant to
be shown to users. In addition, it should not
contain spaces and it should never be changed after
creating the subscription. The second argument is
the specific price the user is subscribing to. This
value should correspond to the price's identifier in
Stripe.
Stripe支払い方法識別子またはStripePaymentMethod
オブジェクトを引数に取るcreate
メソッドは、サブスクリプションを開始するのと同時に、BillableなモデルのStripe顧客IDおよびその他の関連する課金情報でデータベースを更新します。The create
method,
which accepts a Stripe payment method
identifier[#storing-payment-methods] or
Stripe PaymentMethod
object, will begin
the subscription as well as update your database
with the billable model's Stripe customer ID and
other relevant billing information.
Warning! 支払い方法識別子を
create
サブスクリプションメソッドへ直接渡すと、ユーザーの保存済み支払い方法にも自動的に追加されます。[!WARNING]
Passing a payment method identifier directly to thecreate
subscription method will also automatically add it to the user's stored payment methods.
インボイスメールによる定期払いの集金Collecting Recurring Payments via Invoice Emails
顧客の定期払いを自動集金する代わりに、期日ごとに請求書(インボイス)を顧客にメールで送信するように、Stripeへ指示できます。顧客にはインボイスを受け取った後、手作業で支払ってもらいます。インボイスを使い定期払いを集金する場合、顧客は前もって支払い方法を指定する必要はありません。Instead of collecting a customer's recurring payments automatically, you may instruct Stripe to email an invoice to the customer each time their recurring payment is due. Then, the customer may manually pay the invoice once they receive it. The customer does not need to provide a payment method up front when collecting recurring payments via invoices:
$user->newSubscription('default', 'price_monthly')->createAndSendInvoice();
顧客が請求書を支払わなければ、サブスクリプションがキャンセルされる期間は、days_until_due
オプションで決まります。デフォルトは30日間ですが、必要に応じ、日数をこのオプションへ指定してください。The amount of time a customer has
to pay their invoice before their subscription is
cancelled is determined by the
days_until_due
option. By default, this
is 30 days; however, you may provide a specific
value for this option if you wish:
$user->newSubscription('default', 'price_monthly')->createAndSendInvoice([], [
'days_until_due' => 30
]);
サブスクリプション数量Quantities
サブスクリプションの作成時にの価格に数量を指定する場合は、サブスクリプションを作成する前にビルダでquantity
メソッドを呼び出してください。If you would like to set a
specific
quantity[https://stripe.com/docs/billing/subscriptions/quantities]
for the price when creating the subscription, you
should invoke the quantity
method on
the subscription builder before creating the
subscription:
$user->newSubscription('default', 'price_monthly')
->quantity(5)
->create($paymentMethod);
詳細の追加Additional Details
Stripeがサポートしている顧客やサブスクリプションオプションを指定する場合、create
メソッドの2番目と3番目の引数に指定することで、追加できます。If you would like to specify
additional
customer[https://stripe.com/docs/api/customers/create]
or
subscription[https://stripe.com/docs/api/subscriptions/create]
options supported by Stripe, you may do so by
passing them as the second and third arguments to
the create
method:
$user->newSubscription('default', 'price_monthly')->create($paymentMethod, [
'email' => $email,
], [
'metadata' => ['note' => 'Some extra information.'],
]);
クーポンCoupons
サブスクリプションの作成時にクーポンを適用する場合は、withCoupon
メソッドを使用できます。If you would like to apply a
coupon when creating the subscription, you may use
the withCoupon
method:
$user->newSubscription('default', 'price_monthly')
->withCoupon('code')
->create($paymentMethod);
また、Stripeプロモーションコードを適用したい場合には、withPromotionCode
メソッドを使用してください。Or, if you would like to apply a
Stripe promotion
code[https://stripe.com/docs/billing/subscriptions/discounts/codes],
you may use the withPromotionCode
method:
$user->newSubscription('default', 'price_monthly')
->withPromotionCode('promo_code_id')
->create($paymentMethod);
指定するプロモーションコードIDは、プロモーションコードに割り当てたStripe
APIのIDであり、顧客向けのプロモーションコードにすべきでありません。もし、指定する顧客向けプロモーションコードに基づいた、プロモーションコードIDを見つける必要がある場合は、findPromotionCode
メソッドを使用してください。The given promotion code ID
should be the Stripe API ID assigned to the
promotion code and not the customer facing promotion
code. If you need to find a promotion code ID based
on a given customer facing promotion code, you may
use the findPromotionCode
method:
// 顧客向けコードにより、プロモーションコードを見つける
$promotionCode = $user->findPromotionCode('SUMMERSALE');
// 顧客向けコードにより、有効なプロモーションコードを見つける
$promotionCode = $user->findActivePromotionCode('SUMMERSALE');
上の例で、返される$promotionCode
オブジェクトは、Laravel\Cashier\PromotionCode
インスタンスです。このクラスは、基礎となるStripe\PromotionCode
オブジェクトをデコレートしています。プロモーションコードに関連するクーポンは、coupon
メソッドを呼び出すことで取得できます。In the example above, the
returned $promotionCode
object is an
instance of
Laravel\Cashier\PromotionCode
. This
class decorates an underlying
Stripe\PromotionCode
object. You can
retrieve the coupon related to the promotion code by
invoking the coupon
method:
$coupon = $user->findPromotionCode('SUMMERSALE')->coupon();
クーポンのインスタンスで、割引額と、固定割引/パーセントベース割引を判定できます。The coupon instance allows you to determine the discount amount and whether the coupon represents a fixed discount or percentage based discount:
if ($coupon->isPercentage()) {
return $coupon->percentOff().'%'; // 21.5%
} else {
return $coupon->amountOff(); // $5.99
}
また、顧客やサブスクリプションへ現在適用している割引も取得できます。You can also retrieve the discounts that are currently applied to a customer or subscription:
$discount = $billable->discount();
$discount = $subscription->discount();
返されるLaravel\Cashier\Discount
インスタンスは、基礎となるStripe\Discount
オブジェクトインスタンスをデコレートしています。この割引に関連するクーポンは、coupon
メソッドを呼び出し、取得できます。The returned
Laravel\Cashier\Discount
instances
decorate an underlying Stripe\Discount
object instance. You may retrieve the coupon related
to this discount by invoking the coupon
method:
$coupon = $subscription->discount()->coupon();
新しいクーポンやプロモーションコードを顧客やサブスクリプションへ適用したい場合は、applyCoupon
か、applyPromotionCode
メソッドにより、可能です。If you would like to apply a new
coupon or promotion code to a customer or
subscription, you may do so via the
applyCoupon
or
applyPromotionCode
methods:
$billable->applyCoupon('coupon_id');
$billable->applyPromotionCode('promotion_code_id');
$subscription->applyCoupon('coupon_id');
$subscription->applyPromotionCode('promotion_code_id');
顧客側へ提示するプロモーションコードは使用せず、そのプロモーションコードに割り当てられたStripe APIのIDを使用していることに留意してください。クーポンやプロモーションコードは、一度に1つの顧客やサブスクリプションにのみ適用できます。Remember, you should use the Stripe API ID assigned to the promotion code and not the customer facing promotion code. Only one coupon or promotion code can be applied to a customer or subscription at a given time.
この主題の詳細は、クーポンとプロモーションコードに関する、Stripeのドキュメントを参照してください。For more info on this subject, please consult the Stripe documentation regarding coupons[https://stripe.com/docs/billing/subscriptions/coupons] and promotion codes[https://stripe.com/docs/billing/subscriptions/coupons/codes].
サブスクリプションの追加Adding Subscriptions
すでにデフォルトの支払い方法を持っている顧客へサブスクリプションを追加する場合は、サブスクリプションビルダでadd
メソッドを呼び出してください。If you would like to add a
subscription to a customer who already has a default
payment method you may invoke the add
method on the subscription builder:
use App\Models\User;
$user = User::find(1);
$user->newSubscription('default', 'price_monthly')->add();
Stripeダッシュボードからのサブスクリプション作成Creating Subscriptions From the Stripe Dashboard
Stripeダッシュボード自体からも、サブスクリプションを作成できます。その際、Cashierは新しく追加したサブスクリプションを同期し、それらにdefault
のタイプを割り当てます。ダッシュボードから作成するサブスクリプションに割り当てるサブスクリプション名をカスタマイズするには、Webフックイベントハンドラを定義してください。You may also create subscriptions
from the Stripe dashboard itself. When doing so,
Cashier will sync newly added subscriptions and
assign them a type of default
. To
customize the subscription type that is assigned to
dashboard created subscriptions, define webhook
event
handlers[#defining-webhook-event-handlers].
また、Stripeダッシュボードから作成できるサブスクリプションのタイプは1つだけです。アプリケーションが異なるタイプを使用する複数のサブスクリプションを提供している場合でも、Stripeダッシュボードから追加できるサブスクリプションのタイプは1つのみです。In addition, you may only create one type of subscription via the Stripe dashboard. If your application offers multiple subscriptions that use different types, only one type of subscription may be added through the Stripe dashboard.
最後に、アプリケーションが提供するサブスクリプションのタイプごとに、アクティブなサブスクリプションを1つだけ追加するようにしてください。顧客が2つのdefault
サブスクリプションを持っている場合、たとえ両方がアプリケーションのデータベースと同期されていても、最後に追加したサブスクリプションのみ、Cashierは使用します。Finally, you should always make
sure to only add one active subscription per type of
subscription offered by your application. If a
customer has two default
subscriptions,
only the most recently added subscription will be
used by Cashier even though both would be synced
with your application's database.
サブスクリプション状態のチェックChecking Subscription Status
顧客がアプリケーションでサブスクリプションを購入すると、さまざまな便利なメソッドを使用して、サブスクリプションの状態を簡単に確認できます。まず、subscribed
メソッドは、そのサブスクリプションが現在無料トライアル期間内であっても、顧客がアクティブなサブスクリプションを持っている場合は、true
を返します。subscribed
メソッドは、最初の引数としてサブスクリプションのタイプを引数に取ります。Once a customer 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 customer has an
active subscription, even if the subscription is
currently within its trial period. The
subscribed
method accepts the type of
the subscription as its first argument:
if ($user->subscribed('default')) {
// ...
}
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:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureUserIsSubscribed
{
/**
* 受信リクエストの処理
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if ($request->user() && ! $request->user()->subscribed('default')) {
// このユーザーは、支払い済みユーザーではない
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 determining if you should display a
warning to the user that they are still on their
trial period:
if ($user->subscription('default')->onTrial()) {
// ...
}
subscribedToProduct
メソッドは、ユーザーが指定のStripe製品識別子に基づき、指定の製品を購読しているかどうかを判断するために使用します。Stripeでの商品とは、価格のコレクションです。この例では、ユーザーのdefault
サブスクリプションが、アプリケーションの「プレミアム」製品をアクティブに購読しているかを判定してみます。指定するStripe製品識別子は、Stripeダッシュボード内の製品識別子のいずれかに対応する必要があります。The
subscribedToProduct
method may be used
to determine if the user is subscribed to a given
product based on a given Stripe product's
identifier. In Stripe, products are collections of
prices. In this example, we will determine if the
user's default
subscription is actively
subscribed to the application's "premium"
product. The given Stripe product identifier should
correspond to one of your product's identifiers in
the Stripe dashboard:
if ($user->subscribedToProduct('prod_premium', 'default')) {
// ...
}
subscribedToProduct
メソッドへ配列を渡し、ユーザーのdefault
サブスクリプションがアプリケーションの"basic"か"premium"製品をアクティブに購読しているかを判断してみます。By passing an array to the
subscribedToProduct
method, you may
determine if the user's default
subscription is actively subscribed to the
application's "basic" or
"premium" product:
if ($user->subscribedToProduct(['prod_basic', 'prod_premium'], 'default')) {
// ...
}
subscribedToPrice
メソッドは、顧客のサブスクリプションが指定する価格IDに対応しているかを判断するために使用します。The
subscribedToPrice
method may be used to
determine if a customer's subscription corresponds
to a given price ID:
if ($user->subscribedToPrice('price_basic_monthly', 'default')) {
// ...
}
recurring
メソッドを使用して、ユーザーが現在サブスクリプションを購入しており、無料トライアル期間でないことを判定します。The recurring
method
may be used to determine if the user is currently
subscribed and is no longer within their trial
period:
if ($user->subscription('default')->recurring()) {
// ...
}
Warning! ユーザーが同じタイプのサブスクリプションを2つ持っている場合、
subscription
メソッドは最新のサブスクリプションを常に返します。たとえば、ユーザーがdefault
というタイプのサブスクリプションレコードを2つ持っているとします。この場合、サブスクリプションの1つは古い期限切れのサブスクリプションであり、もう1つは現在のアクティブなサブスクリプションである可能性があります。最新のサブスクリプションを常に返しますが、古いサブスクリプションは履歴レビューのためにデータベースに保持されます。[!WARNING]
If a user has two subscriptions with the same type, the most recent subscription will always be returned by thesubscription
method. For example, a user might have two subscription records with the type ofdefault
; however, one of the subscriptions may be an old, expired subscription, while the other is the current, active subscription. The most recent subscription will always be returned while older subscriptions are kept in the database for historical review.
サブスクリプションの取り消しCanceled Subscription Status
ユーザーがかつてアクティブなサブスクリプション購入者であったが、そのサブスクリプションをキャンセルしたかを判定するには、canceled
メソッドを使用します。To determine if the user was once
an active subscriber but has canceled their
subscription, you may use the canceled
method:
if ($user->subscription('default')->canceled()) {
// ...
}
また、ユーザーがサブスクリプションをキャンセルしたが、サブスクリプションが完全に期限切れになるまで「猶予期間」にあるかを判定することもできます。たとえば、ユーザーが3月10日に期限切れになる予定のサブスクリプションを3月5日にキャンセルした場合、ユーザーは3月10日まで「猶予期間」になります。この間、subscribed
メソッドは引き続きtrue
を返すことに注意してください。You may also determine if a user
has canceled 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('default')->onGracePeriod()) {
// ...
}
ユーザーがサブスクリプションをキャンセルし、「猶予期間」も過ぎていることを判断するには、ended
メソッドを使用します。To determine if the user has
canceled their subscription and is no longer within
their "grace period", you may use the
ended
method:
if ($user->subscription('default')->ended()) {
// ...
}
不完全および延滞ステータスIncomplete and Past Due Status
サブスクリプションの作成後に二次支払いアクションが必要な場合、そのサブスクリプションは「未完了(incomplete
)」としてマークされます。サブスクリプションステータスは、Cashierのsubscriptions
データベーステーブルのstripe_status
列に保存されます。If a subscription requires a
secondary payment action after creation the
subscription will be marked as
incomplete
. Subscription statuses are
stored in the stripe_status
column of
Cashier's subscriptions
database
table.
同様に、価格を変更するときに二次支払いアクションが必要な場合、そのサブスクリプションは「延滞(past_due
)」としてマークされます。サブスクリプションがこれらの状態のどちらかにある場合、顧客が支払いを確認するまでサブスクリプションはアクティブになりません。サブスクリプションの支払いが不完全であるかの判定は、BillableモデルまたはサブスクリプションインスタンスでhasIncompletePayment
メソッドを使用します。Similarly, if a secondary payment
action is required when swapping prices the
subscription will be marked as
past_due
. When your subscription is in
either of these states it will not be active until
the customer has confirmed their payment.
Determining if a subscription has an incomplete
payment may be accomplished using the
hasIncompletePayment
method on the
billable model or a subscription
instance:
if ($user->hasIncompletePayment('default')) {
// ...
}
if ($user->subscription('default')->hasIncompletePayment()) {
// ...
}
サブスクリプションの支払いが不完全な場合は、latestPayment
識別子を渡して、ユーザーをCashierの支払い確認ページに誘導する必要があります。サブスクリプションインスタンスで使用可能なlatestPayment
メソッドを使用して、この識別子を取得できます。When a subscription has an
incomplete payment, you should direct the user to
Cashier's payment confirmation page, passing the
latestPayment
identifier. You may use
the latestPayment
method available on
subscription instance to retrieve this
identifier:
<a href="{{ route('cashier.payment', $subscription->latestPayment()->id) }}">
お支払いを確認してください。
</a>
もし、サブスクリプションがpast_due
かincomplete
の状態でも、アクティブとみなしたい場合は、Cashierが提供するkeepPastDueSubscriptionsActive
と、keepIncompleteSubscriptionsActive
メソッドを使用します。通常、これらのメソッドはAppAppServiceProviders
のregister
メソッドで呼び出す必要があります。If you would like the
subscription to still be considered active when it's
in a past_due
or
incomplete
state, you may use the
keepPastDueSubscriptionsActive
and
keepIncompleteSubscriptionsActive
methods provided by Cashier. Typically, these
methods should be called in the
register
method of your
App\Providers\AppServiceProvider
:
use Laravel\Cashier\Cashier;
/**
* 全アプリケーションサービスの登録
*/
public function register(): void
{
Cashier::keepPastDueSubscriptionsActive();
Cashier::keepIncompleteSubscriptionsActive();
}
Warning! サブスクリプションが
incomplete
状態の場合、支払いが確認されるまで変更できません。したがって、サブスクリプションがincomplete
状態の場合、swap
メソッドとupdateQuantity
メソッドは例外を投げます。[!WARNING]
When a subscription is in anincomplete
state it cannot be changed until the payment is confirmed. Therefore, theswap
andupdateQuantity
methods will throw an exception when the subscription is in anincomplete
state.
サブスクリプションのスコープSubscription Scopes
ほとんどのサブスクリプション状態はクエリスコープとしても利用できるため、特定の状態にあるサブスクリプションはデータベースから簡単にクエリできます。Most subscription states are also available as query scopes so that you may easily query your database for subscriptions that are in a given state:
// すべてのアクティブなサブスクリプションを取得
$subscriptions = Subscription::query()->active()->get();
// ユーザーのキャンセルしたサブスクリプションをすべて取得
$subscriptions = $user->subscriptions()->canceled()->get();
使用可能なスコープの完全なリストは、以下のとおりです。A complete list of available scopes is available below:
Subscription::query()->active();
Subscription::query()->canceled();
Subscription::query()->ended();
Subscription::query()->incomplete();
Subscription::query()->notCanceled();
Subscription::query()->notOnGracePeriod();
Subscription::query()->notOnTrial();
Subscription::query()->onGracePeriod();
Subscription::query()->onTrial();
Subscription::query()->pastDue();
Subscription::query()->recurring();
価格の変更Changing Prices
顧客がアプリケーションでサブスクリプションを購読した後に、新しいサブスクリプション価格に変更したいと思うことがあるでしょう。顧客のサブスクリプションを新しい価格に変更するには、Stripe価格の識別子をswap
メソッドに渡します。価格を交換する場合に、それが以前にキャンセルされている場合、ユーザーはサブスクリプションの再アクティブ化を希望していると見なします。指定する価格識別子は、Stripeダッシュボードの利用可能なStripe価格識別子である必要があります。After a customer is subscribed to
your application, they may occasionally want to
change to a new subscription price. To swap a
customer to a new price, pass the Stripe price's
identifier to the swap
method. When
swapping prices, it is assumed that the user would
like to re-activate their subscription if it was
previously canceled. The given price identifier
should correspond to a Stripe price identifier
available in the Stripe dashboard:
use App\Models\User;
$user = App\Models\User::find(1);
$user->subscription('default')->swap('price_yearly');
その顧客が無料トライアル中の場合、トライアル期間は維持されます。さらに、サブスクリプションに「数量」が存在する場合、その数量も維持されます。If the customer is on trial, the trial period will be maintained. Additionally, if a "quantity" exists for the subscription, that quantity will also be maintained.
価格を交換して、顧客が現在行っている無料トライアル期間をキャンセルしたい場合は、skipTrial
メソッドを呼び出してください。If you would like to swap prices
and cancel any trial period the customer is
currently on, you may invoke the
skipTrial
method:
$user->subscription('default')
->skipTrial()
->swap('price_yearly');
価格を交換して、次の請求サイクルを待たずにすぐに顧客に請求する場合は、swapAndInvoice
メソッドを使用します。If you would like to swap prices
and immediately invoice the customer instead of
waiting for their next billing cycle, you may use
the swapAndInvoice
method:
$user = User::find(1);
$user->subscription('default')->swapAndInvoice('price_yearly');
比例按分Prorations
デフォルトで、Stripeは価格を変更するときに料金を比例按分します。noProrate
メソッドを使用すると、料金を比例按分せずにサブスクリプションの価格を更新できます。By default, Stripe prorates
charges when swapping between prices. The
noProrate
method may be used to update
the subscription's price without prorating the
charges:
$user->subscription('default')->noProrate()->swap('price_yearly');
サブスクリプションの比例按分について詳しくは、Stripeドキュメントを参照してください。For more information on subscription proration, consult the Stripe documentation[https://stripe.com/docs/billing/subscriptions/prorations].
Warning!
swapAndInvoice
メソッドの前にnoProrate
メソッドを実行しても、比例按分には影響しません。請求書は常に発行されます。[!WARNING]
Executing thenoProrate
method before theswapAndInvoice
method will have no effect on proration. An invoice will always be issued.
サブスクリプション数量Subscription Quantity
サブスクリプションは「数量」の影響を受ける場合があります。たとえば、プロジェクト管理アプリケーションは、プロジェクトごとに月額$10を請求する場合があります。incrementQuantity
メソッドとdecrementQuantity
メソッドを使用して、サブスクリプション数量を簡単に増減できます。Sometimes subscriptions are
affected by "quantity". For example, a
project management application might charge $10 per
month per project. You may use the
incrementQuantity
and
decrementQuantity
methods to easily
increment or decrement your subscription
quantity:
use App\Models\User;
$user = User::find(1);
$user->subscription('default')->incrementQuantity();
// サブスクリプションの現在の数量へ5個追加
$user->subscription('default')->incrementQuantity(5);
$user->subscription('default')->decrementQuantity();
// サブスクリプションの現在の数量から5個減少
$user->subscription('default')->decrementQuantity(5);
または、updateQuantity
メソッドを使用して特定の数量を設定することもできます。Alternatively, you may set a
specific quantity using the
updateQuantity
method:
$user->subscription('default')->updateQuantity(10);
noProrate
メソッドを使用すると、料金を比例按分せずにサブスクリプションの数量を更新できます。The noProrate
method
may be used to update the subscription's quantity
without prorating the charges:
$user->subscription('default')->noProrate()->updateQuantity(10);
サブスクリプション数量の詳細については、Stripeドキュメントを参照してください。For more information on subscription quantities, consult the Stripe documentation[https://stripe.com/docs/subscriptions/quantities].
複数商品サブスクリプション時の数量Quantities for Subscriptions With Multiple Products
サブスクリプションが複数商品を持つサブスクリプションであれば、数量を増加/減少させたい価格のIDを増分/減分メソッドの第2引数へ渡す必要があります。If your subscription is a subscription with multiple products[#subscriptions-with-multiple-products], you should pass the ID of the price whose quantity you wish to increment or decrement as the second argument to the increment / decrement methods:
$user->subscription('default')->incrementQuantity(1, 'price_chat');
複数商品のサブスクリプションSubscriptions With Multiple Products
複数製品のサブスクリプション
では、1つのサブスクリプションに複数の支払い製品を割り当てることができます。たとえば、顧客サービス「ヘルプデスク」アプリケーションで、月額10ドルの基本サブスクリプションがあり、月額15ドルの追加料金でライブチャットのアドオン製品を提供するサービスを構築している場合を想像してみてください。複数製品のサブスクリプションの情報は、Cashierのsubscription_items
データベーステーブルに格納されます。Subscription with multiple
products[https://stripe.com/docs/billing/subscriptions/multiple-products]
allow you to assign multiple billing products to a
single subscription. For example, imagine you are
building a customer service "helpdesk"
application that has a base subscription price of
$10 per month but offers a live chat add-on product
for an additional $15 per month. Information for
subscriptions with multiple products is stored in
Cashier's subscription_items
database
table.
特定のサブスクリプションに対し、複数の商品を指定するには、newSubscription
メソッドの第2引数へ価格の配列を渡します。You may specify multiple products
for a given subscription by passing an array of
prices as the second argument to the
newSubscription
method:
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription('default', [
'price_monthly',
'price_chat',
])->create($request->paymentMethodId);
// ...
});
上記の例では、顧客のdefault
サブスクリプションに2つの価格を設定しています。どちらの価格も、それぞれの請求間隔で請求されます。必要に応じて、quantity
メソッドを使用して、各価格に特定の数量を指定できます。In the example above, the
customer will have two prices attached to their
default
subscription. Both prices will
be charged on their respective billing intervals. If
necessary, you may use the quantity
method to indicate a specific quantity for each
price:
$user = User::find(1);
$user->newSubscription('default', ['price_monthly', 'price_chat'])
->quantity(5, 'price_chat')
->create($paymentMethod);
既存のサブスクリプションに別の価格を追加したい場合は、サブスクリプションのaddPrice
メソッドを呼び出します。If you would like to add another
price to an existing subscription, you may invoke
the subscription's addPrice
method:
$user = User::find(1);
$user->subscription('default')->addPrice('price_chat');
上記の例では、新しい価格が追加され、次の請求サイクルで顧客へ請求します。すぐに顧客へ請求したい場合は、addPriceAndInvoice
メソッドを使います。The example above will add the
new price and the customer will be billed for it on
their next billing cycle. If you would like to bill
the customer immediately you may use the
addPriceAndInvoice
method:
$user->subscription('default')->addPriceAndInvoice('price_chat');
数量を指定して価格を追加したい場合には、addPrice
またはaddPriceAndInvoice
メソッドの第2引数に数量を渡します。If you would like to add a price
with a specific quantity, you can pass the quantity
as the second argument of the addPrice
or addPriceAndInvoice
methods:
$user = User::find(1);
$user->subscription('default')->addPrice('price_chat', 5);
サブスクリプションから価格を削除するには、removePrice
メソッドを使用します。You may remove prices from
subscriptions using the removePrice
method:
$user->subscription('default')->removePrice('price_chat');
[!WARNING]
Warning! サブスクリプションの最後の価格は削除できません。代わりに、単にサブスクリプションをキャンセルしてください。
You may not remove the last price on a subscription. Instead, you should simply cancel the subscription.
価格の交換Swapping Prices
また、複数製品を持つ月額プランに付随する価格を変更することもできます。例えば、ある顧客がprice_basic
というサブスクリプションと、price_chat
というアドオン製品を購入していて、その顧客をprice_basic
からprice_pro
価格へアップグレードしたいとします。You may also change the prices
attached to a subscription with multiple products.
For example, imagine a customer has a
price_basic
subscription with a
price_chat
add-on product and you want
to upgrade the customer from the
price_basic
to the
price_pro
price:
use App\Models\User;
$user = User::find(1);
$user->subscription('default')->swap(['price_pro', 'price_chat']);
上記の例を実行すると、price_basic
のサブスクリプションアイテムが削除され、price_chat
のサブスクリプションアイテムが保存されます。さらに、price_pro
のサブスクリプションアイテムが新たに作成されます。When executing the example above,
the underlying subscription item with the
price_basic
is deleted and the one with
the price_chat
is preserved.
Additionally, a new subscription item for the
price_pro
is created.
また、キーと値のペアの配列をswap
メソッドに渡すことで、サブスクリプションアイテムのオプションを指定することもできます。たとえば、サブスクリプション価格の数量を指定する必要があるかもしれません。You can also specify subscription
item options by passing an array of key / value
pairs to the swap
method. For example,
you may need to specify the subscription price
quantities:
$user = User::find(1);
$user->subscription('default')->swap([
'price_pro' => ['quantity' => 5],
'price_chat'
]);
サブスクリプションの価格を1つだけ交換したい場合は、サブスクリプションアイテム自体のswap
メソッドを使って交換できます。この方法は、サブスクリプションの他の価格に関する既存のメタデータをすべて保持したい場合に特に有効です。If you want to swap a single
price on a subscription, you may do so using the
swap
method on the subscription item
itself. This approach is particularly useful if you
would like to preserve all of the existing metadata
on the subscription's other prices:
$user = User::find(1);
$user->subscription('default')
->findItemOrFail('price_basic')
->swap('price_pro');
比例按分Proration
Stripeは複数商品を持つサブスクリプションに価格を追加または削除する際、デフォルトで料金を按分します。按分せずに価格を調整したい場合は、価格操作時にnoProrate
メソッドをチェーンしてください。By default, Stripe will prorate
charges when adding or removing prices from a
subscription with multiple products. If you would
like to make a price adjustment without proration,
you should chain the noProrate
method
onto your price operation:
$user->subscription('default')->noProrate()->removePrice('price_chat');
サブスクリプション数量Quantities
個々のサブスクリプション価格の個数を変更する場合は、既存の個数メソッドを使用して、価格のIDをメソッドの追加引数として渡すことで更新できます。If you would like to update quantities on individual subscription prices, you may do so using the existing quantity methods[#subscription-quantity] by passing the ID of the price as an additional argument to the method:
$user = User::find(1);
$user->subscription('default')->incrementQuantity(5, 'price_chat');
$user->subscription('default')->decrementQuantity(3, 'price_chat');
$user->subscription('default')->updateQuantity(10, 'price_chat');
Warning! サブスクリプションに複数の価格がある場合、
Subscription
モデルのstripe_plan
属性とquantity
属性はnull
になります。個々の価格属性にアクセスするには、Subscription
モデルで使用可能なitems
リレーションを使用する必要があります。[!WARNING]
When a subscription has multiple prices thestripe_price
andquantity
attributes on theSubscription
model will benull
. To access the individual price attributes, you should use theitems
relationship available on theSubscription
model.
サブスクリプションアイテムSubscription Items
サブスクリプションに複数の価格がある場合、データベースのsubscription_items
テーブルに複数のサブスクリプション「アイテム」が保存されます。サブスクリプションのitems
リレーションを介してこれらにアクセスできます。When a subscription has multiple
prices, it will have multiple subscription
"items" stored in your database's
subscription_items
table. You may
access these via the items
relationship
on the subscription:
use App\Models\User;
$user = User::find(1);
$subscriptionItem = $user->subscription('default')->items->first();
// 特定のアイテムのStripe価格と個数を取得
$stripePrice = $subscriptionItem->stripe_price;
$quantity = $subscriptionItem->quantity;
findItemOrFail
メソッドを使用して特定の価格を取得できます。You can also retrieve a specific
price using the findItemOrFail
method:
$user = User::find(1);
$subscriptionItem = $user->subscription('default')->findItemOrFail('price_chat');
複数のサブスクリプションMultiple Subscriptions
Stripeの顧客は, サブスクリプションを同時に複数利用可能です。例えば、水泳とウェイトリフティング両方のサブスクリプションを提供するスポーツジムを経営している場合、各サブスクリプションは異なる価格設定になっているでしょう。もちろん、顧客はどちらか、もしくは両方のプランを申し込むことができるでしょう。Stripe allows your customers to have multiple subscriptions simultaneously. For example, you may run a gym that offers a swimming subscription and a weight-lifting subscription, and each subscription may have different pricing. Of course, customers should be able to subscribe to either or both plans.
アプリケーションでサブスクリプションを作成するときに、newSubscription
メソッドへサブスクリプションのタイプを指定してください。このタイプは、ユーザーが開始するサブスクリプションのタイプを表す任意の文字列にできます。When your application creates
subscriptions, you may provide the type of the
subscription to the newSubscription
method. The type may be any string that represents
the type of subscription the user is
initiating:
use Illuminate\Http\Request;
Route::post('/swimming/subscribe', function (Request $request) {
$request->user()->newSubscription('swimming')
->price('price_swimming_monthly')
->create($request->paymentMethodId);
// ...
});
この例は、顧客に月ごとの水泳サブスクリプションを開始しました。しかし、彼らは後で年間サブスクリプションに変更したいと思うかもしれません。顧客のサブスクリプションを調整するときは、単純にswimming
サブスクリプションの価格を交換できます。In this example, we initiated a
monthly swimming subscription for the customer.
However, they may want to swap to a yearly
subscription at a later time. When adjusting the
customer's subscription, we can simply swap the
price on the swimming
subscription:
$user->subscription('swimming')->swap('price_swimming_yearly');
もちろん、完全に解約することも可能です。Of course, you may also cancel the subscription entirely:
$user->subscription('swimming')->cancel();
使用量ベースの料金Metered Billing
使用量ベースの料金を使用すると、課金サイクル中の製品の利用状況に基づき顧客へ請求できます。たとえば、顧客が1か月に送信するテキストメッセージまたは電子メールの数に基づいて顧客に請求するケースが考えられます。Metered billing[https://stripe.com/docs/billing/subscriptions/metered-billing] allows you to charge customers based on their product usage during a billing cycle. For example, you may charge customers based on the number of text messages or emails they send per month.
使用量ベースの料金を使用開始するには、最初にStripeダッシュボードの従量制価格(metered
price)で新しい製品を作成する必要があります。次に、meteredPrice
を使用して、従量制の価格IDを顧客のサブスクリプションに追加します。To start using metered billing,
you will first need to create a new product in your
Stripe dashboard with a metered price. Then, use the
meteredPrice
to add the metered price
ID to a customer subscription:
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription('default')
->meteredPrice('price_metered')
->create($request->paymentMethodId);
// ...
});
Stripeの支払いから従量制サブスクリプションを開始することもできます。You may also start a metered subscription via Stripe Checkout[#checkout]:
$checkout = Auth::user()
->newSubscription('default', [])
->meteredPrice('price_metered')
->checkout();
return view('your-checkout-view', [
'checkout' => $checkout,
]);
利用状況のレポートReporting Usage
顧客がアプリケーションを使用しているとき、正確な請求ができるように、利用状況をStripeへ報告します。従量制サブスクリプションの使用量を増やすには、reportUsage
メソッドを使用します。As your customer uses your
application, you will report their usage to Stripe
so that they can be billed accurately. To increment
the usage of a metered subscription, you may use the
reportUsage
method:
$user = User::find(1);
$user->subscription('default')->reportUsage();
デフォルトでは、「使用量」1が請求期間に追加されます。または、指定の「使用量」を渡して、請求期間中の顧客の使用量に追加することもできます。By default, a "usage quantity" of 1 is added to the billing period. Alternatively, you may pass a specific amount of "usage" to add to the customer's usage for the billing period:
$user = User::find(1);
$user->subscription('default')->reportUsage(15);
アプリケーションが単一のサブスクリプションで複数の価格を提供している場合は、reportUsageFor
メソッドを使用して、利用状況を報告する従量制価格を指定する必要があります。If your application offers
multiple prices on a single subscription, you will
need to use the reportUsageFor
method
to specify the metered price you want to report
usage for:
$user = User::find(1);
$user->subscription('default')->reportUsageFor('price_metered', 15);
以前に報告した利用状況を更新する必要も起こるでしょう。これにはタイムスタンプまたはDateTimeInterface
インスタンスを2番目のパラメータとしてreportUsage
に渡します。その際、Stripeはその時点で報告された利用状況を更新します。指定する日時は現在の請求期間内であるため、以前の使用記録を引き続き更新できます。Sometimes, you may need to update
usage which you have previously reported. To
accomplish this, you may pass a timestamp or a
DateTimeInterface
instance as the
second parameter to reportUsage
. When
doing so, Stripe will update the usage that was
reported at that given time. You can continue to
update previous usage records as the given date and
time is still within the current billing
period:
$user = User::find(1);
$user->subscription('default')->reportUsage(5, $timestamp);
使用記録の取得Retrieving Usage Records
顧客の過去の利用状況を取得するには、サブスクリプションインスタンスのusageRecords
メソッドを使用します。To retrieve a customer's past
usage, you may use a subscription instance's
usageRecords
method:
$user = User::find(1);
$usageRecords = $user->subscription('default')->usageRecords();
アプリケーションが1つのサブスクリプションで複数の価格を提供している場合は、usageRecordsFor
メソッドを使用して、使用記録を取得する従量制価格を指定します。If your application offers
multiple prices on a single subscription, you may
use the usageRecordsFor
method to
specify the metered price that you wish to retrieve
usage records for:
$user = User::find(1);
$usageRecords = $user->subscription('default')->usageRecordsFor('price_metered');
usageRecords
メソッドとusageRecordsFor
メソッドは、使用レコードの連想配列を含むCollectionインスタンスを返します。この配列を繰り返し処理して、顧客の合計使用量を表示できます。The usageRecords
and
usageRecordsFor
methods return a
Collection instance containing an associative array
of usage records. You may iterate over this array to
display a customer's total usage:
@foreach ($usageRecords as $usageRecord)
- Period Starting: {{ $usageRecord['period']['start'] }}
- Period Ending: {{ $usageRecord['period']['end'] }}
- Total Usage: {{ $usageRecord['total_usage'] }}
@endforeach
返されるすべての利用状況データの完全なリファレンスと、Stripeのカーソルベースのペジネーションの使用方法の詳細は、Stripe公式のAPIドキュメントを参照してください。For a full reference of all usage data returned and how to use Stripe's cursor based pagination, please consult the official Stripe API documentation[https://stripe.com/docs/api/usage_records/subscription_item_summary_list].
サブスクリプションの税率Subscription Taxes
Stripe Taxを使って自動的に税金を計算できます。[!WARNING]
Warning! 税率を手作業で計算する代わりに、
Instead of calculating Tax Rates manually, you can automatically calculate taxes using Stripe Tax[#tax-configuration]
ユーザーがサブスクリプションで支払う税率を指定するには、BillableなモデルにtaxRates
メソッドを実装し、Stripe税率IDを含む配列を返す必要があります。これらの税率は、Stripeダッシュボードで定義します。To specify the tax rates a user
pays on a subscription, you should implement the
taxRates
method on your billable model
and return an array containing the Stripe tax rate
IDs. You can define these tax rates in your
Stripe
dashboard[https://dashboard.stripe.com/test/tax-rates]:
/**
* 顧客のサブスクリプションに適用する税率
*
* @return array<int, string>
*/
public function taxRates(): array
{
return ['txr_id'];
}
taxRates
メソッドを使用すると、顧客ごとに税率を適用できます。これは、ユーザーベースが複数の国と税率にまたがる場合に役立つでしょう。The taxRates
method
enables you to apply a tax rate on a
customer-by-customer basis, which may be helpful for
a user base that spans multiple countries and tax
rates.
複数商品のサブスクリプションを提供している場合は、BillableなモデルにpriceTaxRates
メソッドを実装することで、プランごとに異なる税率を定義できます。If you're offering subscriptions
with multiple products, you may define different tax
rates for each price by implementing a
priceTaxRates
method on your billable
model:
/**
* 顧客のサブスクリプションに適用する税率
*
* @return array<string, array<int, string>>
*/
public function priceTaxRates(): array
{
return [
'price_monthly' => ['txr_id'],
];
}
Warning!
taxRates
メソッドはサブスクリプション料金にのみ適用されます。Cashierを使用して「1回限り」の料金を請求する場合は、その時点で税率を手作業で指定する必要があります。[!WARNING]
ThetaxRates
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.
税率の同期Syncing Tax Rates
taxRates
メソッドによりハードコードした税率IDを変更しても、ユーザーの既存サブスクリプションの設定税率は同じまま残っています。既存のサブスクリプションの税額を新しいtaxRates
値で更新する場合は、ユーザーのサブスクリプションインスタンスでsyncTaxRates
メソッドを呼び出す必要があります。When changing the hard-coded tax
rate IDs returned by the taxRates
method, the tax settings on any existing
subscriptions for the user will remain the same. If
you wish to update the tax value for existing
subscriptions with the new taxRates
values, you should call the
syncTaxRates
method on the user's
subscription instance:
$user->subscription('default')->syncTaxRates();
これにより、複数商品を持つサブスクリプションの全商品の税率も同期されます。もしアプリケーションで複数商品のサブスクリプションを提供しているなら、課金モデルがpriceTaxRates
メソッド(上記)を実装していることを確認する必要があります。This will also sync any item tax
rates for a subscription with multiple products. If
your application is offering subscriptions with
multiple products, you should ensure that your
billable model implements the
priceTaxRates
method discussed
above[#subscription-taxes].
非課税Tax Exemption
Cashierは、顧客が非課税であるかどうかを判断するために、isNotTaxExempt
、isTaxExempt
、reverseChargeApplies
メソッドも提供しています。これらのメソッドは、StripeAPIを呼び出して、顧客の免税ステータスを判定します。Cashier also offers the
isNotTaxExempt
,
isTaxExempt
, and
reverseChargeApplies
methods to
determine if the customer is tax exempt. These
methods will call the Stripe API to determine a
customer's tax exemption status:
use App\Models\User;
$user = User::find(1);
$user->isTaxExempt();
$user->isNotTaxExempt();
$user->reverseChargeApplies();
Warning! これらのメソッドは、すべての
Laravel\Cashier\Invoice
オブジェクトでも使用できます。ただし、Invoice
オブジェクトで呼び出した場合、メソッドは請求書が作成された時点の免税状態を用います。[!WARNING]
These methods are also available on anyLaravel\Cashier\Invoice
object. However, when invoked on anInvoice
object, the methods will determine the exemption status at the time the invoice was created.
サブスクリプション基準日Subscription Anchor Date
デフォルトの請求サイクル基準日は、サブスクリプションが作成された日付、または無料トライアル期間が使用されている場合はトライアルが終了した日付です。請求基準日を変更する場合は、anchorBillingCycleOn
メソッドを使用します。By default, the billing cycle
anchor is the date the subscription was created or,
if a trial period is used, the date that the trial
ends. If you would like to modify the billing anchor
date, you may use the
anchorBillingCycleOn
method:
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$anchor = Carbon::parse('first day of next month');
$request->user()->newSubscription('default', 'price_monthly')
->anchorBillingCycleOn($anchor->startOfDay())
->create($request->paymentMethodId);
// ...
});
サブスクリプションの請求サイクルの管理の詳細については、Stripe請求サイクルのドキュメントを参照してください。For more information on managing subscription billing cycles, consult the Stripe billing cycle documentation[https://stripe.com/docs/billing/subscriptions/billing-cycle]
サブスクリプションの取り消しCancelling Subscriptions
サブスクリプションをキャンセルするには、ユーザーのサブスクリプションでcancel
メソッドを呼び出します。To cancel a subscription, call
the cancel
method on the user's
subscription:
$user->subscription('default')->cancel();
サブスクリプションがキャンセルされると、Cashierは自動的にsubscriptions
データベーステーブルのends_at
カラムを設定します。このカラムは、subscribed
メソッドがfalse
を返し始めるタイミングを決めるため使用されます。When a subscription is canceled,
Cashier will automatically set the
ends_at
column in your
subscriptions
database table. This
column is used to know when the
subscribed
method should begin
returning false
.
たとえば、顧客が3月1日にサブスクリプションをキャンセルしたが、そのサブスクリプションが3月5日までに終了するようスケジュールされていなかった場合、subscribed
メソッドは3月5日までtrue
を返し続けます。この振る舞いを行うのは、ユーザーは請求サイクルが終了するまでアプリケーションの使用を通常継続できるためです。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. This is done because a user is typically
allowed to continue using an application until the
end of their billing cycle.
onGracePeriod
メソッドを使用して、ユーザーがサブスクリプションをキャンセルしたが、まだ「猶予期間」にあるかどうかを判断できます。You may determine if a user has
canceled their subscription but are still on their
"grace period" using the
onGracePeriod
method:
if ($user->subscription('default')->onGracePeriod()) {
// ...
}
サブスクリプションをすぐにキャンセルする場合は、ユーザーのサブスクリプションでcancelNow
メソッドを呼び出します。If you wish to cancel a
subscription immediately, call the
cancelNow
method on the user's
subscription:
$user->subscription('default')->cancelNow();
サブスクリプションをすぐにキャンセルし、従量制による使用量の未請求部分や、新規/保留中の請求項目を請求する場合は、ユーザーのサブスクリプションに対しcancelNowAndInvoice
メソッドを呼び出します。If you wish to cancel a
subscription immediately and invoice any remaining
un-invoiced metered usage or new / pending proration
invoice items, call the
cancelNowAndInvoice
method on the
user's subscription:
$user->subscription('default')->cancelNowAndInvoice();
特定の時間に購読をキャンセルすることもできます。You may also choose to cancel the subscription at a specific moment in time:
$user->subscription('default')->cancelAt(
now()->addDays(10)
);
最後に、関連するユーザーモデルを削除する前に、必ずユーザーのサブスクリプションをキャンセルしてください:Finally, you should always cancel user subscriptions before deleting the associated user model:
$user->subscription('default')->cancelNow();
$user->delete();
サブスクリプションの再開Resuming Subscriptions
顧客がサブスクリプションをキャンセルし、それを再開する場合は、サブスクリプションに対しresume
メソッドを呼び出します。サブスクリプションを再開するには、顧客は「猶予期間」内である必要があります。If a customer has canceled their
subscription and you wish to resume it, you may
invoke the resume
method on the
subscription. The customer must still be within
their "grace period" in order to resume a
subscription:
$user->subscription('default')->resume();
顧客がサブスクリプションをキャンセルし、サブスクリプションが完全に期限切れになる前にそのサブスクリプションを再開する場合、請求はすぐに顧客へ課せられれません。代わりに、サブスクリプションを再アクティブ化し、元の請求サイクルで請求します。If the customer cancels a subscription and then resumes that subscription before the subscription has fully expired the customer 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 Payment Method 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:
use Illuminate\Http\Request;
Route::post('/user/subscribe', function (Request $request) {
$request->user()->newSubscription('default', 'price_monthly')
->trialDays(10)
->create($request->paymentMethodId);
// ...
});
このメソッドは、データベース内のサブスクリプションレコードに無料トライアル期間の終了日を設定し、この日付が過ぎるまで顧客への請求を開始しないようにStripeに指示します。trialDays
メソッドを使用すると、CashierはStripeの価格に設定しているデフォルトの無料トライアル期間を上書きします。This method will set the trial
period ending date on the subscription record within
the database and instruct Stripe to not begin
billing the customer until after this date. When
using the trialDays
method, Cashier
will overwrite any default trial period configured
for the price in Stripe.
[!WARNING]
Warning! 無料トライアル期間の終了日より前に顧客がそのサブスクリプションをキャンセルしなかった場合、無料トライアル期間の終了時にすぐ課金されるため、無料トライアル期間の終了日をユーザーに必ず通知する必要があります。
If the customer's subscription is not canceled 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.
trialUntil
メソッドを使用すると、無料トライアル期間をいつ終了するかを指定するDateTime
インスタンスを渡せます。The trialUntil
method allows you to provide a DateTime
instance that specifies when the trial period should
end:
use Carbon\Carbon;
$user->newSubscription('default', 'price_monthly')
->trialUntil(Carbon::now()->addDays(10))
->create($paymentMethod);
ユーザーインスタンスのonTrial
メソッドまたはサブスクリプションインスタンスのonTrial
メソッドのいずれかを使用して、ユーザーが無料トライアル期間内にあるかどうか判定できます。以下の2例は同じ働きです。You may determine if a 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
equivalent:
if ($user->onTrial('default')) {
// ...
}
if ($user->subscription('default')->onTrial()) {
// ...
}
endTrial
メソッドを使用して、サブスクリプションの無料トライアル期間を即時終了できます。You may use the
endTrial
method to immediately end a
subscription trial:
$user->subscription('default')->endTrial();
既存のトライアル期間が切れているかを判断するには、hasExpiredTrial
メソッドを使用します。To determine if an existing trial
has expired, you may use the
hasExpiredTrial
methods:
if ($user->hasExpiredTrial('default')) {
// ...
}
if ($user->subscription('default')->hasExpiredTrial()) {
// ...
}
ストライプ/Cashierでの無料トライアル日数の定義Defining Trial Days in Stripe / Cashier
価格が受け取るトライアル日数をStripeダッシュボードで定義するか、常にCashierを使用して明示的に渡すかを選択できます。Stripeで価格の試用日数を定義することを選択した場合、過去にそのサブスクリプションを購読していた顧客の新しいサブスクリプションを含む、新しいサブスクリプションは全部、明示的にskipTrial()
メソッドを呼び出さない限り、常に無料トライアル期間が提供されることに注意してください。You may choose to define how many
trial days your price's receive in the Stripe
dashboard or always pass them explicitly using
Cashier. If you choose to define your price's trial
days in Stripe you should be aware that new
subscriptions, including new subscriptions for a
customer that had a subscription in the past, will
always receive a trial period unless you explicitly
call the skipTrial()
method.
支払い方法事前登録なしWithout Payment Method 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:
use App\Models\User;
$user = User::create([
// ...
'trial_ends_at' => now()->addDays(10),
]);
Warning! Billableなモデルのクラス定義内の
trial_ends_at
属性に日付のキャストを必ず追加してください。[!WARNING]
Be sure to add a date cast[/docs/{{version}}/eloquent-mutators#date-casting] for thetrial_ends_at
attribute within your billable model's class definition.
Cashierはこのタイプの無料トライアル期間を「一般的な無料トライアル期間(generic
trial)」と呼んでいます。これは、既存のサブスクリプションに関連付けられていないからです。BillableなモデルインスタンスのonTrial
メソッドは、現在の日付がtrial_ends_at
の値を超えていない場合にtrue
を返します。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 billable model
instance will return true
if the
current date is not past the value of
trial_ends_at
:
if ($user->onTrial()) {
// ユーザーは無料トライアル期間内
}
ユーザーの実際のサブスクリプションを作成する準備ができたら、通常どおり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('default', 'price_monthly')->create($paymentMethod);
ユーザーの無料トライアル終了日を取得するには、trialEndsAt
メソッドを使用します。このメソッドは、ユーザーがトライアル中の場合はCarbon日付インスタンスを返し、そうでない場合はnull
を返します。デフォルト以外の特定のサブスクリプションの試用終了日を取得する場合は、オプションのサブスクリプションタイプパラメーターを渡すこともできます。To retrieve the user's trial
ending date, you may use the
trialEndsAt
method. This method will
return a Carbon date instance if a user is on a
trial or null
if they aren't. You may
also pass an optional subscription type parameter if
you would like to get the trial ending date for a
specific subscription other than the default
one:
if ($user->onTrial()) {
$trialEndsAt = $user->trialEndsAt('main');
}
ユーザーが「一般的な」無料トライアル期間内であり、実際のサブスクリプションをまだ作成していないことを具体的に知りたい場合は、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 yet
created an actual subscription:
if ($user->onGenericTrial()) {
// ユーザーは「一般的な」無料トライアル期間内
}
無料トライアル期間の延長Extending Trials
extendTrial
メソッドを使用すると、サブスクリプションの作成後にサブスクリプションの無料トライアル期間を延長できます。無料トライアル期間がすでに終了していて、顧客にサブスクリプションの料金が既に請求されている場合でも、延長無料トライアル期間を提供できます。無料トライアル期間内に費やされた時間は、その顧客の次の請求から差し引かれます。The extendTrial
method allows you to extend the trial period of a
subscription after the subscription has been
created. If the trial has already expired and the
customer is already being billed for the
subscription, you can still offer them an extended
trial. The time spent within the trial period will
be deducted from the customer's next
invoice:
use App\Models\User;
$subscription = User::find(1)->subscription('default');
// 今から7日後に無料トライアル期間終了
$subscription->extendTrial(
now()->addDays(7)
);
// 無料トライアル期間をさらに5日追加
$subscription->extendTrial(
$subscription->trial_ends_at->addDays(5)
);
StripeのWebフックの処理Handling Stripe Webhooks
Stripe CLIを使用して、ローカル開発中にWebhookをテストすることができます。[!NOTE]
Note:
You may use the Stripe CLI[https://stripe.com/docs/stripe-cli] to help test webhooks during local development.
Stripeは、Webフックを介してさまざまなイベントをアプリケーションに通知できます。デフォルトでは、CashierのWebフックコントローラを指すルートは、Cashierサービスプロバイダにより自動的に登録されます。このコントローラは、すべての受信Webフックリクエストを処理します。Stripe can notify your application of a variety of events via webhooks. By default, a route that points to Cashier's webhook controller is automatically registered by the Cashier service provider. This controller will handle all incoming webhook requests.
デフォルトでは、Cashier Webフックコントローラは、(Stripe設定で定義する)課金失敗が多すぎるサブスクリプションのキャンセル、顧客の更新、顧客の削除、サブスクリプションの更新、および支払い方法の変更を自動的に処理します。ただし、この後ですぐに説明しますが、このコントローラを拡張して、任意のStripe Webフックイベントを処理できます。By default, the Cashier webhook controller will automatically handle cancelling subscriptions that have too many failed charges (as defined by your Stripe settings), customer updates, customer deletions, subscription updates, and payment method changes; however, as we'll soon discover, you can extend this controller to handle any Stripe webhook event you like.
アプリケーションがStripe
Webフックを処理できるようにするには、StripeコントロールパネルでWebフックURLを設定してください。デフォルトでは、CashierのWebフックコントローラは/stripe/webhook
URLパスに応答します。Stripeコントロールパネルで有効にする必要があるすべてのWebフックの完全なリストは次のとおりです。To ensure your application can
handle Stripe webhooks, be sure to configure the
webhook URL in the Stripe control panel. By default,
Cashier's webhook controller responds to the
/stripe/webhook
URL path. The full list
of all webhooks you should enable in the Stripe
control panel are:
customer.subscription.created
customer.subscription.created
customer.subscription.updated
customer.subscription.updated
customer.subscription.deleted
customer.subscription.deleted
customer.updated
customer.updated
customer.deleted
customer.deleted
payment_method.automatically_updated
payment_method.automatically_updated
invoice.payment_action_required
invoice.payment_action_required
invoice.payment_succeeded
invoice.payment_succeeded
Cashierは、cashier:webhook
Artisanコマンドを利便性のために用意しています。このコマンドはCashierが必要とするすべてのイベントをリッスンする、StripeのWebフックを作成します。For
convenience, Cashier
includes a
cashier:webhook
Artisan command.
This command will
create a webhook in
Stripe that listens
to all of the events
required by
Cashier:
php artisan cashier:webhook
作成されたWebhookはデフォルトで、環境変数APP_URL
とCashierに含まれるcashier.webhook
ルートで定義したURLを示します。別のURLを使用したい場合は、このコマンドを実行するとき、--url
オプションで指定できます。By
default, the created
webhook will point
to the URL defined
by the
APP_URL
environment variable
and the
cashier.webhook
route that is
included with
Cashier. You may
provide the
--url
option when invoking
the command if you
would like to use a
different
URL:
php artisan cashier:webhook --url "https://example.com/stripe/webhook"
作成されるWebフックは、使用するCashierバージョンが対応しているStripe
APIバージョンを使用します。異なるStripeのバージョンを使用したい場合は、--api-version
オプションを指定してください。The
webhook that is
created will use the
Stripe API version
that your version of
Cashier is
compatible with. If
you would like to
use a different
Stripe version, you
may provide the
--api-version
option:
php artisan cashier:webhook --api-version="2019-12-03"
作成後、Webフックはすぐに有効になります。Webフックを作成するが、準備が整うまで無効にしておく場合は、コマンド実行時に、--disabled
オプションを指定します。After
creation, the
webhook will be
immediately active.
If you wish to
create the webhook
but have it disabled
until you're ready,
you may provide the
--disabled
option when invoking
the
command:
php artisan cashier:webhook --disabled
Webフック署名の確認ミドルウェアを使って、受信するStripe Webフックリクエストを保護してください。[!WARNING]
Warning! Cashierに含まれる
Make sure you protect incoming Stripe webhook requests with Cashier's included webhook signature verification[#verifying-webhook-signatures] middleware.
WebフックとCSRF保護Webhooks and CSRF Protection
Stripe WebフックはLaravelのCSRF保護をバイパスする必要があるため、Laravelが受信するStripe
WebフックのCSRFトークンを検証させない必要があります。そのため、アプリケーションのbootstrap/app.php
ファイルで、CSRF保護からstripe/*
を除外する必要があります。Since
Stripe webhooks need
to bypass Laravel's
CSRF
protection[/docs/{{version}}/csrf],
you should ensure
that Laravel does
not attempt to
validate the CSRF
token for incoming
Stripe webhooks. To
accomplish this, you
should exclude
stripe/*
from CSRF protection
in your
application's
bootstrap/app.php
file:
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(except: [
'stripe/*',
]);
})
Webフックイベントハンドラの定義Defining Webhook Event Handlers
Cashierは課金の失敗やその他一般的なStripe Webフックイベントによる、サブスクリプションキャンセルを自動的に処理します。ただし、追加でWebフックイベントを処理したい場合は、Cashierが発行する以下のイベントをリッスンすることで可能です。Cashier automatically handles subscription cancellations for failed charges and other common Stripe webhook events. However, if you have additional webhook events you would like to handle, you may do so by listening to the following events that are dispatched by Cashier:
Laravel\Cashier\Events\WebhookReceived
Laravel\Cashier\Events\WebhookReceived
Laravel\Cashier\Events\WebhookHandled
Laravel\Cashier\Events\WebhookHandled
両イベントも、Stripe
Webフックの完全なペイロードが含んでいます。例えば、invoice.payment_succeeded
というWebフックを扱いたい場合は、そのイベントを処理するリスナを登録します。Both
events
contain the
full payload
of the
Stripe
webhook. For
example, if
you wish to
handle the
invoice.payment_succeeded
webhook, you
may register
a
listener[/docs/{{version}}/events#defining-listeners]
that will
handle the
event:
<?php
namespace App\Listeners;
use Laravel\Cashier\Events\WebhookReceived;
class StripeEventListener
{
/**
* 受信したStripeのWebフックを処理
*/
public function handle(WebhookReceived $event): void
{
if ($event->payload['type'] === 'invoice.payment_succeeded') {
// 受信イベントの処理…
}
}
}
Webフック署名の確認Verifying Webhook Signatures
Webフックを保護するために、StripeのWebフック署名を使用できます。便利なように、Cashierには受信Stripe Webフックリクエストが有効であるかを検証するミドルウェアが自動的に含まれています。To secure your webhooks, you may use Stripe's webhook signatures[https://stripe.com/docs/webhooks/signatures]. For convenience, Cashier automatically includes a middleware which validates that the incoming Stripe webhook request is valid.
Webフックの検証を有効にするには、STRIPE_WEBHOOK_SECRET
環境変数がアプリケーションの.env
ファイルに設定されていることを確認してください。Webフックのsecret
は、Stripeアカウントダッシュボードから取得できます。To
enable
webhook
verification,
ensure that
the
STRIPE_WEBHOOK_SECRET
environment
variable is
set in your
application's
.env
file. The
webhook
secret
may be
retrieved
from your
Stripe
account
dashboard.
一回限りの支払いSingle Charges
シンプルな支払いSimple Charge
顧客に対して1回限りの請求を行う場合は、Billableなモデルインスタンスでcharge
メソッドを使用します。charge
メソッドの2番目の引数として支払い方法識別子を指定する必要があります。If
you would
like to make
a one-time
charge
against a
customer,
you may use
the
charge
method on a
billable
model
instance.
You will
need to
provide a
payment
method
identifier[#payment-methods-for-single-charges]
as the
second
argument to
the
charge
method:
use Illuminate\Http\Request;
Route::post('/purchase', function (Request $request) {
$stripeCharge = $request->user()->charge(
100, $request->paymentMethodId
);
// ...
});
charge
メソッドは3番目の引数を取り、ベースにあるStripeの課金作成へのオプションを指定できます。課金作成時に利用できるオプションの詳細は、Stripeドキュメントを参照してください。The
charge
method
accepts an
array as its
third
argument,
allowing you
to pass any
options you
wish to the
underlying
Stripe
charge
creation.
More
information
regarding
the options
available to
you when
creating
charges may
be found in
the
Stripe
documentation[https://stripe.com/docs/api/charges/create]:
$user->charge(100, $paymentMethod, [
'custom_option' => $value,
]);
また、基礎となる顧客やユーザーなしにcharge
メソッドを使用することもできます。そのためには、アプリケーションのBillableなモデルの新しいインスタンスでcharge
メソッドを呼び出します。You
may also use
the
charge
method
without an
underlying
customer or
user. To
accomplish
this, invoke
the
charge
method on a
new instance
of your
application's
billable
model:
use App\Models\User;
$stripeCharge = (new User)->charge(100, $paymentMethod);
課金失敗の場合、charge
メソッドは例外を投げます。課金が成功すると、メソッドはLaravel\Cashier\Payment
のインスタンスを返します。The
charge
method will
throw an
exception if
the charge
fails. If
the charge
is
successful,
an instance
of
Laravel\Cashier\Payment
will be
returned
from the
method:
try {
$payment = $user->charge(100, $paymentMethod);
} catch (Exception $e) {
// ...
}
Warning!
charge
メソッドは、アプリケーションで使用する通貨の最小単位で支払額を引数に取ります。例えば、顧客が米ドルで支払う場合、金額はペニーで指定する必要があります。[!WARNING]
Thecharge
method accepts the payment amount in the lowest denominator of the currency used by your application. For example, if customers are paying in United States Dollars, amounts should be specified in pennies.
インボイス付きの支払いCharge With Invoice
時には、一回限りの請求を行い、顧客にPDFのインボイスを提供する必要があるでしょう。invoicePrice
メソッドを使えば、それが可能です。例えば、新しいシャツを5枚購入した顧客へ請求書を発行してみましょう。Sometimes
you may need
to make a
one-time
charge and
offer a PDF
invoice to
your
customer.
The
invoicePrice
method lets
you do just
that. For
example,
let's
invoice a
customer for
five new
shirts:
$user->invoicePrice('price_tshirt', 5);
インボイスは、ユーザーのデフォルトの支払い方法に対し即時請求されます。invoicePrice
メソッドは3番目の引数として配列も受け入れます。この配列には、インボイスアイテムの請求オプションを指定します。メソッドの4番目の引数も配列で、インボイス自体の請求オプションを指定します。The
invoice will
be
immediately
charged
against the
user's
default
payment
method. The
invoicePrice
method also
accepts an
array as its
third
argument.
This array
contains the
billing
options for
the invoice
item. The
fourth
argument
accepted by
the method
is also an
array which
should
contain the
billing
options for
the invoice
itself:
$user->invoicePrice('price_tshirt', 5, [
'discounts' => [
['coupon' => 'SUMMER21SALE']
],
], [
'default_tax_rates' => ['txr_id'],
]);
invoicePrice
と同様、tabPrice
メソッドを使用して、複数のアイテム(1インボイスにつき250アイテムまで)を顧客の「タブ」へ追加し、顧客にインボイスを発行することで、一回限りの課金ができます。例として、シャツ5枚とマグカップ2個のインボイスを顧客へ発行してみましょう。Similarly
to
invoicePrice
,
you may use
the
tabPrice
method to
create a
one-time
charge for
multiple
items (up to
250 items
per invoice)
by adding
them to the
customer's
"tab"
and then
invoicing
the
customer.
For example,
we may
invoice a
customer for
five shirts
and two
mugs:
$user->tabPrice('price_tshirt', 5);
$user->tabPrice('price_mug', 2);
$user->invoice();
もしくは、invoiceFor
メソッドを使って、顧客のデフォルトの支払い方法に対して「一回限り」の請求を行うこともできます。Alternatively,
you may use
the
invoiceFor
method to
make a
"one-off"
charge
against the
customer's
default
payment
method:
$user->invoiceFor('One Time Fee', 500);
invoiceFor
メソッドを使用することもできますが、あらかじめ価格を設定し、invoicePrice
メソッドやtabPrice
メソッドの使用を推奨します。それにより、商品ごとの売上に関するより良い分析・データへ、Stripeのダッシュボードによりアクセスできます。Although
the
invoiceFor
method is
available
for you to
use, it is
recommended
that you use
the
invoicePrice
and
tabPrice
methods with
pre-defined
prices. By
doing so,
you will
have access
to better
analytics
and data
within your
Stripe
dashboard
regarding
your sales
on a
per-product
basis.
Warning!
invoice
、invoicePrice
、invoiceFor
メソッドは、課金に失敗した場合に再試行する、Stripeインボイスを作成します。請求の失敗時に再試行したくない場合は、最初の請求が失敗した後に、Stripe APIを使用し、そのインボイスを閉じる必要があります。[!WARNING]
Theinvoice
,invoicePrice
, andinvoiceFor
methods 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.
支払いインテントの作成Creating Payment Intents
Billableモデルのインスタンスで、pay
メソッドを呼び出すと、新しいStripe支払いインテントを作成できます。このメソッドを呼び出すと、Laravel\Cashier\Payment
インスタンスでラップした支払いインテントが作成されます。You
can create a
new Stripe
payment
intent by
invoking the
pay
method on a
billable
model
instance.
Calling this
method will
create a
payment
intent that
is wrapped
in a
Laravel\Cashier\Payment
instance:
use Illuminate\Http\Request;
Route::post('/pay', function (Request $request) {
$payment = $request->user()->pay(
$request->get('amount')
);
return $payment->client_secret;
});
支払いインテントを作成したら、アプリケーションのフロントエンドへクライアントシークレットを返し、ユーザーにブラウザで支払いを完了してもらえます。Stripe支払いインテントを使った支払いフロー全体の構築は、Stripeのドキュメントを参照してください。After creating the payment intent, you can return the client secret to your application's frontend so that the user can complete the payment in their browser. To read more about building entire payment flows using Stripe payment intents, please consult the Stripe documentation[https://stripe.com/docs/payments/accept-a-payment?platform=web].
pay
メソッドを使用すると、Stripeのダッシュボードで有効に設定されているデフォルト支払い方法を顧客が利用できるようになります。もしくは、特定の支払い方法のみを許可したい場合は、payWith
メソッドを使用できます。When
using the
pay
method, the
default
payment
methods that
are enabled
within your
Stripe
dashboard
will be
available to
the
customer.
Alternatively,
if you only
want to
allow for
some
specific
payment
methods to
be used, you
may use the
payWith
method:
use Illuminate\Http\Request;
Route::post('/pay', function (Request $request) {
$payment = $request->user()->payWith(
$request->get('amount'), ['card', 'bancontact']
);
return $payment->client_secret;
});
Warning!
pay
とpayWith
メソッドは、アプリケーションで使用する通貨の最小単位で支払額を引数に取ります。例えば、顧客が米ドルで支払う場合、金額はペニーで指定する必要があります。[!WARNING]
Thepay
andpayWith
methods accept the payment amount in the lowest denominator of the currency used by your application. For example, if customers are paying in United States Dollars, amounts should be specified in pennies.
支払の返金Refunding Charges
Stripeの料金を払い戻す必要がある場合は、refund
メソッドを使用します。このメソッドは、最初の引数にStripe支払いインテントIDを取ります。If
you need to
refund a
Stripe
charge, you
may use the
refund
method. This
method
accepts the
Stripe
payment
intent
ID[#payment-methods-for-single-charges]
as its first
argument:
$payment = $user->charge(100, $paymentMethodId);
$user->refund($payment->id);
インボイスInvoices
インボイスの取得Retrieving Invoices
invoices
メソッドを使用して、Billableなモデルのインボイスの配列を簡単に取得できます。invoices
メソッドはLaravel\Cashier\Invoice
インスタンスのコレクションを返します。You
may easily
retrieve an
array of a
billable
model's
invoices
using the
invoices
method. The
invoices
method
returns a
collection
of
Laravel\Cashier\Invoice
instances:
$invoices = $user->invoices();
結果に保留中のインボイスを含めたい場合は、invoicesInclusivePending
メソッドを使用します。If
you would
like to
include
pending
invoices in
the results,
you may use
the
invoicesIncludingPending
method:
$invoices = $user->invoicesIncludingPending();
findInvoice
メソッドを使用して、IDで特定のインボイスを取得できます。You
may use the
findInvoice
method to
retrieve a
specific
invoice by
its
ID:
$invoice = $user->findInvoice($invoiceId);
インボイス情報の表示Displaying Invoice Information
ある顧客のインボイスを一覧表示する場合、インボイスのメソッドを使用し関連するインボイス情報を表示すると思います。たとえば、テーブル中の全インボイスをリストする場合、ユーザーがどれでも簡単にダウンロードできるようにしたいことでしょう。When listing the invoices for the customer, you may use the invoice's 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>
将来のインボイスUpcoming Invoices
顧客の将来のインボイスを取得するには、upcomingInvoice
メソッドを使います。To
retrieve the
upcoming
invoice for
a customer,
you may use
the
upcomingInvoice
method:
$invoice = $user->upcomingInvoice();
同様に、顧客が複数のサブスクリプションを持っている場合、指定するサブスクリプションの次期インボイスを取得することもできます。Similarly, if the customer has multiple subscriptions, you can also retrieve the upcoming invoice for a specific subscription:
$invoice = $user->subscription('default')->upcomingInvoice();
サブスクリプションインボイスのプレビューPreviewing Subscription Invoices
previewInvoice
メソッドを使うと、価格変更をする前にインボイスをプレビューできます。これにより、特定の価格変更を行う場合、顧客のインボイスがどのようなものになるか確認できます。Using
the
previewInvoice
method, you
can preview
an invoice
before
making price
changes.
This will
allow you to
determine
what your
customer's
invoice will
look like
when a given
price change
is
made:
$invoice = $user->subscription('default')->previewInvoice('price_yearly');
新しい複数価格のインボイスをプレビューするには、価格の配列をpreviewInvoice
メソッドへ渡します。You
may pass an
array of
prices to
the
previewInvoice
method in
order to
preview
invoices
with
multiple new
prices:
$invoice = $user->subscription('default')->previewInvoice(['price_yearly', 'price_metered']);
インボイスPDFの生成Generating Invoice PDFs
インボイスPDFを生成する前にComposerを使い、CashierのデフォルトインボイスレンダラであるDompdfライブラリをインストールする必要があります。Before generating invoice PDFs, you should use Composer to install the Dompdf library, which is the default invoice renderer for Cashier:
composer require dompdf/dompdf
ルートまたはコントローラ内から、downloadInvoice
メソッドを使用して、特定のインボイスのPDFダウンロードを生成できます。このメソッドは、インボイスのダウンロードに必要なHTTP応答を適切かつ自動的に生成します。From
within a
route or
controller,
you may use
the
downloadInvoice
method to
generate a
PDF download
of a given
invoice.
This method
will
automatically
generate the
proper HTTP
response
needed to
download the
invoice:
use Illuminate\Http\Request;
Route::get('/user/invoice/{invoice}', function (Request $request, string $invoiceId) {
return $request->user()->downloadInvoice($invoiceId);
});
インボイスのすべてのデータはデフォルトで、Stripeに保存されている顧客と請求書のデータから作成します。ファイル名はapp.name
設定値に基づきます。しかし、downloadInvoice
メソッドの第2引数に配列を指定することで、データの一部をカスタマイズ可能です。この配列で、会社や製品の詳細などの情報がカスタマイズできます。By
default, all
data on the
invoice is
derived from
the customer
and invoice
data stored
in Stripe.
The filename
is based on
your
app.name
config
value.
However, you
can
customize
some of this
data by
providing an
array as the
second
argument to
the
downloadInvoice
method. This
array allows
you to
customize
information
such as your
company and
product
details:
return $request->user()->downloadInvoice($invoiceId, [
'vendor' => 'Your Company',
'product' => 'Your Product',
'street' => 'Main Str. 1',
'location' => '2000 Antwerp, Belgium',
'phone' => ' 32 499 00 00 00',
'email' => 'info@example.com',
'url' => 'https://example.com',
'vendorVat' => 'BE123456789',
]);
downloadInvoice
メソッドの第3引数でカスタムファイル名の指定もできます。このファイル名には自動的に.pdf
というサフィックスが付きます。The
downloadInvoice
method also
allows for a
custom
filename via
its third
argument.
This
filename
will
automatically
be suffixed
with
.pdf
:
return $request->user()->downloadInvoice($invoiceId, [], 'my-invoice');
カスタム・インボイス・レンダラCustom Invoice Renderer
また、Cashierはカスタムインボイスレンダラを使用可能です。デフォルトでCashierは、dompdf
PHPライブラリを利用し請求書を生成する、DompdfInvoiceRenderer
の実装を使用します。しかし、Laravel\Cashier\Contracts\InvoiceRenderer
インターフェイスを実装することにより、任意のレンダラを使用できます。例えば、サードパーティのPDFレンダリングサービスへのAPIコールを使用し、請求書PDFをレンダリングするとしましょう。Cashier
also makes
it possible
to use a
custom
invoice
renderer. By
default,
Cashier uses
the
DompdfInvoiceRenderer
implementation,
which
utilizes the
dompdf[https://github.com/dompdf/dompdf]
PHP library
to generate
Cashier's
invoices.
However, you
may use any
renderer you
wish by
implementing
the
Laravel\Cashier\Contracts\InvoiceRenderer
interface.
For example,
you may wish
to render an
invoice PDF
using an API
call to a
third-party
PDF
rendering
service:
use Illuminate\Support\Facades\Http;
use Laravel\Cashier\Contracts\InvoiceRenderer;
use Laravel\Cashier\Invoice;
class ApiInvoiceRenderer implements InvoiceRenderer
{
/**
* 与えられた請求書をレンダリングし、素のPDFバイトを返す
*/
public function render(Invoice $invoice, array $data = [], array $options = []): string
{
$html = $invoice->view($data)->render();
return Http::get('https://example.com/html-to-pdf', ['html' => $html])->get()->body();
}
}
請求書レンダラ契約を実装したら、アプリケーションの
config/cashier.php
設定ファイルにあるcashier.invoices.renderer
設定値を更新する必要があります。この設定値には、カスタムレンダラ実装のクラス名を設定します。Once
you have
implemented
the invoice
renderer
contract,
you should
update the
cashier.invoices.renderer
configuration
value in
your
application's
config/cashier.php
configuration
file. This
configuration
value should
be set to
the class
name of your
custom
renderer
implementation.
チェックアウトCheckout
Cashier Stripeは、Stripe Checkoutもサポートしています。Stripe Checkoutは、チェックアウトページを事前に構築しホストするという、支払いを受け入れるためカスタムページを実装する手間を省きます。Cashier Stripe also provides support for Stripe Checkout[https://stripe.com/payments/checkout]. Stripe Checkout takes the pain out of implementing custom pages to accept payments by providing a pre-built, hosted payment page.
以下のドキュメントで、Stripe Checkoutをどのように利用開始するのかに関する情報を説明していきます。Stripe Checkoutの詳細は、StrepeのCheckoutに関するドキュメントを確認する必要があるでしょうThe following documentation contains information on how to get started using Stripe Checkout with Cashier. To learn more about Stripe Checkout, you should also consider reviewing Stripe's own documentation on Checkout[https://stripe.com/docs/payments/checkout].
商品の支払いProduct Checkouts
Billableなモデル上のcheckout
メソッドを使用して、Stripeダッシュボード内に作成した既存の製品への課金を実行できます。checkout
メソッドは新しいStripeチェックアウトセッションを開始します。デフォルトで、Stripe価格IDを渡す必要があります。You
may perform
a checkout
for an
existing
product that
has been
created
within your
Stripe
dashboard
using the
checkout
method on a
billable
model. The
checkout
method will
initiate a
new Stripe
Checkout
session. By
default,
you're
required to
pass a
Stripe Price
ID:
use Illuminate\Http\Request;
Route::get('/product-checkout', function (Request $request) {
return $request->user()->checkout('price_tshirt');
});
必要に応じて、製品数量を指定することもできます。If needed, you may also specify a product quantity:
use Illuminate\Http\Request;
Route::get('/product-checkout', function (Request $request) {
return $request->user()->checkout(['price_tshirt' => 15]);
});
顧客がこのルートを訪れると、Stripeのチェックアウトページにリダイレクトされます。デフォルトでは、ユーザーが購入を正常に完了した場合、または購入をキャンセルすると、Home
ルートへリダイレクトされますが、success_url
とcancel_url
オプションを使い、カスタムコールバックURLを指定できます。When
a customer
visits this
route they
will be
redirected
to Stripe's
Checkout
page. By
default,
when a user
successfully
completes or
cancels a
purchase
they will be
redirected
to your
home
route
location,
but you may
specify
custom
callback
URLs using
the
success_url
and
cancel_url
options:
use Illuminate\Http\Request;
Route::get('/product-checkout', function (Request $request) {
return $request->user()->checkout(['price_tshirt' => 1], [
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
success_url
チェックアウトオプションを定義するときに、指定したURLを呼び出す際にチェックアウトセッションIDをクエリ文字列のパラメータとして追加するように、Stripeへ指示できます。それには、リテラル文字列
{CHECKOUT_SESSION_ID}
を
success_url
のクエリ文字列に追加します。Stripeはこのプレースホルダーを実際のチェックアウトセッションIDに置き換えます。When
defining
your
success_url
checkout
option, you
may instruct
Stripe to
add the
checkout
session ID
as a query
string
parameter
when
invoking
your URL. To
do so, add
the literal
string
{CHECKOUT_SESSION_ID}
to your
success_url
query
string.
Stripe will
replace this
placeholder
with the
actual
checkout
session
ID:
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use Stripe\Customer;
Route::get('/product-checkout', function (Request $request) {
return $request->user()->checkout(['price_tshirt' => 1], [
'success_url' => route('checkout-success').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('checkout-cancel'),
]);
});
Route::get('/checkout-success', function (Request $request) {
$checkoutSession = $request->user()->stripe()->checkout->sessions->retrieve($request->get('session_id'));
return view('checkout.success', ['checkoutSession' => $checkoutSession]);
})->name('checkout-success');
プロモーションコードPromotion Codes
Stripe
Checkoutはデフォルトで、ユーザーが商品に使用できるプロモーションコードを許可していません。幸いなことに、チェックアウトページでこれを有効にする簡単な方法があります。有効にするには、allowPromotionCodes
メソッドを呼び出します。By
default,
Stripe
Checkout
does not
allow
user
redeemable
promotion
codes[https://stripe.com/docs/billing/subscriptions/discounts/codes].
Luckily,
there's an
easy way to
enable these
for your
Checkout
page. To do
so, you may
invoke the
allowPromotionCodes
method:
use Illuminate\Http\Request;
Route::get('/product-checkout', function (Request $request) {
return $request->user()
->allowPromotionCodes()
->checkout('price_tshirt');
});
一回限りの支払いSingle Charge Checkouts
ストライプダッシュボードで作成していない、アドホックな商品をシンプルに課金することもできます。これには、BillableなモデルでcheckoutCharge
メソッドを使用し、課金可能な料金、製品名、およびオプションの数量を渡たします。顧客がこのルートを訪れると、Stripeのチェックアウトページへリダイレクトされます。You
can also
perform a
simple
charge for
an ad-hoc
product that
has not been
created in
your Stripe
dashboard.
To do so you
may use the
checkoutCharge
method on a
billable
model and
pass it a
chargeable
amount, a
product
name, and an
optional
quantity.
When a
customer
visits this
route they
will be
redirected
to Stripe's
Checkout
page:
use Illuminate\Http\Request;
Route::get('/charge-checkout', function (Request $request) {
return $request->user()->checkoutCharge(1200, 'T-Shirt', 5);
});
Warning!
checkoutCharge
メソッドを使用すると、Stripeは常にStripeダッシュボードに新しい製品と価格を作成します。そのため、代わりにStripeダッシュボードで事前に商品を作成し、checkout
メソッドを使用することを推奨します。[!WARNING]
When using thecheckoutCharge
method, Stripe will always create a new product and price in your Stripe dashboard. Therefore, we recommend that you create the products up front in your Stripe dashboard and use thecheckout
method instead.
サブスクリプションの支払いSubscription Checkouts
Warning! Stripe Checkoutのサブスクリプションを使用するには、Stripeダッシュボードで
customer.subscription.created
Webフックを有効にする必要があります。このWebフックは、データベースにサブスクリプションレコードを作成し、すべてのサブスクリプション関連アイテムを保存します。[!WARNING]
Using Stripe Checkout for subscriptions requires you to enable thecustomer.subscription.created
webhook in your Stripe dashboard. This webhook will create the subscription record in your database and store all of the relevant subscription items.
サブスクリプションを開始するため、Stripe
Checkoutを使用することもできます。Cashierのサブスクリプションビルダメソッドを使用してサブスクリプションを定義した後に、checkout
メソッドを呼び出せます。顧客がこのルートを訪れると、Stripeのチェックアウトページへリダイレクトされます。You
may also use
Stripe
Checkout to
initiate
subscriptions.
After
defining
your
subscription
with
Cashier's
subscription
builder
methods, you
may call the
checkout
method.
When a
customer
visits this
route they
will be
redirected
to Stripe's
Checkout
page:
use Illuminate\Http\Request;
Route::get('/subscription-checkout', function (Request $request) {
return $request->user()
->newSubscription('default', 'price_monthly')
->checkout();
});
製品のチェックアウトと同様に、成功およびキャンセルのURLをカスタマイズできます。Just as with product checkouts, you may customize the success and cancellation URLs:
use Illuminate\Http\Request;
Route::get('/subscription-checkout', function (Request $request) {
return $request->user()
->newSubscription('default', 'price_monthly')
->checkout([
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
もちろん、サブスクリプションチェックアウトのプロモーションコードを有効にすることもできます。Of course, you can also enable promotion codes for subscription checkouts:
use Illuminate\Http\Request;
Route::get('/subscription-checkout', function (Request $request) {
return $request->user()
->newSubscription('default', 'price_monthly')
->allowPromotionCodes()
->checkout();
});
Warning! 残念ながらStripe Checkoutはサブスクリプションを開始するとき、すべてのサブスクリプション請求オプションをサポートしていません。サブスクリプションビルダの
anchorBillingCycleOn
メソッドの使用や、比例配分の動作の設定、支払い動作の設定は、Stripeチェックアウトセッション中は全く効果がありません。どのパラメータが利用可能であるかを確認するには、Stripe CheckoutセッションAPIのドキュメントを参照してください。[!WARNING]
Unfortunately Stripe Checkout does not support all subscription billing options when starting subscriptions. Using theanchorBillingCycleOn
method on the subscription builder, setting proration behavior, or setting payment behavior will not have any effect during Stripe Checkout sessions. Please consult the Stripe Checkout Session API documentation[https://stripe.com/docs/api/checkout/sessions/create] to review which parameters are available.
Stripeの支払と無料トライアル期間Stripe Checkout and Trial Periods
もちろん、Stripe Checkoutを使用して購サブスクリプションを作成するときにも、無料トライアル期間の完了時間を定義できます。Of course, you can define a trial period when building a subscription that will be completed using Stripe Checkout:
$checkout = Auth::user()->newSubscription('default', 'price_monthly')
->trialDays(3)
->checkout();
ただし、無料トライアル期間は最低48時間でなければならず、これはStripe Checkoutでサポートされている試行時間の最短時間です。However, the trial period must be at least 48 hours, which is the minimum amount of trial time supported by Stripe Checkout.
Subscriptions and WebhooksSubscriptions and Webhooks
StripeとCashierはWebフックを使いサブスクリプションの状態を更新することを覚えておいてください。そのため、顧客が支払い情報を入力した後にアプリケーションへ戻った時点で、サブスクリプションが有効になっていない可能性があります。このシナリオに対応するため、ユーザーに支払いやサブスクリプションが保留中であることを知らせるメッセージの表示を推奨します。Remember, Stripe and Cashier update subscription statuses via webhooks, so there's a possibility a subscription might not yet be active when the customer returns to the application after entering their payment information. To handle this scenario, you may wish to display a message informing the user that their payment or subscription is pending.
課税IDの収集Collecting Tax IDs
Checkoutは、顧客の課税IDの収集もサポートしています。チェックアウトセッションでこれを有効にするには、セッションを作成するときにcollectTaxIds
メソッドを呼び出します。Checkout
also
supports
collecting a
customer's
Tax ID. To
enable this
on a
checkout
session,
invoke the
collectTaxIds
method when
creating the
session:
$checkout = $user->collectTaxIds()->checkout('price_tshirt');
このメソッドを呼び出すと、顧客が会社として購入するかを示すための新しいチェックボックスが利用可能になります。会社として購入する場合は、課税IDを入力してもらいます。When this method is invoked, a new checkbox will be available to the customer that allows them to indicate if they're purchasing as a company. If so, they will have the opportunity to provide their Tax ID number.
自動徴税を設定済みであれば、この機能は自動的に有効になり、
Warning! アプリケーションのサービスプロバイダでcollectTaxIds
メソッドを呼び出す必要はありません。[!WARNING]
If you have already configured automatic tax collection[#tax-configuration] in your application's service provider then this feature will be enabled automatically and there is no need to invoke thecollectTaxIds
method.
ゲストの支払いGuest Checkouts
Checkout::guest
メソッドを使用すると、アプリケーションの「アカウント」を持っていないゲストに対して、チェックアウトセッションを開始できます。Using
the
Checkout::guest
method, you
may initiate
checkout
sessions for
guests of
your
application
that do not
have an
"account":
use Illuminate\Http\Request;
use Laravel\Cashier\Checkout;
Route::get('/product-checkout', function (Request $request) {
return Checkout::guest()->create('price_tshirt', [
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
既存のユーザーのチェックアウトセッションを作成するときと同様に、Laravel\Cashier\CheckoutBuilder
インスタンスで利用可能な拡張メソッドを利用して、ゲストのチェックアウトセッションをカスタマイズできます。Similarly
to when
creating
checkout
sessions for
existing
users, you
may utilize
additional
methods
available on
the
Laravel\Cashier\CheckoutBuilder
instance to
customize
the guest
checkout
session:
use Illuminate\Http\Request;
use Laravel\Cashier\Checkout;
Route::get('/product-checkout', function (Request $request) {
return Checkout::guest()
->withPromotionCode('promo-code')
->create('price_tshirt', [
'success_url' => route('your-success-route'),
'cancel_url' => route('your-cancel-route'),
]);
});
ゲストのチェックアウトが完了すると、Stripeはcheckout.session.completed
Webフックイベントをディスパッチします。ですから、このイベントを確実にアプリケーションへ送信するため、StripeのWebフックを設定してください。StripeのダッシュボードでWebフックを有効にしたら、Cashierを使ってwebフックを処理できます。Webフックのペイロードに含まれるオブジェクトはcheckout
オブジェクトであり、顧客の注文を処理するため確認できます。After
a guest
checkout has
been
completed,
Stripe can
dispatch a
checkout.session.completed
webhook
event, so
make sure to
configure
your
Stripe
webhook[https://dashboard.stripe.com/webhooks]
to actually
send this
event to
your
application.
Once the
webhook has
been enabled
within the
Stripe
dashboard,
you may
handle
the
webhook
with
Cashier[#handling-stripe-webhooks].
The object
contained in
the webhook
payload will
be a
checkout
object[https://stripe.com/docs/api/checkout/sessions/object]
that you may
inspect in
order to
fulfill your
customer's
order.
支払い失敗の処理Handling Failed Payments
サブスクリプションまたは1回限りの支払いが失敗する場合もあります。これが起きると、Cashierはこの発生を通知するLaravel\Cashier\Exceptions\IncompletePayment
例外を投げます。この例外をキャッチした後に続行する方法は、2つの選択肢があります。Sometimes,
payments for
subscriptions
or single
charges can
fail. When
this
happens,
Cashier will
throw an
Laravel\Cashier\Exceptions\IncompletePayment
exception
that informs
you that
this
happened.
After
catching
this
exception,
you have two
options on
how to
proceed.
1つ目はCashierが用意している専用の支払い確認ページに顧客をリダイレクトすることです。このページは、Cashierのサービスプロバイダを介して登録済みの名前付きルートがすでに割り振られています。したがって、IncompletePayment
例外をキャッチして、ユーザーを支払い確認ページにリダイレクトできます。First,
you could
redirect
your
customer to
the
dedicated
payment
confirmation
page which
is included
with
Cashier.
This page
already has
an
associated
named route
that is
registered
via
Cashier's
service
provider.
So, you may
catch the
IncompletePayment
exception
and redirect
the user to
the payment
confirmation
page:
use Laravel\Cashier\Exceptions\IncompletePayment;
try {
$subscription = $user->newSubscription('default', 'price_monthly')
->create($paymentMethod);
} catch (IncompletePayment $exception) {
return redirect()->route(
'cashier.payment',
[$exception->payment->id, 'redirect' => route('home')]
);
}
支払い確認ページで、顧客はクレジットカード情報を再度入力し、「3Dセキュア」確認などのStripeに必要な追加のアクションを実行するように求められます。支払いを確認すると、ユーザーは上記のredirect
パラメータで指定したURLへリダイレクトされます。リダイレクト時に、message
(文字列)およびsuccess
(整数)クエリ文字列変数をURLへ追加します。支払い確認ページでは現在、以下の決済方法に対応しています。On
the payment
confirmation
page, the
customer
will be
prompted to
enter their
credit card
information
again and
perform any
additional
actions
required by
Stripe, such
as "3D
Secure"
confirmation.
After
confirming
their
payment, the
user will be
redirected
to the URL
provided by
the
redirect
parameter
specified
above. Upon
redirection,
message
(string) and
success
(integer)
query string
variables
will be
added to the
URL. The
payment page
currently
supports the
following
payment
method
types:
- クレジットカードCredit Cards
- AlipayAlipay
- BancontactBancontact
- BECS Direct DebitBECS Direct Debit
- EPSEPS
- GiropayGiropay
- iDEALiDEAL
- SEPA Direct DebitSEPA Direct Debit
もう一つの方法として、Stripeに支払い確認の処理を任せることもできます。この場合、支払い確認ページにリダイレクトする代わりに、StripeダッシュボードでStripeの自動請求メールを設定してください。ただし、IncompletePayment
例外がキャッチされた場合でも、支払い確認の手順を記載したメールがユーザーへ届くよう、通知する必要があります。Alternatively,
you
could
allow
Stripe
to
handle
the
payment
confirmation
for
you.
In
this
case,
instead
of
redirecting
to
the
payment
confirmation
page,
you
may
setup
Stripe's
automatic
billing
emails[https://dashboard.stripe.com/account/billing/automatic]
in
your
Stripe
dashboard.
However,
if
an
IncompletePayment
exception
is
caught,
you
should
still
inform
the
user
they
will
receive
an
email
with
further
payment
confirmation
instructions.
Billable
トレイトを使用するモデルのcharge
、invoiceFor
、invoice
メソッドでは、支払いの例外が投げられる場合があります。サブスクリプションを操作する場合では、SubscriptionBuilder
のcreate
メソッド、およびSubscription
とSubscriptionItem
モデルのincrementAndInvoice
メソッドとswapAndInvoice
メソッドは、不完全な支払い例外を投げる可能性があります。Payment
exceptions
may
be
thrown
for
the
following
methods:
charge
,
invoiceFor
,
and
invoice
on
models
using
the
Billable
trait.
When
interacting
with
subscriptions,
the
create
method
on
the
SubscriptionBuilder
,
and
the
incrementAndInvoice
and
swapAndInvoice
methods
on
the
Subscription
and
SubscriptionItem
models
may
throw
incomplete
payment
exceptions.
既存のサブスクリプションの支払いが不完全であるかどうかの判断は、BillableモデルまたはサブスクリプションインスタンスでhasIncompletePayment
メソッドを使用して行えます。Determining
if
an
existing
subscription
has
an
incomplete
payment
may
be
accomplished
using
the
hasIncompletePayment
method
on
the
billable
model
or
a
subscription
instance:
if ($user->hasIncompletePayment('default')) {
// ...
}
if ($user->subscription('default')->hasIncompletePayment()) {
// ...
}
例外インスタンスのpayment
プロパティを調べると、不完全な支払いの具体的なステータスを調べられます。You
can
derive
the
specific
status
of
an
incomplete
payment
by
inspecting
the
payment
property
on
the
exception
instance:
use Laravel\Cashier\Exceptions\IncompletePayment;
try {
$user->charge(1000, 'pm_card_threeDSecure2Required');
} catch (IncompletePayment $exception) {
// 支払いインテント状態の取得
$exception->payment->status;
// 特定の条件の確認
if ($exception->payment->requiresPaymentMethod()) {
// ...
} elseif ($exception->payment->requiresConfirmation()) {
// ...
}
}
支払いの確認Confirming Payments
いくつかの支払い方法は、支払いを確認するための追加データを必要とします。例えば、SEPA(単一ユーロ決済圏)の支払いメソッドは、支払いプロセス中に追加で「委任状(mandate)」データが必要です。withPaymentConfirmationOptions
メソッドを使用して、このデータをCashierへ指定できます:Some
payment
methods
require
additional
data
in
order
to
confirm
payments.
For
example,
SEPA
payment
methods
require
additional
"mandate"
data
during
the
payment
process.
You
may
provide
this
data
to
Cashier
using
the
withPaymentConfirmationOptions
method:
$subscription->withPaymentConfirmationOptions([
'mandate_data' => '...',
])->swap('price_xxx');
Stripe APドキュメントを参照すれば、支払い確認を行うときに受取れる、すべてのオプションを確認できます。You may consult the Stripe API documentation[https://stripe.com/docs/api/payment_intents/confirm] to review all of the options accepted when confirming payments.
強力な顧客認証(SCA)Strong Customer Authentication
あなたのビジネスがヨーロッパに拠点を置いているか、顧客がヨーロッパにいる場合は、EUの強力な顧客認証(SCA)法令を遵守する必要があります。これらの法令は、支払い詐欺を防ぐために2019年9月に欧州連合によって課されました。幸いにして、StripeとCashierは、SCA準拠のアプリケーションを構築する準備ができています。If your business or one of your customers is based in Europe you will need to abide by the EU's Strong Customer Authentication (SCA) regulations. These regulations were imposed in September 2019 by the European Union to prevent payment fraud. Luckily, Stripe and Cashier are prepared for building SCA compliant applications.
PSD2とSCAに関するStripeのガイドと新しいSCA APIに関するドキュメントを確認してください。[!WARNING]
Warning! 使用開始前に、
Before getting started, review Stripe's guide on PSD2 and SCA[https://stripe.com/guides/strong-customer-authentication] as well as their documentation on the new SCA APIs[https://stripe.com/docs/strong-customer-authentication].
追加の確認が必要な支払いPayments Requiring Additional Confirmation
SCA法令では支払いを確認し処理するため、追加の検証が頻繁に必要になります。これが起きると、Cashierは追加の検証が必要であることを通知するLaravel\Cashier\Exceptions\IncompletePayment
例外を投げます。こうした例外の処理方法の詳細は、失敗した支払いの処理のドキュメントを参照してください。SCA
regulations
often
require
extra
verification
in
order
to
confirm
and
process
a
payment.
When
this
happens,
Cashier
will
throw
a
Laravel\Cashier\Exceptions\IncompletePayment
exception
that
informs
you
that
extra
verification
is
needed.
More
information
on
how
to
handle
these
exceptions
be
found
can
be
found
in
the
documentation
on
handling
failed
payments[#handling-failed-payments].
StripeとCashierが提供する支払い確認画面は、特定の銀行またはカード発行者の支払いフローに合わせて調整することができ、追加のカード確認、一時的な少額の支払い、個別のデバイス認証、その他の形式の検証を含むことができます。Payment confirmation screens presented by Stripe or Cashier may be tailored to a specific bank or card issuer's payment flow and can include additional card confirmation, a temporary small charge, separate device authentication, or other forms of verification.
不完了と期限超過の状態Incomplete and Past Due State
支払いに追加の確認が必要な場合、サブスクリプションはstripe_status
データベースカラムが、incomplete
かpast_due
状態のままになることで示されます。Cashierは支払いの確認が完了し、アプリケーションがWebフックを介してStripeから完了の通知を受けるととすぐに、顧客のサブスクリプションを自動的にアクティブ化します。When
a
payment
needs
additional
confirmation,
the
subscription
will
remain
in
an
incomplete
or
past_due
state
as
indicated
by
its
stripe_status
database
column.
Cashier
will
automatically
activate
the
customer's
subscription
as
soon
as
payment
confirmation
is
complete
and
your
application
is
notified
by
Stripe
via
webhook
of
its
completion.
incomplete
およびpast_due
状態の詳細については、これらの状態に関する追加のドキュメントを参照してください。For
more
information
on
incomplete
and
past_due
states,
please
refer
to
our
additional
documentation
on
these
states[#incomplete-and-past-due-status].
オフセッション支払い通知Off-Session Payment Notifications
SCAの法令では、サブスクリプションがアクティブな場合でも、顧客は支払いの詳細を時々確認することを求めているため、Cashierはオフセッションでの支払い確認が必要なときに顧客に通知を送れるようになっています。たとえば、これはサブスクリプションの更新時に発生する可能性があります。Cashierの支払い通知は、CASHIER_PAYMENT_NOTIFICATION
環境変数を通知クラスに設定することで有効にできます。デフォルトでは、この通知は無効になっています。もちろん、Cashierにはこの目的で使用できる通知クラスが含まれていますが、必要に応じて独自の通知クラスを自由に提供できます。Since
SCA
regulations
require
customers
to
occasionally
verify
their
payment
details
even
while
their
subscription
is
active,
Cashier
can
send
a
notification
to
the
customer
when
off-session
payment
confirmation
is
required.
For
example,
this
may
occur
when
a
subscription
is
renewing.
Cashier's
payment
notification
can
be
enabled
by
setting
the
CASHIER_PAYMENT_NOTIFICATION
environment
variable
to
a
notification
class.
By
default,
this
notification
is
disabled.
Of
course,
Cashier
includes
a
notification
class
you
may
use
for
this
purpose,
but
you
are
free
to
provide
your
own
notification
class
if
desired:
CASHIER_PAYMENT_NOTIFICATION=Laravel\Cashier\Notifications\ConfirmPayment
オフセッションでの支払い確認通知が確実に配信されるようにするため、アプリケーションでStripe
Webフックが設定されていることと、Stripeダッシュボードでinvoice.payment_action_required
webhookが有効になっていることを確認してください。さらに、Billable
モデルでLaravelのIlluminate\Notifications\Notifiable
トレイトを使用していることも確認する必要があります。To
ensure
that
off-session
payment
confirmation
notifications
are
delivered,
verify
that
Stripe
webhooks
are
configured[#handling-stripe-webhooks]
for
your
application
and
the
invoice.payment_action_required
webhook
is
enabled
in
your
Stripe
dashboard.
In
addition,
your
Billable
model
should
also
use
Laravel's
Illuminate\Notifications\Notifiable
trait.
[!WARNING]
Warning! 顧客が追加の確認を必要とする支払いを手作業で行う場合でも、通知は送信されます。残念ながら、支払いが手作業なのか「オフセッション」で行われたかをStripeが知る方法はありません。ただし、顧客が支払いを確認した後に支払いページへアクセスすると、「支払いが成功しました(Payment Successful)」というメッセージが表示されます。謝って顧客へ同じ支払いを2回確認させ、2回目の請求を行ってしまうことはありません。
Notifications will be sent even when customers are manually making a payment that requires additional confirmation. Unfortunately, there is no way for Stripe to know that the payment was done manually or "off-session". But, a customer will simply see a "Payment Successful" message if they visit the payment page after already confirming their payment. The customer will not be allowed to accidentally confirm the same payment twice and incur an accidental second charge.
Stripe SDKStripe SDK
Cashierのオブジェクトの多くは、StripeSDKオブジェクトのラッパーです。Stripeオブジェクトを直接操作したい場合は、asStripe
メソッドを使用してオブジェクトを簡単に取得できます。Many
of
Cashier's
objects
are
wrappers
around
Stripe
SDK
objects.
If
you
would
like
to
interact
with
the
Stripe
objects
directly,
you
may
conveniently
retrieve
them
using
the
asStripe
method:
$stripeSubscription = $subscription->asStripeSubscription();
$stripeSubscription->application_fee_percent = 5;
$stripeSubscription->save();
updateStripeSubscription
メソッドを使用して、Stripeサブスクリプションを直接更新することもできます。You
may
also
use
the
updateStripeSubscription
method
to
update
a
Stripe
subscription
directly:
$subscription->updateStripeSubscription(['application_fee_percent' => 5]);
Stripe\StripeClient
のクライアントを直接使用したい場合は、Cashier
クラスのstripe
メソッドを呼び出せます。例えば、このメソッドを使ってStripeClient
のインスタンスにアクセスし、Stripeアカウントから価格のリストを取得できます。You
may
invoke
the
stripe
method
on
the
Cashier
class
if
you
would
like
to
use
the
Stripe\StripeClient
client
directly.
For
example,
you
could
use
this
method
to
access
the
StripeClient
instance
and
retrieve
a
list
of
prices
from
your
Stripe
account:
use Laravel\Cashier\Cashier;
$prices = Cashier::stripe()->prices->all();
テストTesting
Cashierを使用するアプリケーションをテストする場合、Stripe APIへの実際のHTTPリクエストをモックすることができます。しかし、そのためにはCashier自身の動作を部分的に再実装する必要があります。そのため、実際のStripe APIを利用し、テストすることをお勧めします。その分テスト速度が遅くなりますが、アプリケーションが期待通りに動作しているかどうかをより確実に確認できます。また、動作が遅いテストは、自身のPest/PHPUnitテストグループ内で実行できます。When testing an application that uses Cashier, you may mock the actual HTTP requests to the Stripe API; however, this requires you to partially re-implement Cashier's own behavior. Therefore, we recommend allowing your tests to hit the actual Stripe API. While this is slower, it provides more confidence that your application is working as expected and any slow tests may be placed within their own Pest / PHPUnit testing group.
テストするときは、Cashier自体には優れたテストスイートを既に持っていることを忘れないでください。したがって、基本的なCashierの動作すべてではなく、独自のアプリケーションのサブスクリプションと支払いフローのテストにのみ焦点を当てる必要があります。When testing, remember that Cashier itself already has a great test suite, so you should only focus on testing the subscription and payment flow of your own application and not every underlying Cashier behavior.
テスト開始するには、Stripeシークレットのテストバージョンをphpunit.xml
ファイルに追加します。To
get
started,
add
the
testing
version
of
your
Stripe
secret
to
your
phpunit.xml
file:
<env name="STRIPE_SECRET" value="sk_test_<your-key>"/>
これで、テスト中にCashierとやり取りするたびに、実際のAPIリクエストがStripeテスト環境に送信されます。便宜上、Stripeテストアカウントに、テスト中に使用できるサブスクリプション/価格を事前に入力する必要があります。Now, whenever you interact with Cashier while testing, it will send actual API requests to your Stripe testing environment. For convenience, you should pre-fill your Stripe testing account with subscriptions / prices that you may use during testing.
カード番号とトークンのテストを使用できます。[!NOTE]
Note: クレジットカードの拒否や失敗など、さまざまな請求シナリオをテストするため、Stripeが提供しているさまざまな
In order to test a variety of billing scenarios, such as credit card denials and failures, you may use the vast range of testing card numbers and tokens[https://stripe.com/docs/testing] provided by Stripe.