Readouble

Laravel 7.x Laravel Cashier

イントロダクションIntroduction

Laravel CashierはStripeによるサブスクリプション(定期課金)サービスの読みやすく、スラスラと記述できるインターフェイスを提供します。これにより書くのが恐ろしくなるような、サブスクリプション支払いのための決まりきったコードのほとんどが処理できます。基本的なサブスクリプション管理に加え、Cashierはクーポン、サブスクリプションの変更、サブスクリプション数、キャンセル猶予期間、さらにインボイスのPDF発行まで行います。Laravel Cashier provides an expressive, fluent interface to Stripe's[https://stripe.com] subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs.

CashierのアップデートUpgrading Cashier

新しいバージョンの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].

Note: note ブレーキングチェンジを防ぐために、CashierではStripeの固定APIバージョンを使用しています。Cashier12では、Stripeの2020-03-02付けAPIバージョンを使用しています。Stripeの新機能や機能向上を利用するため、マイナーリリースでもStripe APIのバージョンを更新することがあります。{note} To prevent breaking changes, Cashier uses a fixed Stripe API version. Cashier 12 utilizes Stripe API version 2020-03-02. The Stripe API version will be updated on minor releases in order to make use of new Stripe features and improvements.

インストールInstallation

はじめに、Stripe向けCashierパッケージをComposerでインストールしてください。First, require the Cashier package for Stripe with Composer:

composer require laravel/cashier

Note: note Stripeの全イベントをCashierで確実に処理するために、CashierのWebhook処理の準備を行なってください。{note} To ensure Cashier properly handles all Stripe events, remember to set up Cashier's webhook handling[#handling-stripe-webhooks].

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

CashierサービスプロバーダでCashierのデータベースマイグレーションを登録しています。ですから、パッケージをインストールしたら、データベースのマイグレーションを忘れず実行してください。Cashierマイグレーションはusersテーブルにいくつものカラムを追加し、顧客のサブスクリプションをすべて保持するために新しいsubscriptionsテーブルを作成します。The Cashier 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 the Cashier package, 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 provided by Cashier. Typically, this method should be called in the register method of your AppServiceProvider:

use Laravel\Cashier\Cashier;

Cashier::ignoreMigrations();

Note: note StripeはStripeの識別子を保存しておくカラムはケースセンシティブ(大文字小文字区別)にするべきだと勧めています。そのためstripe_idカラムには、たとえばMySQLではutf8_binのように、適切なカラムコレーションを確実に指定してください。詳しい情報は、Stripeのドキュメントをお読みください。{note} Stripe 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, for example, utf8_bin in MySQL. More info 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トレイトを追加します。このトレイトはサブスクリプションの作成やクーポンの適用、支払い情報の更新などのような、共通の支払いタスク実行を提供する数多くのメソッドを提供しています。Before using Cashier, add the Billable trait to your model definition. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons, and updating payment method information:

use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;
}

CashierはLaravelに含まれているApp\UserクラスがBillableモデルであると仮定しています。これを変更する場合は、.envファイルでモデルを指定してください。Cashier assumes your Billable model will be the App\User class that ships with Laravel. If you wish to change this you can specify a different model in your .env file:

CASHIER_MODEL=App\User

Note: note Laravelの提供するApp\Userモデル以外のモデルを使用する場合は、提供しているマイグレーションをリソース公開し、モデルのテーブル名に一致するように変更する必要があります。{note} If you're using a model other than Laravel's supplied App\User model, you'll need to publish and alter the migrations[#installation] provided to match your alternative model's table name.

APIキーAPI Keys

次に、.envファイルの中のStripeキーを設定する必要があります。Stripe APIキーは、Stripeのコントロールパネルから取得できます。Next, you should configure your Stripe keys in your .env file. You can retrieve your Stripe API keys from the Stripe control panel.

STRIPE_KEY=your-stripe-key
STRIPE_SECRET=your-stripe-secret

通貨設定Currency Configuration

Cashierのデフォルト通貨は米ドル(USD)です。CASHIER_CURRENCY環境変数の指定で、デフォルト通貨を変更可能です。The default Cashier currency is United States Dollars (USD). You can change the default currency by setting the CASHIER_CURRENCY environment variable:

CASHIER_CURRENCY=eur

Caishierの通貨設定に付け加え、インボイスで表示する金額のフォーマットをローケルを使い指定することも可能です。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

Note: note en以外のローケルを指定する場合は、サーバ設定でext-intl PHP拡張がインストールされているのを確認してください。{note} In order to use locales other than en, ensure the ext-intl PHP extension is installed and configured on your server.

ログLogging

Stripeに関連する例外をすべてログする時に使用できるログチャンネルをCashierでは指定できます。CASHIER_LOGGER環境変数を使用し、ログチャンネルを指定します。Cashier allows you to specify the log channel to be used when logging all Stripe related exceptions. You may specify the log channel using the CASHIER_LOGGER environment variable:

CASHIER_LOGGER=stack

顧客Customers

顧客の取得Retrieving Customers

Cashier::findBillableメソッドによりStripe IDで顧客を取得できます。Billableモデルのインスタンスを返します。You can retrieve a customer by their Stripe ID using the Cashier::findBillable method. This 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上に作成しておき、後日サブスクリプションを開始することもできます。また、Stripe APIが提供するオプション($options)を配列として、追加引数に渡すことも可能です。Once the customer has been created in Stripe, you may begin a subscription at a later date. You can also use an optional $options array to pass in any additional parameters which are supported by the Stripe API:

$stripeCustomer = $user->createAsStripeCustomer($options);

BillableなエンティティがすでにStripeの顧客である場合に顧客オブジェクトを返したい場合は、asStripeCustomerメソッドを使用できます。You may use the asStripeCustomer method if you want to return the customer object if the billable entity is already a customer within Stripe:

$stripeCustomer = $user->asStripeCustomer();

createOrGetStripeCustomerメソッドは、顧客オブジェクトを返したいがBillableなエンティティがすでにStripeの顧客であるかどうかわからない場合に使用します。このメソッドは、まだ存在していない場合、Stripeに新しい顧客を作成します。The createOrGetStripeCustomer method may be used if you want to return the customer object but are not sure whether the billable entity 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メソッドを使用してください。Occasionally, you may wish to update the Stripe customer directly with additional information. You may accomplish this using the updateStripeCustomer method:

$stripeCustomer = $user->updateStripeCustomer($options);

支払いポータルBilling Portal

