Readouble

Laravel 9.x Laravel Cashier (Stripe)

イントロダクション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 Warning! 重大な変更を防ぐために、Cashierは固定のStripe APIバージョンを使用します。Cashier14はStripe APIバージョン2022-11-15を利用しています。Stripe APIバージョンは、新しいStripe機能と改善点を利用するために、マイナーリリースで更新されます。WarningTo prevent breaking changes, Cashier uses a fixed Stripe API version. Cashier 14 utilizes Stripe API version 2022-11-15. 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

warning Warning! CashierにすべてのStripeイベントを適切に処理させるには、キャッシャーのWebhook処理を忘れずに設定してください。WarningTo ensure Cashier properly handles all Stripe events, remember to set up Cashier's webhook handling[#handling-stripe-webhooks].

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

Cashierのサービスプロバイダは独自のデータベースマイグレーションディレクトリを登録しているため、パッケージのインストール後にデータベースをマイグレーションするのを忘れないでください。Cashierのマイグレーションにより、usersテーブルへ列がいくつか追加されるだけでなく、顧客のすべてのサブスクリプションを保持する新しいsubscriptionsテーブルが作成されます。Cashier's service provider registers its own database migration directory, so remember to migrate your database after installing the package. The Cashier migrations will add several columns to your users table as well as create a new subscriptions table to hold all of your customer's subscriptions:

php artisan migrate

Cashierに同梱されているマイグレーションを上書きする必要がある場合は、vendor:publish Artisanコマンドを使用してそれらをリソース公開できます。If you need to overwrite the migrations that ship with Cashier, you can publish them using the vendor:publish Artisan command:

php artisan vendor:publish --tag="cashier-migrations"

Cashierのマイグレーションを完全に実行しないようにする場合は、Cashierが提供するignoreMigrationsメソッドを使用してください。通常、このメソッドは、AppServiceProviderregisterメソッドで呼び出す必要があります。If you would like to prevent Cashier's migrations from running entirely, you may use the ignoreMigrations method provided by Cashier. Typically, this method should be called in the register method of your AppServiceProvider:

use Laravel\Cashier\Cashier;

/**
 * 全アプリケーションサービスの登録
 *
 * @return void
 */
public function register()
{
    Cashier::ignoreMigrations();
}

warning Warning! Stripeは、Stripe識別子の格納に使用するカラムでは、大文字と小文字を区別することを推奨しています。したがって、MySQLを使用する場合は、stripe_id列の列照合順序を確実にutf8_binへ設定する必要があります。これに関する詳細は、Stripeドキュメントにあります。WarningStripe recommends that any column used for storing Stripe identifiers should be case-sensitive. Therefore, you should ensure the column collation for the stripe_id column is set to utf8_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;

/**
 * アプリケーション全サービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    Cashier::useCustomerModel(User::class);
}

warning Warning! Laravelが提供するApp\Models\Userモデル以外のモデルを使用する場合は、提供しているCashierマイグレーションをリソース公開し、代替モデルのテーブル名と一致するように変更する必要があります。WarningIf you're using a model other than Laravel's supplied App\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 Warning! アプリケーションの.envファイルで、STRIPE_WEBHOOK_SECRET環境変数を確実に定義してください。この変数は、受け取ったWebhookが実際にStripeから送られたものであることを確認するために使用します。WarningYou should ensure that the STRIPE_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 Warning! en以外のロケールを使用するは、ext-intl PHP拡張機能をサーバへ確実にインストール・設定してください。WarningIn order to use locales other than en, ensure the ext-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;

/**
 * アプリケーション全サービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    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! 一回限りの課金一回限りの支払いでは税金が計算されません。WarningNo 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;

/**
 * アプリケーション全サービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    Cashier::useSubscriptionModel(Subscription::class);
    Cashier::useSubscriptionItemModel(SubscriptionItem::class);
}

顧客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 function Illuminate\Events\queueable;

/**
 * モデルの「起動(booted)」メソッド
 *
 * @return void
 */