顧客がサブスクリプションや支払い方法を管理したり、履歴を確認したりを簡単にできるよう、Stripeは支払いポータルを用意しています。コントローラやルートでredirectToBillingPortalメソッドを使えば、ユーザーを支払いポータルへリダイレクトできます。Stripe offers an easy way to set up a billing portal[https://stripe.com/docs/billing/subscriptions/customer-portal] so your customer can manage their subscription, payment methods, and view their billing history. You can redirect your users to the billing portal using the redirectToBillingPortal method from a controller or route:

use Illuminate\Http\Request;

public function billingPortal(Request $request)
{
    return $request->user()->redirectToBillingPortal();
}

サブスクリプションの管理を終えたユーザーは、アプリケーションのhomeルートへ戻されるのがデフォルトです。redirectToBillingPortalメソッドの引数としてユーザーの戻りURLを指定し、カスタマイズ可能です。By default, when the user is finished managing their subscription, they can return to the home route of your application. You may provide a custom URL the user should return to by passing the URL as an argument to the redirectToBillingPortal method:

use Illuminate\Http\Request;

public function billingPortal(Request $request)
{
    return $request->user()->redirectToBillingPortal(
        route('billing')
    );
}

支払いポータルへのURLを生成のみしたい場合はbillingPortalUrlメソッドを使用してください。If you would like to only generate the URL to the billing portal, you may use the billingPortalUrl method:

$url = $user->billingPortalUrl(route('billing'));

支払い方法Payment Methods

支払い方法の保存Storing Payment Methods

Stripeでサブスクリプションを生成するか「一度だけ」の課金を実行するためには、支払い方法を登録し、IDを取得する必要があります。サブスクリプションのための支払いメソッドか、一回だけの課金ためかによりアプローチが異なるため、以下で両方共にみていきましょう。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 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 Intentを簡単に作成できるcreateSetupIntentを含んでいます。顧客の支払いメソッドの詳細情報を集めるフォームをレンダーしたいルートやコントローラから、このメソッドを呼び出してください。When storing credit cards to a customer for future use, 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 to easily create a new Setup Intent. You should call 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 Intentを作成したらそれをビューに渡し、支払い方法を集める要素にsecretを付け加える必要があります。たとえば、このような「支払い方法更新」フォームを考えてください。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">

<!-- Stripe要素のプレースホルダ -->
<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 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">Tip!! Setup Intentsと顧客支払いの詳細情報の収集に関するより詳しい情報は、Stripeが提供している概要をご覧ください。{tip} If you would like more information about Setup Intents and gathering customer payment details please review this overview provided by Stripe[https://stripe.com/docs/payments/save-and-reuse#php].

一回のみの課金に対する支払い方法Payment Methods For Single Charges

顧客の支払いメソッドに対し一回のみの課金を作成する場合、ワンタイムの支払いメソッド識別子を使う必要があるだけで済みます。Stripeの制限により、保存されている顧客のデフォルト支払い方法は使用できません。Stripe.jsライブラリを使用し、顧客に支払い方法の詳細を入力してもらえるようにする必要があります。例として、以降のフォームを考えてみましょう。Of course, when making a single charge against a customer's payment method we'll only need to use a payment method identifier a single time. 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">

<!-- Stripe要素のプレースホルダ -->
<div id="card-element"></div>

<button id="card-button">
    Process Payment
</button>

Stripe.jsライブラリを使い、Stripe要素をフォームに付け加え、顧客の支払いの詳細を安全に収集します。Next, the Stripe.js library may be used to attach a Stripe Element 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によりカードが検証し、安全な「支払い方法識別子」をSrtipeから取得します。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アプリケーションに渡し、1回限りの支払いを処理できます。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();

デフォルト支払いメソッドを取得する場合は、defaultPaymentMethodメソッドを使用してください。To retrieve the default payment method, the defaultPaymentMethod method may be used:

$paymentMethod = $user->defaultPaymentMethod();

findPaymentMethodメソッドを使用し、そのBillableモデルが持っている特定の支払いメソッドを取得することもできます。You can also retrieve a specific payment method that is owned by 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, use the hasDefaultPaymentMethod method:

if ($user->hasDefaultPaymentMethod()) {
    //
}

Billableモデルが自身のアカウントに付加されている支払いメソッドを最低1つ持っているかを判定するには、hasPaymentMethodメソッドを使用します。To determine if a Billable model has at least one payment method attached to their account, use the hasPaymentMethod method:

if ($user->hasPaymentMethod()) {
    //
}

デフォルト支払い方法の更新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();

Note: note 顧客のデフォルト支払い方法は、インボイス発行処理と新しいサブスクリプションの生成にだけ使用されます。Stripeの制限により、一回だけの課金には使用されません。{note} The default payment method on a customer can only be used for invoicing and creating new subscriptions. Due to limitations from Stripe, it may not be used for single charges.

支払い方法の追加Adding Payment Methods

新しい支払い方法を追加するには、Billableのユーザーに対し、addPaymentMethodを呼び出します。支払いメソッド識別子を渡してください。To add a new payment method, you may call the addPaymentMethod method on the billable user, passing the payment method identifier:

$user->addPaymentMethod($paymentMethod);

lightbulb">Tip!! 支払い方法の識別子の取得方法を学ぶには、支払い方法保持のドキュメントを確認してください。{tip} To learn how to retrieve payment method identifiers please review the payment method storage documentation[#storing-payment-methods].

支払い方法の削除Deleting Payment Methods

支払い方法を削除するには、削除したいLaravel\Cashier\PaymentMethodインスタンス上のdeleteメソッドを呼び出します。To delete a payment method, you may call the delete method on the Laravel\Cashier\PaymentMethod instance you wish to delete:

$paymentMethod->delete();

deletePaymentMethodsメソッドは、そのBillableモデルの全支払いメソッド情報を削除します。The deletePaymentMethods method will delete all of the payment method information for the Billable model:

$user->deletePaymentMethods();

Note: note アクティブなサブスクリプションがあるユーザーでは、デフォルト支払いメソッドが削除されないようにする必要があるでしょう。{note} If a user has an active subscription, you should prevent them from deleting their default payment method.

サブスクリプションSubscriptions

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

サブスクリプションを作成するには最初にbillableなモデルのインスタンスを取得しますが、通常はApp\Userのインスタンスでしょう。モデルインスタンスが獲得できたら、モデルのサブスクリプションを作成するために、newSubscriptionメソッドを使います。To create a subscription, first retrieve an instance of your billable model, which typically will be an instance of App\User. Once you have retrieved the model instance, you may use the newSubscription method to create the model's subscription:

$user = User::find(1);

$user->newSubscription('default', 'price_premium')->create($paymentMethod);

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

createメソッドはStripeの支払い方法識別子、もしくはPaymentMethodオブジェクトを引数に取り、サブスクリプションを開始するのと同時に、データベースの顧客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 customer ID and other relevant billing information.

Note: note サブスクリプションのcreate()へ支払いメソッド識別子を直接渡すと、ユーザーの保存済み支払いメソッドへ自動的に追加します。{note} Passing a payment method identifier directly to the create() subscription method will also automatically add it to the user's stored payment methods.

注文数Quantities

サブスクリプションの作成時に注文数を指定する場合は、quantityメソッドを使います。If you would like to set a specific quantity for the plan when creating the subscription, you may use the quantity method:

$user->newSubscription('default', 'price_monthly')
     ->quantity(5)
     ->create($paymentMethod);

詳細情報の指定Additional Details

ユーザーとサブスクリプションに関する詳細情報を追加したい場合は、createメソッドの第2引数と第3引数へ渡すことができます。If you would like to specify additional customer or subscription details, 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.'],
]);

Stripeがサポートしている追加のフィールドについてのさらなる情報は、Stripeの顧客の作成サブスクリプションの作成ドキュメントを確認してください。To learn more about the additional fields supported by Stripe, check out Stripe's documentation on customer creation[https://stripe.com/docs/api#create_customer] and subscription creation[https://stripe.com/docs/api/subscriptions/create].

クーポン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);

サブスクリプションの追加Adding Subscriptions

デフォルトの支払い方法を設定済みユーザーへサブスクリプションを追加する場合は、newSubscriptionメソッド使用時にaddメソッドが使えます。If you would like to add a subscription to a customer who already has a default payment method set you can use the add method when using the newSubscription method:

$user = User::find(1);

$user->newSubscription('default', 'price_premium')->add();

サブスクリプション状態の確認Checking Subscription Status

ユーザーがアプリケーションで何かを購入したら、バラエティー豊かで便利なメソッドでサブスクリプション状況を簡単にチェックできます。まず初めにsubscribedメソッドがtrueを返したら、サブスクリプションが現在試用期間であるにしても、そのユーザーはアクティブなサブスクリプションを持っています。Once a user is subscribed to your application, you may easily check their subscription status using a variety of convenient methods. First, the subscribed method returns true if the user has an active subscription, even if the subscription is currently within its trial period:

if ($user->subscribed('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:

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 displaying a warning to the user that they are still on their trial period:

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

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

if ($user->subscribedToPlan('price_monthly', 'default')) {
    //
}

subscribedToPlanメソッドに配列を渡せば、ユーザーのdefaultサブスクリプションが、購入され有効なmonthlyyearlyプランであるかを判定できます。By passing an array to the subscribedToPlan method, you may determine if the user's default subscription is actively subscribed to the monthly or the yearly plan:

if ($user->subscribedToPlan(['price_monthly', 'price_yearly'], '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()) {
    //
}

キャンセルしたサブスクリプションの状態Cancelled Subscription Status

ユーザーが一度アクティブな購入者になってから、サブスクリプションをキャンセルしたことを調べるには、cancelledメソッドを使用します。To determine if the user was once an active subscriber, but has cancelled their subscription, you may use the cancelled method:

if ($user->subscription('default')->cancelled()) {
    //
}

また、ユーザーがサブスクリプションをキャンセルしているが、まだ完全に期限が切れる前の「猶予期間」中であるかを調べることもできます。たとえば、ユーザーが3月5日にサブスクリプションをキャンセルし、3月10日で無効になる場合、そのユーザーは3月10日までは「猶予期間」中です。subscribedメソッドは、この期間中、まだtrueを返すことに注目してください。You may also determine if a user has cancelled their subscription, but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. Note that the subscribed method still returns true during this time:

if ($user->subscription('default')->onGracePeriod()) {
    //
}

ユーザーがサブスクリプションをキャンセルし、「猶予期間」を過ぎていることを調べるには、endedメソッドを使ってください。To determine if the user has cancelled their subscription and is no longer within their "grace period", you may use the ended method:

if ($user->subscription('default')->ended()) {
    //
}

サブスクリプションスコープ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()->cancelled()->get();

以下に利用可能なサブスクリプションスコープをリストします。A complete list of available scopes is available below:

Subscription::query()->active();
Subscription::query()->cancelled();
Subscription::query()->ended();
Subscription::query()->incomplete();
Subscription::query()->notCancelled();
Subscription::query()->notOnGracePeriod();
Subscription::query()->notOnTrial();
Subscription::query()->onGracePeriod();
Subscription::query()->onTrial();
Subscription::query()->pastDue();
Subscription::query()->recurring();

不十分と期日超過の状態Incomplete and Past Due Status

サブスクリプション作成後、そのサブクリプションが2つ目の支払いアクションを要求している場合、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.

同様に、サブスクリプションの変更時に第2の支払いアクションが要求されている場合は、past_due(期日超過)として印がつけられます。サブスクリプションが2つのどちらかである時、顧客が支払いを受領するまで状態は有効になりません。あるサブクリプションに不十分な支払いがあるかを確認する場合は、Billableモデルかサブクリプションインスタンス上のhasIncompletePaymentメソッドを使用します。Similarly, if a secondary payment action is required when swapping plans 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. Checking if a subscription has an incomplete payment can be done 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) }}">
    Please confirm your payment.
</a>

past_due状態のときでも、特定のサブスクリプションをアクティブと見なしたい場合は、Cashierが提供するkeepPastDueSubscriptionsActiveメソッドを使用します。通常このメソッドは、AppServiceProviderregisterメソッドの中で呼び出すべきです。If you would like the subscription to still be considered active when it's in a past_due state, you may use the keepPastDueSubscriptionsActive 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::keepPastDueSubscriptionsActive();
}

Note: note あるサブクリプションにincomplete状態がある場合、支払いを確認するまでは変更できません。そのためサブクリプションがincomplete状態では、swapupdateQuantityメソッドは例外を投げます。{note} When 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.

プラン変更Changing Plans

アプリケーションの購入済みユーザーが新しいサブスクリプションプランへ変更したくなるのはよくあるでしょう。ユーザーを新しいサブスクリプションに変更するには、swapメソッドへプランの価格識別子を渡します。After a user is subscribed to your application, they may occasionally want to change to a new subscription plan. To swap a user to a new subscription, pass the plan's price identifier to the swap method:

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