protected static function booted()
{
    static::updated(queueable(function ($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:

/**
 * ストライプと同期する顧客名の取得
 *
 * @return string|null
 */
public function stripeName()
{
    return $this->company_name;
}

同様に、stripeEmailstripePhonestripeAddressstripePreferredLocalesメソッドをオーバーライドできます。これらのメソッドは、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].

lightbulb Note:Setup Intentsと顧客の支払いの詳細の収集について詳しく知りたい場合は、Stripeが提供しているこの概要を確認してくださいNoteIf 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();

このメソッドはデフォルトで、cardタイプの支払い方法を返します。別のタイプの支払い方法を取得するには、メソッドの引数にtypeを渡します。By default, this method will return payment methods of the card type. To retrieve payment methods of a different 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);

顧客に支払い方法があるか判定Determining If A User Has A Payment Method

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モデルがcardタイプの支払い方法を持っているかどうかを判断します。そのモデルに別のタイプの支払い方法が存在するかを判断するには、メソッドの引数にtypeを渡してください。This method will determine if the billable model has payment methods of the card type. To determine if a payment method of another 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回だけの請求には使用できません。WarningThe 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);

lightbulb Note:支払い方法の識別子を取得する方法については、支払い方法の保存に関するドキュメントを確認してください。NoteTo 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();

このメソッドはデフォルトで、cardタイプの支払い方法を削除します。別のタイプの支払い方法を削除するには、メソッドの引数にtypeを渡します。By default, this method will delete payment methods of the card type. To delete payment methods of a different type you can pass the type as an argument to the method:

$user->deletePaymentMethods('sepa_debit');

warning Warning! ユーザーがアクティブなサブスクリプションを持っている場合、アプリケーションはユーザーがデフォルトの支払い方法を削除することを許してはいけません。WarningIf 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メソッドへ渡す最初の引数は、サブスクリプションの内部名称です。アプリケーションが単一サブスクリプションのみ提供している場合は、これをdefaultprimaryと名付けることが多いでしょう。このサブスクリプション名は、アプリケーション内部でのみ使用するものであり、ユーザーに表示するものではありません。また、スペースを含んではならず、サブスクリプションを作成した後は決して変更してはいけません。2番目の引数は、ユーザーが購読している価格の指定です。この値は、Stripeにおける価格の識別子に対応していなければなりません。The first argument passed to the newSubscription method should be the internal name of the subscription. If your application only offers a single subscription, you might call this default or primary. This subscription name 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 Warning! 支払い方法識別子をcreateサブスクリプションメソッドへ直接渡すと、ユーザーの保存済み支払い方法にも自動的に追加されます。WarningPassing a payment method identifier directly to the create 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の名前を割り当てます。ダッシュボードから作成するサブスクリプションに割り当てるサブスクリプション名をカスタマイズするには、WebhookControllerを拡張し、newSubscriptionNameメソッドを上書きします。You may also create subscriptions from the Stripe dashboard itself. When doing so, Cashier will sync newly added subscriptions and assign them a name of default. To customize the subscription name that is assigned to dashboard created subscriptions, extend the WebhookController[#defining-webhook-event-handlers] and overwrite the newSubscriptionName method.

また、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 names, 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 name 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;

class EnsureUserIsSubscribed
{
    /**
     * 受信リクエストの処理
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        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 Warning! ユーザーが同じ名前のサブスクリプションを2つ持っている場合、subscriptionメソッドは最新のサブスクリプションを常に返します。たとえば、ユーザーがdefaultという名前のサブスクリプションレコードを2つ持っているとします。この場合、サブスクリプションの1つは古い期限切れのサブスクリプションであり、もう1つは現在のアクティブなサブスクリプションである可能性があります。最新のサブスクリプションを常に返しますが、古いサブスクリプションは履歴レビューのためにデータベースに保持されます。WarningIf a user has two subscriptions with the same name, the most recent subscription will always be returned by the subscription method. For example, a user might have two subscription records named default; 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_dueincompleteの状態でも、アクティブとみなしたい場合は、Cashierが提供するkeepPastDueSubscriptionsActiveと、keepIncompleteSubscriptionsActiveメソッドを使用します。通常、これらのメソッドはAppAppServiceProvidersregisterメソッドで呼び出す必要があります。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;

/**
 * 全アプリケーションサービスの登録
 *
 * @return void
 */
public function register()
{
    Cashier::keepPastDueSubscriptionsActive();
    Cashier::keepIncompleteSubscriptionsActive();
}

warning Warning! サブスクリプションがincomplete状態の場合、支払いが確認されるまで変更できません。したがって、サブスクリプションがincomplete状態の場合、swapメソッドとupdateQuantityメソッドは例外を投げます。WarningWhen a subscription is in an incomplete state it cannot be changed until the payment is confirmed. Therefore, the swap and updateQuantity methods will throw an exception when the subscription is in an incomplete 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 Warning! swapAndInvoiceメソッドの前にnoProrateメソッドを実行しても、比例按分には影響しません。請求書は常に発行されます。WarningExecuting the noProrate method before the swapAndInvoice 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! サブスクリプションの最後の価格は削除できません。代わりに、単にサブスクリプションをキャンセルしてください。WarningYou 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

個々のサブスクリプション価格の個数を変更する場合は、既存の個数メソッドを使用して、価格の名前をメソッドの追加引数として渡すことで更新できます。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 name 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 Warning! サブスクリプションに複数の価格がある場合、Subscriptionモデルのstripe_plan属性とquantity属性はnullになります。個々の価格属性にアクセスするには、Subscriptionモデルで使用可能なitemsリレーションを使用する必要があります。WarningWhen a subscription has multiple prices the stripe_price and quantity attributes on the Subscription model will be null. To access the individual price attributes, you should use the items relationship available on the Subscription 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 name of the subscription to the newSubscription method. The name 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

warning Warning! 税率を手作業で計算する代わりに、Stripe Taxを使って自動的に税金を計算できます。WarningInstead 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
 */
public function taxRates()
{
    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
 */
public function priceTaxRates()
{
    return [
        'price_monthly' => ['txr_id'],
    ];
}

warning Warning! taxRatesメソッドはサブスクリプション料金にのみ適用されます。Cashierを使用して「1回限り」の料金を請求する場合は、その時点で税率を手作業で指定する必要があります。WarningThe taxRates 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は、顧客が非課税であるかどうかを判断するために、isNotTaxExemptisTaxExemptreverseChargeAppliesメソッドも提供しています。これらのメソッドは、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 Warning! これらのメソッドは、すべてのLaravel\Cashier\Invoiceオブジェクトでも使用できます。ただし、Invoiceオブジェクトで呼び出した場合、メソッドは請求書が作成された時点の免税状態を用います。WarningThese methods are also available on any Laravel\Cashier\Invoice object. However, when invoked on an Invoice 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)
);

サブスクリプションの再開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! 無料トライアル期間の終了日より前に顧客がそのサブスクリプションをキャンセルしなかった場合、無料トライアル期間の終了時にすぐ課金されるため、無料トライアル期間の終了日をユーザーに必ず通知する必要があります。WarningIf 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 Warning! Billableなモデルのクラス定義内のtrial_ends_at属性に日付のキャストを必ず追加してください。WarningBe sure to add a date cast[/docs/{{version}}/eloquent-mutators#date-casting] for the trial_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 name 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

lightbulb Note:Stripe CLIを使用して、ローカル開発中にWebhookをテストすることができます。NoteYou 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/webhookURLパスに応答します。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.createdcustomer.subscription.created
  • customer.subscription.updatedcustomer.subscription.updated
  • customer.subscription.deletedcustomer.subscription.deleted
  • customer.updatedcustomer.updated
  • customer.deletedcustomer.deleted
  • invoice.payment_succeededinvoice.payment_succeeded
  • invoice.payment_action_requiredinvoice.payment_action_required

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

warning Warning! Cashierに含まれるWebフック署名の確認ミドルウェアを使って、受信するStripe Webフックリクエストを保護してください。WarningMake sure you protect incoming Stripe webhook requests with Cashier's included webhook signature verification[#verifying-webhook-signatures] middleware.

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

Stripe WebフックはLaravelのCSRF保護をバイパスする必要があるため、アプリケーションのApp\Http\Middleware\VerifyCsrfTokenミドルウェアに例外としてURIをリストするか、webミドルウェアグループの外にルートをリストしてください。Since Stripe webhooks need to bypass Laravel's CSRF protection[/docs/{{version}}/csrf], be sure to list the URI as an exception in your application's App\Http\Middleware\VerifyCsrfToken middleware or list the route outside of the web middleware group:

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

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

Cashierは課金の失敗やその他一般的なStripe Webフックイベントによる、サブスクリプションキャンセルを自動的に処理します。ただし、追加でWebフックイベントを処理したい場合は、Cashierが発行する以下のイベントをリッスンすることで可能です。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\WebhookReceivedLaravel\Cashier\Events\WebhookReceived
  • Laravel\Cashier\Events\WebhookHandledLaravel\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フックを処理
     *
     * @param  \Laravel\Cashier\Events\WebhookReceived  $event
     * @return void
     */
    public function handle(WebhookReceived $event)
    {
        if ($event->payload['type'] === 'invoice.payment_succeeded') {
            // 受信イベントの処理…
        }
    }
}

リスナを定義したら、アプリケーションのEventServiceProviderで登録します。Once your listener has been defined, you may register it within your application's EventServiceProvider:

<?php

namespace App\Providers;

use App\Listeners\StripeEventListener;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Laravel\Cashier\Events\WebhookReceived;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        WebhookReceived::class => [
            StripeEventListener::class,
        ],
    ];
}

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 Warning! The charge 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.WarningThe charge 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 receipt 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 Warning! invoiceinvoicePriceinvoiceForメソッドは、課金に失敗した場合に再試行する、Stripeインボイスを作成します。請求の失敗時に再試行したくない場合は、最初の請求が失敗した後に、Stripe APIを使用し、そのインボイスを閉じる必要があります。WarningThe invoice, invoicePrice, and invoiceFor 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 Warning! paypayWithメソッドは、アプリケーションで使用する通貨の最小単位で支払額を引数に取ります。例えば、顧客が米ドルで支払う場合、金額はペニーで指定する必要があります。WarningThe pay and payWith 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, $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バイトを返す
     *
     * @param  \Laravel\Cashier\Invoice. $invoice
     * @param  array  $data
     * @param  array  $options
     * @return string
     */
    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_urlcancel_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 Warning! checkoutChargeメソッドを使用すると、Stripeは常にStripeダッシュボードに新しい製品と価格を作成します。そのため、代わりにStripeダッシュボードで事前に商品を作成し、checkoutメソッドを使用することを推奨します。WarningWhen using the checkoutCharge 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 the checkout method instead.