$user->subscription('default')->swap('provider-price-id');

ユーザーが試用期間中の場合、試用期間は継続します。また、そのプランに「購入数」が存在している場合、購入個数も継続します。If the user is on trial, the trial period will be maintained. Also, if a "quantity" exists for the subscription, that quantity will also be maintained.

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

$user->subscription('default')
        ->skipTrial()
        ->swap('provider-price-id');

次の支払いサイクルまで待つ代わりに、プランを変更時即時にインボイスを発行したい場合は、swapAndInvoiceメソッドを使用します。If you would like to swap plans and immediately invoice the user instead of waiting for their next billing cycle, you may use the swapAndInvoice method:

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

$user->subscription('default')->swapAndInvoice('provider-price-id');

按分課金Prorations

デフォルトでStripeはプランの変更時に按分課金(日割り計算:prorate)を行います。noProrateメソッドは按分課金を行わずにサブスクリプションの更新を指定するために使用します。By default, Stripe prorates charges when swapping between plans. The noProrate method may be used to update the subscription's without prorating the charges:

$user->subscription('default')->noProrate()->swap('provider-price-id');

サブスクリプションの按分課金についての情報は、Stripeドキュメントで確認してください。For more information on subscription proration, consult the Stripe documentation[https://stripe.com/docs/billing/subscriptions/prorations].

Note: note swapAndInvoiceメソッドの前にnoProrateメソッドを実行しても按分課金には影響しません。インボイスは常に発行されます。{note} Executing the noProrate method before the swapAndInvoice method will have no affect on proration. An invoice will always be issued.

購入数Subscription Quantity

購入数はサブスクリプションに影響をあたえることがあります。たとえば、あるアプリケーションで「ユーザーごと」に毎月10ドル課金している場合です。購入数を簡単に上げ下げするには、incrementQuantitydecrementQuantityメソッドを使います。Sometimes subscriptions are affected by "quantity". For example, your application might charge $10 per month per user on an account. To easily increment or decrement your subscription quantity, use the incrementQuantity and decrementQuantity methods:

$user = User::find(1);

$user->subscription('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].

Note: note マルチプランサブスクリプションを使用する場合、上記の数量メソッドには追加の「プラン」パラメーターが必要です。{note} Please note that when working with multiplan subscriptions, an extra "plan" parameter is required for the above quantity methods.

複数のサブスクリプションMultiplan Subscriptions

複数のサブスクリプションでは、1つのサブスクリプションに複数の請求プランを割り当てられます。たとえば、月額10ドルの基本サブスクリプションがあり、さらに月額16ドルのライブチャットアドオンプランを提供する、カスタマーサービスの「ヘルプデスク」アプリケーションを構築していると想像してください。Multiplan subscriptions[https://stripe.com/docs/billing/subscriptions/multiplan] allow you to assign multiple billing plans to a single subscription. For example, imagine you are building a customer service "helpdesk" application that has a base subscription of $10 per month, but offers a live chat add-on plan for an additional $15 per month:

$user = User::find(1);

$user->newSubscription('default', [
    'price_monthly',
    'chat-plan',
])->create($paymentMethod);

これにより、顧客は新しいデフォルト(default)サブスクリプションを購入できました。両プランともそれぞれの課金期間に応じ、課金されます。各プランの購入数を指定するためにquantityメソッドも使えます。Now the customer will have two plans on their default subscription. Both plans will be charged for on their respective billing intervals. You can also use the quantity method to indicate the specific quantity for each plan:

$user = User::find(1);

$user->newSubscription('default', ['price_monthly', 'chat-plan'])
    ->quantity(5, 'chat-plan')
    ->create($paymentMethod);

もしくはplanメソッドで、追加のプランと購入数を動的に指定できます。Or, you may dynamically add the extra plan and its quantity using the plan method:

$user = User::find(1);

$user->newSubscription('default', 'price_monthly')
    ->plan('chat-plan', 5)
    ->create($paymentMethod);

他の方法として、既存のサブスクリプションへ後から、新しいプランを追加できます。Alternatively, you may add a new plan to an existing subscription at a later time:

$user = User::find(1);

$user->subscription('default')->addPlan('chat-plan');

上記の例では新しいプランが追加され、次の請求サイクルで顧客へ請求されます。すぐに顧客に請求したい場合は、addPlanAndInvoiceメソッドを使用します。The example above will add the new plan 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 addPlanAndInvoice method:

$user->subscription('default')->addPlanAndInvoice('chat-plan');

プラン追加と同時に購入数を指定したい場合は、addPlanaddPlanAndInvoiceメソッドの第2引数へ購入数を渡してください。If you would like to add a plan with a specific quantity, you can pass the quantity as the second parameter of the addPlan or addPlanAndInvoice methods:

$user = User::find(1);

$user->subscription('default')->addPlan('chat-plan', 5);

サブスクリプションからプランを削除したい場合は、removePlanメソッドを使用します。You may remove plans from subscriptions using the removePlan method:

$user->subscription('default')->removePlan('chat-plan');

Note: note サブスクリプションの最後のプランは削除できません。その代わりにサブスクリプションをシンプルにキャンセルしてください。{note} You may not remove the last plan on a subscription. Instead, you should simply cancel the subscription.

プラン切り替えSwapping

複数のサブスクリプションに紐付いているプランを変更することもできます。たとえば、chat-planアドオンを含むbasic-planサブスクリプションを利用していて、pro-planプランにアップグレードしたいとします。You may also change the plans attached to a multiplan subscription. For example, imagine you're on a basic-plan subscription with a chat-plan add-on and you want to upgrade to the pro-plan plan:

$user = User::find(1);

$user->subscription('default')->swap(['pro-plan', 'chat-plan']);

上記のコードを実行すると、basic-planを含む基になるサブスクリプションアイテムが削除され、chat-planを含むものが保持されます。さらに、新しいpro-planのために新しいサブスクリプションアイテムが作成されます。When executing the code above, the underlying subscription item with the basic-plan is deleted and the one with the chat-plan is preserved. Additionally, a new subscription item for the new pro-plan is created.

サブスクリプションアイテムのオプションを指定することもできます。たとえば、プランの購入数を指定する必要が起きる場合もあるでしょう。You can also specify subscription item options. For example, you may need to specify the subscription plan quantities:

$user = User::find(1);

$user->subscription('default')->swap([
    'pro-plan' => ['quantity' => 5],
    'chat-plan'
]);

サブスクリプション上のプランをひとつだけ切り替える場合は、サブスクリプションアイテム自体に対してswapメソッドを使用してください。このアプローチは、たとえばサブスクリプションアイテムの既存のメタデータをすべて保持したい場合に役立ちます。If you want to swap a single plan on a subscription, you may do so using the swap method on the subscription item itself. This approach is useful if you, for example, want to preserve all of the existing metadata on the subscription item.

$user = User::find(1);

$user->subscription('default')
        ->findItemOrFail('basic-plan')
        ->swap('pro-plan');

按分課金Proration

Stripeはサブスクリプションのプランを追加または削除する場合、デフォルトで料金を按分課金(日割り計算:prorate)します。按分課金を行わずにプランを調整する場合は、noProrateメソッドをプラン操作へチェーンしてください。By default, Stripe will prorate charges when adding or removing plans from a subscription. If you would like to make a plan adjustment without proration, you should chain the noProrate method onto your plan operation:

$user->subscription('default')->noProrate()->removePlan('chat-plan');

購入数Quantities

個々のサブスクリプションプランの購入数を更新する場合は、既存の購入数メソッドをつかい、メソッドの追加の引数としてプラン名を渡してください。If you would like to update quantities on individual subscription plans, you may do so using the existing quantity methods[#subscription-quantity] and passing the name of the plan as an additional argument to the method:

$user = User::find(1);

$user->subscription('default')->incrementQuantity(5, 'chat-plan');

$user->subscription('default')->decrementQuantity(3, 'chat-plan');

$user->subscription('default')->updateQuantity(10, 'chat-plan');

Note: note サブスクリプションに複数のプランを設定している場合、Subscriptionモデルのstripe_planおよびquantity属性はnullになります。個々のプランにアクセスするには、Subscriptionモデルで利用可能なitemsリレーションを使用する必要があります。{note} When you have multiple plans set on a subscription the stripe_plan and quantity attributes on the Subscription model will be null. To access the individual plans, you should use the items relationship available on the Subscription model.

サブスクリプションアイテムSubscription Items

サブスクリプションに複数のプランがある場合、データベースのsubscription_itemsテーブルに複数のサブスクリプション「アイテム」が保存されます。サブスクリプションのitemsリレーションを介してこれらにアクセスできます:When a subscription has multiple plans, 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:

$user = User::find(1);

$subscriptionItem = $user->subscription('default')->items->first();

// Retrieve the Stripe plan and quantity for a specific item...
$stripePlan = $subscriptionItem->stripe_plan;
$quantity = $subscriptionItem->quantity;

findItemOrFailメソッドを使用し、特定のプランを取得することも可能です。You can also retrieve a specific plan using the findItemOrFail method:

$user = User::find(1);

$subscriptionItem = $user->subscription('default')->findItemOrFail('chat-plan');

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

ユーザーがサブスクリプションに対して支払う税率を指定するには、BillableモデルにtaxRatesメソッドを実装し、税率IDを含む配列を返してください。これらの税率は、[Stripeダッシュボード](https://dashboard.stripe.com/test/tax-rates)で定義できます。To specify the tax rates a user pays on a subscription, implement the taxRates method on your billable model, and return an array with the Tax Rate IDs. You can define these tax rates in your Stripe dashboard[https://dashboard.stripe.com/test/tax-rates]:

public function taxRates()
{
    return ['tax-rate-id'];
}

taxRatesメソッドを使用すると、モデルごとに税率を適用できます。これは、複数の国や税率にまたがるユーザー向けサービスで役立つでしょう。マルチプランサブスクリプションを使用している場合は、BillableモデルにplanTaxRatesメソッドを実装することで、プランごとに異なる税率を定義できます。The taxRates method enables you to apply a tax rate on a model-by-model basis, which may be helpful for a user base that spans multiple countries and tax rates. If you're working with multiplan subscriptions you can define different tax rates for each plan by implementing a planTaxRates method on your billable model:

public function planTaxRates()
{
    return [
        'plan-id' => ['tax-rate-id'],
    ];
}

Note: note taxRatesメソッドはサブスクリプション料金にのみ適用されます。Cashierを使用して「1回限り」の請求を行う場合は、その時点で税率を手動で指定する必要があります。{note} The 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を変更しても、ユーザーの既存サブスクリプションの税率設定は同じままです。返されたtaxTaxRates値で既存サブスクリプションの税率を更新する場合は、ユーザーのサブスクリプションインスタンスに対し、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 returned taxTaxRates values, you should call the syncTaxRates method on the user's subscription instance:

$user->subscription('default')->syncTaxRates();

これはサブスクリプションアイテムの税率も同期するため、planTaxRatesメソッドも適切に変更してください。This will also sync any subscription item tax rates so make sure you also properly change the planTaxRates method.

非課税Tax Exemption

キャッシャーは、Stripe APIを呼び出して顧客が非課税かを判断するメソッドも提供します。isNotTaxExemptおよびisTaxExemptreverseChargeAppliesメソッドはBillableモデルで使用できます。Cashier also offers methods to determine if the customer is tax exempt by calling the Stripe API. The isNotTaxExempt, isTaxExempt, and reverseChargeApplies methods are available on the billable model:

$user = User::find(1);

$user->isTaxExempt();
$user->isNotTaxExempt();
$user->reverseChargeApplies();

これらのメソッドは、任意の Laravel\Cashier\Invoiceオブジェクトでも使用できます。ただし、Invoiceオブジェクトでこれらのメソッドを呼び出すと、メソッドはインボイス作成時の非課税状態であると判断します。These methods are also available on any Laravel\Cashier\Invoice object. However, when calling these methods 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 App\User;
use Carbon\Carbon;

$user = User::find(1);

$anchor = Carbon::parse('first day of next month');

$user->newSubscription('default', 'price_premium')
            ->anchorBillingCycleOn($anchor->startOfDay())
            ->create($paymentMethod);

サブスクリプションの課金間隔を管理する情報は、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は自動的に、データベースのends_atカラムをセットします。このカラムはいつからsubscribedメソッドがfalseを返し始めればよいのか、判定するために使用されています。たとえば、顧客が3月1日にキャンセルしたが、そのサブスクリプションが3月5日に終了するようにスケジュールされていれば、subscribedメソッドは3月5日になるまでtrueを返し続けます。When a subscription is cancelled, Cashier will automatically set the ends_at column in your database. This column is used to know when the subscribed method should begin returning false. For example, if a customer cancels a subscription on March 1st, but the subscription was not scheduled to end until March 5th, the subscribed method will continue to return true until March 5th.

ユーザーがサブスクリプションをキャンセルしたが、まだ「猶予期間」が残っているかどうかを調べるにはonGracePeriodメソッドを使います。You may determine if a user has cancelled their subscription but are still on their "grace period" using the onGracePeriod method:

if ($user->subscription('default')->onGracePeriod()) {
    //
}

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

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

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

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

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

ユーザーがサブスクリプションをキャンセルし、それからそのサブスクリプションを再開する場合、そのサブスクリプションの有効期日が完全に切れていなければすぐに課金されません。そのサブスクリプションはシンプルに再度有効になり、元々の支払いサイクルにより課金されます。If the user cancels a subscription and then resumes that subscription before the subscription has fully expired, they will not be billed immediately. Instead, their subscription will be re-activated, and they will be billed on the original billing cycle.

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

支払いの事前登録ありWith 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:

$user = User::find(1);

$user->newSubscription('default', 'price_monthly')
            ->trialDays(10)
            ->create($paymentMethod);

このメソッドはデータベースのサブスクリプションレコードへ、試用期間の終了日を設定すると同時に、Stripeへこの期日が過ぎるまで、顧客へ課金を始めないように指示します。trialDaysメソッドを使用する場合、Stripeでそのプランに対して設定したデフォルトの試用期間はオーバーライドされます。This method will set the trial period ending date on the subscription record within the database, as well as 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 plan in Stripe.

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

trialUntilメソッドにより、使用期間の終了時を指定する、DateTimeインスタンスを渡せます。The trialUntil method allows you to provide a DateTime instance to specify 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 the user is within their trial period using either the onTrial method of the user instance, or the onTrial method of the subscription instance. The two examples below are identical:

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

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

Stripe/Cashierで使用期間を定義するDefining Trial Days In Stripe / Cashier

Stripeダッシュボードによりプランで受け入れる試用日数を定義するか、Cashierを使用して常に明示的に引数で渡すか選んでください。Stripeでプランの試用日数を定義することを選択する場合、過去にサブスクリプションを購入した顧客の新規サブスクリプションも含め、新規サブスクリプションは明示的にtrialDays(0)を呼び出さない限り、常に試用期間を受け取ることに注意してください。You may choose to define how many trial days your plan's receive in the Stripe dashboard or always pass them explicitly using Cashier. If you choose to define your plan'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 trialDays(0) 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:

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

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

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

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

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

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

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

$user = User::find(1);

$user->newSubscription('default', 'price_monthly')->create($paymentMethod);

試用期限の延長Extending Trials

一度作成したあとに、サブスクリプションの試用期間を延長したい場合は、extendTrialメソッドを使用します。The extendTrial method allows you to extend the trial period of a subscription after it's been created:

// 今から7日後に試用期限を終える
$subscription->extendTrial(
    now()->addDays(7)
);

// 使用期限を5日間延長する
$subscription->extendTrial(
    $subscription->trial_ends_at->addDays(5)
);

試用期間が過ぎ、顧客がサブスクリプションをすでに購入している場合でも、追加の試用期限を与えられます。試用期間で費やされた時間は、その顧客の次回のインボイスから差し引かれます。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.

StripeのWebフック処理Handling Stripe Webhooks

lightbulb">Tip!! ローカル環境でWebhooksのテストするには、Stripe CLIが役立つでしょう。{tip} You may use the Stripe CLI[https://stripe.com/docs/stripe-cli] to help test webhooks during local development.

StripeはWebフックにより、アプリケーションへさまざまなイベントを通知できます。デフォルトで、CashierのWebhookを処理するルートのコントローラは、Cashierのサービスプロバイダで設定されています。このコントローラはWebhookの受信リクエストをすべて処理します。Stripe can notify your application of a variety of events via webhooks. By default, a route that points to Cashier's webhook controller is configured through the Cashier service provider. This controller will handle all incoming webhook requests.

デフォルトでこのコントローラは、課金に多く失敗し続ける(Stripeの設定で定義している回数)、顧客の更新、顧客の削除、サブスクリプションの変更、支払い方法の変更があると、自動的にサブスクリプションをキャンセル処理します。しかしながら、すぐに見つけることができるようにこのコントローラを拡張し、どんなWebhookイベントでもお好きに処理できますBy default, this 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 webhook event you like.

アプリケーションでStripeのWebhookを処理するためには、StripeのコントロールパネルでWebhook URLを確実に設定してください。CashierのWebhookのデフォルトコントローラは、/stripe/webhookのURIをリッスンしています。Stripeのコントロールパネルで設定する必要のあるWebhookの全リストは、以下のとおりです。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 listens to the /stripe/webhook URL path. The full list of all webhooks you should configure in the Stripe control panel are:

  • customer.subscription.updatedcustomer.subscription.updated
  • customer.subscription.deletedcustomer.subscription.deleted
  • customer.updatedcustomer.updated
  • customer.deletedcustomer.deleted
  • invoice.payment_action_requiredinvoice.payment_action_required

Note: note Cashierに含まれる、Webフック署名の確認ミドルウェアを使用し、受信リクエストを確実に保護してください。{note} Make sure you protect incoming requests with Cashier's included webhook signature verification[/docs/{{version}}/billing#verifying-webhook-signatures] middleware.

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

StripeのWebフックでは、Laravelの CSRFバリデーションをバイパスする必要があるため、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 VerifyCsrfToken middleware or list the route outside of the web middleware group:

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

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

Cashierは課金の失敗時に、サブスクリプションを自動的にキャンセル処理しますが、他のWebフックイベントを処理したい場合は、Webフックコントローラを拡張します。メソッド名はCashierが期待する命名規則に沿う必要があります。とくにメソッドはhandleのプレフィックスで始まり、処理したいStripeのWebフックの名前を「キャメルケース」にします。たとえば、invoice.payment_succeeded Webフックを処理する場合は、handleInvoicePaymentSucceededメソッドをコントローラに追加します。Cashier automatically handles subscription cancellation on failed charges, but if you have additional webhook events you would like to handle, extend the Webhook controller. Your method names should correspond to Cashier's expected convention, specifically, methods should be prefixed with handle and the "camel case" name of the webhook you wish to handle. For example, if you wish to handle the invoice.payment_succeeded webhook, you should add a handleInvoicePaymentSucceeded method to the controller:

<?php

namespace App\Http\Controllers;

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

class WebhookController extends CashierController
{
    /**
     * インボイス支払い成功時の処理
     *
     * @param  array  $payload
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handleInvoicePaymentSucceeded($payload)
    {
        // イベントの処理…
    }
}

次に、routes/web.phpの中で、キャッシャーコントローラへのルートを定義します。これにより、デフォルトのルートが上書きされます。Next, define a route to your Cashier controller within your routes/web.php file. This will overwrite the default shipped route:

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

CashierはWebhookを受け取ると、Laravel\Cashier\Events\WebhookReceivedイベントを発行します。そして、WebhookがCashierにより処理されると、Laravel\Cashier\Events\WebhookHandledイベントを発行します。両方のイベント共にStripeのWebhookの完全なペイロードを持っています。Cashier emits a Laravel\Cashier\Events\WebhookReceived event when a webhook is received, and a Laravel\Cashier\Events\WebhookHandled event when a webhook was handled by Cashier. Both events contain the full payload of the Stripe webhook.

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

顧客のクレジットカードが有効期限切れだったら? 心配いりません。CashierのWebhookコントローラが顧客のサブスクリプションをキャンセルします。失敗した支払いは自動的に捉えられ、コントローラにより処理されます。このコントローラはStripeがサブスクリプションに失敗したと判断した場合、顧客のサブスクリプションを取り消します。(通常、3回の課金失敗)What if a customer's credit card expires? No worries - Cashier's Webhook controller will cancel the customer's subscription for you. Failed payments will automatically be captured and handled by the controller. The controller will cancel the customer's subscription when Stripe determines the subscription has failed (normally after three failed payment attempts).

Webフック署名の確認Verifying Webhook Signatures

Webフックを安全にするため、StripeのWebフック署名が利用できます。便利に利用できるよう、Cashierは送信されてきた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.

Webhookの確認を有効にするには、.envファイル中のSTRIPE_WEBHOOK_SECRET環境変数を確実に設定してください。Stripeアカウントのダッシュボードから取得される、Webhookのsecretを指定します。To enable webhook verification, ensure that the STRIPE_WEBHOOK_SECRET environment variable is set in your .env file. The webhook secret may be retrieved from your Stripe account dashboard.

一回だけの課金Single Charges

課金のみSimple Charge

Note: note chargeメソッドにはアプリケーションで使用している通貨の最低単位で金額を指定します。{note} The charge method accepts the amount you would like to charge in the lowest denominator of the currency used by your application.

サブスクリプションを購入している顧客の支払いメソッドに対して、「一回だけ」の課金を行いたい場合は、Billableモデルインスタンス上のchargeメソッドを使用します。第2引数に支払い方法識別子を渡してください。If you would like to make a "one off" charge against a subscribed customer's payment method, you may use the charge method on a billable model instance. You'll need to provide a payment method identifier[#storing-payment-methods] as the second argument:

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

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. Consult the Stripe documentation regarding the options available to you when creating charges:

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

裏で動作する顧客やユーザーがなくても、chargeメソッドは使用できます。You may also use the charge method without an underlying customer or user:

use App\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) {
    //
}

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

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

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

金額は即時にユーザーのデフォルト支払い方法へ課金されます。invoiceForメソッドは第3引数に配列を受け付けます。この配列はインボイスアイテムへの支払いオプションを含みます。第4引数も配列で、インボイス自身に対する支払いオプションを指定します。The invoice will be charged immediately against the user's default payment method. The invoiceFor 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. This final argument accepts the billing options for the invoice itself:

$user->invoiceFor('Stickers', 500, [
    'quantity' => 50,
], [
    'default_tax_rates' => ['tax-rate-id'],
]);

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

払い戻しRefunding Charges

Stripeでの課金を払い戻す必要がある場合は、refundメソッドを使用します。このメソッドの第1引数は、Stripe Payment Intent IDです。If you need to refund a Stripe charge, you may use the refund method. This method accepts the Stripe Payment Intent ID as its first argument:

$payment = $user->charge(100, $paymentMethod);

$user->refund($payment->id);

インボイスInvoices

インボイス取得Retrieving Invoices

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

$invoices = $user->invoices();

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

指定したインボイスを取得する、findInvoiceメソッドも使用できます。You may use the findInvoice method to retrieve a specific invoice:

$invoice = $user->findInvoice($invoiceId);

インボイス情報の表示Displaying Invoice Information

顧客へインボイスを一覧表示するとき、そのインボイスに関連する情報を表示するために、インボイスのヘルパメソッドを表示に利用できます。ユーザーが簡単にダウンロードできるよう、テーブルで全インボイスを一覧表示する例を見てください。When listing the invoices for the customer, you may use the invoice's helper methods to display the relevant invoice information. For example, you may wish to list every invoice in a table, allowing the user to easily download any of them:

<table>
    @foreach ($invoices as $invoice)
        <tr>
            <td>{{ $invoice->date()->toFormattedDateString() }}</td>
            <td>{{ $invoice->total() }}</td>
            <td><a href="/user/invoice/{{ $invoice->id }}">Download</a></td>
        </tr>
    @endforeach
</table>

インボイスPDF生成Generating Invoice PDFs

ルートやコントローラの中でdownloadInvoiceメソッドを使うと、そのインボイスのPDFダウンロードを生成できます。このメソッドはブラウザへダウンロードのHTTPレスポンスを正しく行うHTTPレスポンスを生成します。From within a route or controller, use the downloadInvoice method to generate a PDF download of the invoice. This method will automatically generate the proper HTTP response to send the download to the browser:

use Illuminate\Http\Request;

Route::get('user/invoice/{invoice}', function (Request $request, $invoiceId) {
    return $request->user()->downloadInvoice($invoiceId, [
        'vendor' => 'Your Company',
        'product' => 'Your Product',
    ]);
});

downloadInvoiceメソッドでは、3番目の引数としてオプションのカスタムファイル名も指定できます。このファイル名は自動的に".pdf"のサフィックスが付けられます。The downloadInvoice method also allows for an optional custom filename as the third parameter. This filename will automatically be suffixed with .pdf for you:

return $request->user()->downloadInvoice($invoiceId, [
    'vendor' => 'Your Company',
    'product' => 'Your Product',
], 'my-invoice');

課金失敗の処理Handling Failed Payments

サブスクリプションへの支払い、もしくは一回のみの課金は失敗することがあります。これが発生したことを知らせるため、CashierはIncompletePayment例外を投げます。この例外を補足した後の処理方法は、2つの選択肢があります。Sometimes, payments for subscriptions or single charges can fail. When this happens, Cashier will throw an IncompletePayment exception that informs you that this happened. After catching this exception, you have two options on how to proceed.

最初の方法は、その顧客を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 route that is registered via Cashier's service provider. So, you may catch the IncompletePayment exception and redirect to the payment confirmation page:

use Laravel\Cashier\Exceptions\IncompletePayment;

try {
    $subscription = $user->newSubscription('default', $planId)
                            ->create($paymentMethod);
} catch (IncompletePayment $exception) {
    return redirect()->route(
        'cashier.payment',
        [$exception->payment->id, 'redirect' => route('home')]
    );
}

支払い確認ページで顧客はクレジットカード情報の入力を再度促され、「3Dセキュア」のような追加のアクションがStripeにより実行されます。支払いが確認されたら、上記のようにredirect引数で指定されたURLへユーザーはリダイレクトされます。支払いを確認したら、そのユーザーは上記のようにredirectパラメータで指定されたURLへリダイレクトされます。リダイレクトにはURLへmessage(文字列)とsuccess(整数)クエリ文字列値が追加されます。On the payment confirmation page, the customer will be prompted to enter their credit card info 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.

別の方法として、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 a IncompletePayment exception is caught, you should still inform the user they will receive an email with further payment confirmation instructions.

不完全な支払いの例外は、Billableのユーザーに対するchargeinvoiceForinvoiceメソッドで投げられる可能性があります。スクリプションが処理される時、SubscriptionBuildercreateメソッドと、SubscriptionモデルのincrementAndInvoiceswapAndInvoiceメソッドは、例外を発生させる可能性があります。Payment exceptions may be thrown for the following methods: charge, invoiceFor, and invoice on the Billable user. When handling subscriptions, the create method on the SubscriptionBuilder, and the incrementAndInvoice and swapAndInvoice methods on the Subscription model may throw exceptions.

IncompletePaymentを拡張している支払い例外は現在2タイプ存在します。必要に応じユーザーエクスペリエンスをカスタマイズするために、これらを別々に補足できます。There are currently two types of payment exceptions which extend IncompletePayment. You can catch these separately if needed so that you can customize the user experience:

- `PaymentActionRequired`: これはStripeが支払いの確認と処理のために、追加の確認を要求していることを示します。 - `PaymentFailure`: これは利用可能な資金が無いなど、様々な理由で支払いが失敗したことを示します。

堅牢な顧客認証 (SCA)Strong Customer Authentication

皆さんのビジネスがヨーロッパを基盤とするものであるなら、堅牢な顧客認証 (SCA)規制を守る必要があります。これらのレギュレーションは支払い詐欺を防ぐためにEUにより2019年9月に課せられたものです。幸運なことに、StripeとCashierはSCA準拠のアプリケーション構築のために準備をしてきました。If your business is based in Europe you will need to abide by the 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.

Note: note 始める前に、StripeのPSD2とSCAのガイドと、新SCA APIのドキュメントを確認してください。{note} Before getting started, review Stripe's guide on PSD2 and SCA[https://stripe.com/guides/strong-customer-authentication] as well as their documentation on the new SCA APIs[https://stripe.com/docs/strong-customer-authentication].

支払い要求の追加確認Payments Requiring Additional Confirmation

SCA規制は支払いの確認と処理を行うため、頻繁に追加の検証を要求しています。これが起きるとCashierはPaymentActionRequired例外を投げ、この追加の検証が必要であるとあなたに知らせます。この例外をどのように処理するかは、失敗した支払いの処理方法のセクションをお読みください。SCA regulations often require extra verification in order to confirm and process a payment. When this happens, Cashier will throw a PaymentActionRequired exception that informs you that this extra verification is needed. More info on how to handle these exceptions be found here[#handling-failed-payments].

不十分と期日超過の状態Incomplete and Past Due State

支払いが追加の確認を必要とする場合そのサブクリプションは、stripe_statusデータベースカラムにより表されるincompletepast_due状態になります。Cashierは支払いの確認が完了するとすぐに、Webhookによりその顧客のサブスクリプションを自動的に有効にします。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 via a webhook as soon as payment confirmation is complete.

incompletepast_due状態の詳細は、追加のドキュメントを参照してください。For more information on incomplete and past_due states, please refer to our additional documentation[#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 payment 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のWebhookが設定されており、Stripeのダッシュボードでinvoice.payment_action_required Webhookが有効になっていることを確認してください。さらに、BillableモデルがLaravelのIlluminate\Notifications\Notifiableトレイトを使用していることも確認してください。To ensure that off-session payment confirmation notifications are delivered, verify that Stripe webhooks are configured[#handling-stripe-webhooks] for your application and the invoice.payment_action_required webhook is enabled in your Stripe dashboard. In addition, your Billable model should also use Laravel's Illuminate\Notifications\Notifiable trait.

Note: note 定期課金でなく、顧客が自分で支払った場合でも追加の確認が要求された場合は、その顧客に通知が送られます。残念ながら、Stripeはその支払いが手動や「非セッション時」であることを知る方法がありません。しかし、顧客は支払いを確認した後に支払いページを閲覧したら、「支払いが完了しました」メッセージを確認できます。その顧客は同じ支払いを2度行い、二重に課金されるアクシデントに陥ることを防ぐことができるでしょう。{note} Notifications will be sent even when customers are manually making a payment that requires additional confirmation. Unfortunately, there is no way for Stripe to know that the payment was done manually or "off-session". But, a customer will simply see a "Payment Successful" message if they visit the payment page after already confirming their payment. The customer will not be allowed to accidentally confirm the same payment twice and incur an accidental second charge.

Stripe SDKStripe SDK

CashierのオブジェクトはStripe SDKオブジェクト上にラップされています。Stripe SDKオブジェクトを直接操作したい場合は、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();

Stripeのサブスクリプションを直接更新するために、updateStripeSubscriptionも使用できます。You may also use the updateStripeSubscription method to update the Stripe subscription directly:

$subscription->updateStripeSubscription(['application_fee_percent' => 5]);

テスト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 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.

使用開始する前に、phpunit.xmlファイルへtestingバージョンのStripeシークレットを追加します。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とのやり取りは、Stripeテスト環境へ実際のAPIリクエストが送信されます。便宜上、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 / plans that you may then use during testing.

lightbulb">Tip!! クレジットカードの拒否や失敗など、さまざまな請求シナリオをテストするために、Stripeが提供しているさまざまなテストカード番号とトークンを使用できます。{tip} In order to test a variety of billing scenarios, such as credit card denials and failures, you may use the vast range of testing card numbers and tokens[https://stripe.com/docs/testing] provided by Stripe.

章選択

設定

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

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

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

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

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

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

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

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

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作