サブスクリプションの支払いSubscription Checkouts

warning Warning! Stripe Checkoutのサブスクリプションを使用するには、Stripeダッシュボードでcustomer.subscription.created Webフックを有効にする必要があります。このWebフックは、データベースにサブスクリプションレコードを作成し、すべてのサブスクリプション関連アイテムを保存します。WarningUsing Stripe Checkout for subscriptions requires you to enable the customer.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 Warning! 残念ながらStripe Checkoutはサブスクリプションを開始するとき、すべてのサブスクリプション請求オプションをサポートしていません。サブスクリプションビルダのanchorBillingCycleOnメソッドの使用や、比例配分の動作の設定、支払い動作の設定は、Stripeチェックアウトセッション中は全く効果がありません。どのパラメータが利用可能であるかを確認するには、Stripe CheckoutセッションAPIのドキュメントを参照してください。WarningUnfortunately Stripe Checkout does not support all subscription billing options when starting subscriptions. Using the anchorBillingCycleOn 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 & 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.

サブスクリプションとWebフックSubscriptions & 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 Warning! アプリケーションのサービスプロバイダで自動徴税を設定済みであれば、この機能は自動的に有効になり、collectTaxIdsメソッドを呼び出す必要はありません。WarningIf 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 the collectTaxIds 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トレイトを使用するモデルのchargeinvoiceForinvoiceメソッドでは、支払いの例外が投げられる場合があります。サブスクリプションを操作する場合では、SubscriptionBuildercreateメソッド、およびSubscriptionSubscriptionItemモデルの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()) {
        // ...
    }
}

強力な顧客認証(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.

warning Warning! 使用開始前に、PSD2とSCAに関するStripeのガイド新しいSCA APIに関するドキュメントを確認してください。WarningBefore 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データベースカラムが、incompletepast_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_requiredwebhookが有効になっていることを確認してください。さらに、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回目の請求を行ってしまうことはありません。WarningNotifications 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にヒットすることを許可することをおすすめします。これは遅いですが、アプリケーションが期待どおりに機能しているという確信が高まり、遅いテストは独自の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 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.

lightbulb Note:クレジットカードの拒否や失敗など、さまざまな請求シナリオをテストするため、Stripeが提供しているさまざまなカード番号とトークンのテストを使用できます。NoteIn 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.

章選択

設定

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

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

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

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

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

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

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

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

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作