# PayPal によるサブスクリプションを設定する PayPal を使用したサブスクリプションの作成と請求の方法をご紹介します。 # Stripe がオンラインで提供するページ > This is a Stripe がオンラインで提供するページ for when payments-ui-type is stripe-hosted. View the full page at https://docs.stripe.com/billing/subscriptions/paypal?payments-ui-type=stripe-hosted. [GitHub のサンプル](https://github.com/stripe-samples/checkout-single-subscription)を確認するか[デモ](https://checkout.stripe.dev/checkout)をご覧ください。 このガイドを参照して、[PayPal](https://docs.stripe.com/payments/paypal.md) と *Checkout* (A low-code payment integration that creates a customizable form for collecting payments. You can embed Checkout directly in your website, redirect customers to a Stripe-hosted payment page, or create a customized checkout page with Stripe Elements) を使用する*サブスクリプション* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)を設定します。 [Checkout セッション](https://docs.stripe.com/api/checkout/sessions.md)は、顧客の購入意向の詳細を表します。顧客がサブスクリプションを開始する場合は、Checkout セッションを作成します。顧客が Checkout セッションにリダイレクトされると、、顧客が購入を完了できる支払いフォームが Stripe に表示されます。ユーザーが購入を完了すると、Stripe はユーザーをお客様のサイトにリダイレクトします。 > #### PayPal 継続支払いを有効にする > > Stripe は、ほとんどのユーザーが Stripe ダッシュボードで [PayPal 決済を有効](https://docs.stripe.com/payments/paypal/activate.md)にすると、継続支払いを自動的に有効にします。ただし、PayPal のポリシーと地域の制限により、ダッシュボードで PayPal 継続支払いを手動で[有効に](https://docs.stripe.com/payments/paypal/set-up-future-payments.md#enable-recurring-payments)しなければならない場合があります。 ## Stripe を設定する [サーバ側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 アプリケーションから Stripe APIにアクセスするには、公式ライブラリを使用してください。 #### Ruby ```bash # Available as a gem sudo gem install stripe ``` ```ruby # If you use bundler, you can add this line to your Gemfile gem 'stripe' ``` ## 継続支払いの製品と料金の作成 > Prices API は、Stripe で 1 回限りの購入およびサブスクリプションをモデル化する方法を統一します。Prices API を使用しない既存のシステムも引き続き[サポートされます](https://support.stripe.com/questions/prices-api-and-existing-checkout-integrations)が、一部の Checkout 機能では Prices のみがサポートされます。Prices API へのアップグレードについては、[移行ガイド](https://docs.stripe.com/payments/checkout/migrating-prices.md)を参照してください。 Checkout を使用するには、まず*商品* (Products represent what your business sells—whether that's a good or a service)と*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)を作成する必要があります。物品やサービスレベルごとに商品を作成します。各商品の料金体系は 1 つ以上の価格で示されます。 たとえば、10 USD/月、100 USD/年、9 EUR/月、90 EUR/年の、4 つの「価格」が設定されたソフトウェア「商品」を作成できます。これにより、対象商品の詳細を変更することなく、価格を変更したり追加したりできるます。商品と価格は、[API を通じて](https://docs.stripe.com/api/prices.md)、または [Stripe ダッシュボード](https://dashboard.stripe.com/products)を使用して作成できます。 価格が購入時に決定される場合 (顧客が寄付金額を設定する場合など)、または事前に価格を作成しない選択をした場合は、Checkout セッションの作成時に[価格をインライン](https://docs.stripe.com/billing/subscriptions/paypal.md#creating-prices-inline)で作成することができます。 #### ダッシュボード 商品の設定を開始する前に、サンドボックスを使用していることを確認してください。次に、販売する予定の商品とサービスを定義します。新しい商品と価格を作成するには、以下を実行します。 - ダッシュボードで [商品](https://dashboard.stripe.com/products) セクションに移動します - **商品を追加**をクリックします - 価格を設定する際に「継続」を選択します - 料金プランを設定する 継続支払いの商品ごとに異なるパラメータを設定して、複数の料金プランを定義できます。各料金には ID が生成され、これを決済プロセス中に参照できます。 > サンドボックスで作成された商品は本番環境にコピーできるため、再度作成する必要はありません。ダッシュボードの商品詳細表示で、右上隅にある **本番環境にコピー** をクリックします。この操作はサンドボックスで作成された各商品に対して 1 回のみ実行できます。テスト環境の商品に対する以降の更新は、本番環境の商品には反映されません。 #### API API を使用して基本的な [Product (商品)](https://docs.stripe.com/api/products.md) を作成するには、`name` フィールドのみが必要です。指定した商品の `name`、`description`、および `images` が Checkout で顧客に表示されます。 ```curl curl https://api.stripe.com/v1/products \ -u "<>:" \ -d "name=Blue banana" ``` 次に、[Price (価格)](https://docs.stripe.com/api/prices.md) を作成して、商品の請求額と請求頻度を定義します。これには商品のコスト、使用通貨および請求期間も含まれます。 #### curl ```bash curl https://api.stripe.com/v1/prices \ -u <>: \ -d "product"="{{ PRODUCT_ID }}" \ -d "unit_amount"=1000 \ -d "currency"="eur" \ -d "recurring[interval]=month" ``` この料金 ID は、Checkout を使用して支払いプロセスを開始するときに、商品を参照する手段になります。 ## Checkout セッションを作成する [クライアント側] [サーバ側] サーバー側のエンドポイントを呼び出して Checkout セッションを作成する購入ボタンをウェブサイトに追加します。 ```html Checkout
``` ### Checkout セッションのパラメーター 使用できるパラメーターの完全なリストについては、[Checkout セッションの作成](https://docs.stripe.com/api/checkout/sessions/create.md)を参照してください。 既存の [Price](https://docs.stripe.com/api/prices.md) の ID を使用して Checkout セッションを作成します。モードが `subscription` に設定されており、1 つ以上の継続価格を渡すことを確認してください。継続価格に加えて、1 回限りの価格を追加できます。Checkout セッションを作成したら、レスポンスで返された [URL](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-url) に顧客をリダイレクトします。 #### cURL ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"="paypal" \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \ -d "mode"="subscription" \ -d "success_url"="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" \ ``` 顧客が支払いを正常に完了すると、`success_url` (支払いが成功したことを顧客に通知するウェブページ) にリダイレクトされます。上記の例のように、`success_url` に `{CHECKOUT_SESSION_ID}` テンプレート変数を含めることで、成功ページでセッション ID が使用できるようになります。 デフォルトでは、Checkout セッションは作成後 24 時間で期限切れとなります。 > 決済開始の検出にあたっては、`success_url` へのリダイレクトのみに依存しないでください。その理由は次のとおりです。 > > - 悪意を持つユーザが、支払いをせずに `success_url` に直接アクセスし、商品やサービスにアクセスできるようになる可能性があります。 - 決済が成功した後で、顧客が `success_url` にリダイレクトされる前にブラウザタブを閉じる可能性あります。 ## 支払いが成功したことを確認する > 買い手が PayPal を使用して Stripe でサブスクリプションを確認すると、Stripe と PayPal の両方から買い手に領収書が届きます。 顧客が支払いを完了すると、`success_url` として指定された URL にリダイレクトされます。この URL は通常、顧客に支払いが成功したことを知らせるお客様の Web サイト上のページです。 ダッシュボード、カスタム *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests)、またはサードパーティーのプラグインを使用して、顧客に注文の確認メールを送信したり、売上をデータベースに記録したり、配送ワークフローを開始するなどの、支払い後のイベントを処理します。 #### ダッシュボード 成功した支払いは、ダッシュボードの[支払いの一覧](https://dashboard.stripe.com/payments)に表示されます。支払いをクリックすると、支払いの詳細ページに移動します。**Checkout サマリー**セクションには、請求先情報と購入された商品のリストが記載されています。これらを使用して、注文を手動でフルフィルメントすることができます。 ![Checkout サマリー](https://b.stripecdn.com/docs-statics-srv/assets/source.16d3029596357c80a8efdbbfe106108a.png) > Stripe は顧客が支払いに成功するたびにお客様にメール通知を送信し、今後受領する支払いの最新情報を把握できるようサポートします。ダッシュボードを使用して[メール通知を設定](https://dashboard.stripe.com/settings/user)します。 #### Webhook プログラムで支払い後のイベントを処理するように [Webhook を設定](https://docs.stripe.com/webhooks.md)します。Webhook を最も迅速にローカルで開発およびテストするには、[Stripe CLI](https://docs.stripe.com/stripe-cli.md) を使用します。インストールすると、サーバーにイベントを転送できるようになります。 ```bash stripe listen --forward-to localhost:4242/webhook Ready! Your webhook signing secret is '{{WEBHOOK_SIGNING_SECRET}}' (^C to quit) ``` [イベントを受信したことを確認](https://docs.stripe.com/webhooks.md#acknowledge-events-immediately)すると、Webhook エンドポイントによって顧客が `success_url` にリダイレクトされます。エンドポイントが停止していたり、イベントが正しく確認されない場合、顧客は支払い成功の 10 秒後に `success_url` にリダイレクトされます。 次のエンドポイントの例は、イベントを確認および処理する方法を示しています。 #### Ruby ```ruby # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. # Find your keys at https://dashboard.stripe.com/apikeys. Stripe.api_key = '<>' # You can find your endpoint's secret in your webhook settings endpoint_secret = 'whsec_...' # Using Sinatra post '/webhook' do payload = request.body.read event = nil # Verify webhook signature and extract the event # See https://stripe.com/docs/webhooks#verify-events for more information. sig_header = request.env['HTTP_STRIPE_SIGNATURE'] begin event = Stripe::Webhook.construct_event( payload, sig_header, endpoint_secret ) rescue JSON::ParserError => e # Invalid payload status 400 return rescue Stripe::SignatureVerificationError => e # Invalid signature status 400 return end # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed' session = event['data']['object'] # Fulfill the purchase... handle_checkout_session(session) end status 200 end ``` [Zapier](https://stripe.com/works-with/zapier) などのプラグインを使用すると、Stripe の支払いからの情報を利用して購入のフルフィルメントシステムを自動更新できます。 プラグインで対応可能な自動化の例の一部を以下に挙げます。 - 支払いの成功に対応して、注文の追跡に使用されるスプレッドシートを更新する - 支払いの成功に対応して、在庫管理システムを更新する - メールまたはチャットアプリケーションを使用して、社内のカスタマーサービスチームへの通知をトリガーする ## 組み込みをテストする [テスト API キー](https://docs.stripe.com/keys.md#test-live-modes) を使用して PayPal の実装をテストするには、リダイレクトページを表示します。リダイレクトページで支払いを認証することにより、支払い成功のケースをテストできます。PaymentIntent は `requires_action` から `succeeded` に移行します。 ユーザが認証に失敗するケースをテストするには、テスト API キーを使用してリダイレクトページを表示します。リダイレクトページで **テスト支払い失敗** をクリックします。PaymentIntent は、`requires_action` から `requires_payment_method` に移行します。 ## Optional: 一回限りの設定手数料の追加 [サーバ側] `subscription` モードには継続支払いの料金を渡すだけでなく、1 回限りの料金も追加できます。これらは、サブスクリプションによって作成される初回の*請求書* (Invoices are statements of amounts owed by a customer. They track the status of payments from draft through paid or otherwise finalized. Subscriptions automatically generate invoices, or you can manually create a one-off invoice)にのみ記載されます。これは、サブスクリプションに付随する設定手数料やその他の 1 回限りの手数料の追加に便利です。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"="paypal" \ -d "line_items[0][price]"="{{RECURRING_PRICE_ID}}" \ -d "line_items[0][quantity]"=1 \ -d "line_items[1][price]"="{{ONE_TIME_PRICE_ID}}" \ -d "line_items[1][quantity]"=1 \ -d "mode"="subscription" \ -d "success_url"="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" ``` ## Optional: 価格と商品をインラインで作成する [サーバ側] 既存の料金 ID に渡すだけではなく、Checkout セッションの作成でアイテムの料金を定義することもできます。まず、[Product (商品)](https://docs.stripe.com/api/products.md) を定義します。次に、商品 ID を使用し、それを `unit_amount`、`currency`、`recurring` の詳細とともに [price_data](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-price_data) に渡して、Checkout セッションを作成します。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"=paypal \-d line_items[0][price_data][unit_amount]=5000 \ -d line_items[0][price_data][currency]=eur\ -d line_items[0][price_data][product]="{{PRODUCT_ID}}" \ -d line_items[0][price_data][recurring][interval]=month \ -d line_items[0][quantity]=1 \ -d mode=subscription \ -d success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" \ ``` また、商品もインラインで作成する必要がある場合は、[product_data](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-price_data-product_data) を使用して作成できます。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"=paypal \-d "line_items[][price_data][currency]"=eur\ -d "line_items[][price_data][product_data][name]"=T-shirt \ -d "line_items[][price_data][unit_amount]"=2000 \ -d "line_items[][quantity]"=1 \ -d "mode"="subscription" \ -d success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" \ ``` ## Optional: 既存の顧客 [サーバ側] 顧客を表す *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) オブジェクトを以前に作成している場合、Checkout Session を作成する際に [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) 引数を使用してその顧客 ID を渡します。こうすることで、そのセッション中に作成されたすべてのオブジェクトが正しい Customer オブジェクトに関連付けられます。 顧客 ID を渡すと、Stripe は Customer オブジェクトに保管されたメールアドレスを使用して、Checkout ページのメールフィールドに事前入力します。顧客が Checkout ページでメールアドレスを変更すると、支払いの成功後に Customer オブジェクトの該当項目が更新されます。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "customer"="{{CUSTOMER_ID}}" \ -d "payment_method_types[]"="paypal" \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \ -d "mode"="subscription" \ -d "success_url"="https://example.com/success" ``` ## Optional: 顧客データの事前入力 [サーバ側] すでに顧客のメールを収集していて、それを Checkout セッションで事前に入力するには、Checkout セッションの作成時に [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) を渡します。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \-d customer_email="customer@example.com" \ -d "payment_method_types[]"=paypal \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \ -d mode=subscription \ -d success_url="https://example.com/success" \ ``` ## Optional: トライアルの処理 [サーバ側] Checkout セッションで [trial_end](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-subscription_data-trial_end) または [trial_period_days](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-subscription_data-trial_period_days) を使用して、トライアル期間の日数を指定できます。この例では、`trial_period_days` を使用して 30 日間のトライアルを含むサブスクリプションの Checkout セッションを作成します。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"=paypal \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \-d "subscription_data[trial_period_days]"=30 \ -d mode=subscription \ -d success_url="https://example.com/success?session_id={CHECKOUT_SESSION_ID}" \ ``` Checkout では、トライアルを含むサブスクリプションに対して以下の情報が自動的に表示されます。 - トライアル期間 - トライアル期限満了後の支払いの頻度と金額 法令遵守要件の詳細については、[法令遵守要件の管理](https://docs.stripe.com/billing/subscriptions/trials/manage-trial-compliance.md)または[サポート](https://support.stripe.com/questions/2020-visa-trial-subscription-requirement-changes-guide)ガイドを参照してください。 ## Optional: 税率 [サーバ側] Checkout セッションで[税率](https://docs.stripe.com/billing/taxes/tax-rates.md) (消費税、VAT、GST、その他) を指定し、*サブスクリプション* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)に税金を適用できます。 - 顧客が決済フロープロセスを開始する前に、顧客に請求する正確な税率を把握している場合は、固定税率を使用します (イギリスの顧客にのみ販売し、常に 20% の VAT を課税する場合など)。 - *Prices* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions) API では、請求する税率を決定する前に顧客の詳細情報 (請求先住所、配送先住所など) が必要な場合に、動的税率を使用できます。動的税率では、地域ごとに異なる複数の税率 (イギリスの顧客には 20% の VAT、アメリカ・カリフォルニア州の顧客には 7.25% の売上税など) を作成でき、Stripe は顧客の居住地を、これらの税率のいずれかとマッチングします。 #### 固定税率 Checkout で開始したサブスクリプションにデフォルトの税率を適用するには、[subscription_data.default_tax_rates](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-subscription_data-default_tax_rates) を設定します。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"=paypal \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \-d "subscription_data[default_tax_rates][]"="{{TAX_RATE_ID}}" \ -d mode=subscription \ -d success_url="https://example.com/success" \ ``` また、[line_items.tax_rates](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-tax_rates) あるいは [subscription_data.items.tax_rates](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-subscription_data-items-tax_rates) を指定して、特定のプランまたはインボイスのラインアイテムに税率を適用することもできます。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"="paypal" \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \-d "line_items[][tax_rates][0]"="{{TAX_RATE_ID}}" \ -d "mode"="subscription" \ -d "success_url"="https://example.com/success" \ ``` #### 動的税率 [Tax Rate (税率)](https://docs.stripe.com/api/tax_rates/object.md) の配列を [line_items.dynamic_tax_rates](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-dynamic_tax_rates) に渡します。各 Tax Rate には[サポート対象の](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-dynamic_tax_rates) `country` が設定されている必要があり、アメリカの場合は `state` も必要です。 このリストでは、税率を顧客の[配送先住所](https://docs.stripe.com/payments/collect-addresses.md)または請求先住所と突き合わせます。請求する税率を決定する際は、請求先住所よりも配送先住所が優先されます。 配送先住所や請求先住所を収集していない場合は、税率の決定に顧客の国 (および該当する場合には郵便番号) が使用されます。顧客の配送先住所、請求先住所、または国に一致する税率を渡していない場合、税率は適用されません。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"="paypal" \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \-d "line_items[][dynamic_tax_rates][]"="{{FIRST_TAX_RATE_ID}}" \ -d "line_items[][dynamic_tax_rates][]"="{{SECOND_TAX_RATE_ID}}" \ -d "mode"="subscription" \ -d "success_url"="https://example.com/success" \ ``` > [subscription_data.default_tax_rates](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-subscription_data-default_tax_rates) および [line_items.tax_rates](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-tax_rates) を [line_items.dynamic_tax_rates](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-line_items-dynamic_tax_rates) と組み合わせて使用することはできません。 Stripe のデータエクスポート機能を使用して、送金に必要となる定期的な申告書に入力することができます。詳細については、[納税申告および送金](https://docs.stripe.com/billing/taxes/tax-rates.md#remittance)を参照してください。 ## Optional: クーポンの追加 [サーバ側] Checkout セッションでは、[discounts (割引)](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-discounts) を設定することで、サブスクリプションに[クーポン](https://docs.stripe.com/billing/subscriptions/coupons.md)を適用できます。このクーポンは、顧客の他のクーポンよりも優先されます。[既存の顧客](https://docs.stripe.com/billing/subscriptions/paypal.md#handling-existing-customers)でサブスクリプションを作成している場合、その顧客に関連付けられたクーポンがサブスクリプションの*インボイス* (Invoices are statements of amounts owed by a customer. They track the status of payments from draft through paid or otherwise finalized. Subscriptions automatically generate invoices, or you can manually create a one-off invoice)に適用されます。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"=paypal \ -d "line_items[][price]"="{{PRICE_ID}}" \ -d "line_items[][quantity]"=1 \-d "discounts[][coupon]"="{{COUPON_ID}}" \ -d "mode"="subscription" \ -d success_url="https://example.com/success" \ ``` ### 顧客に表示されるプロモーションコードを追加する また、ユーザーが引き換え可能な[プロモーションコード](https://docs.stripe.com/billing/subscriptions/coupons.md#promotion-codes)は、Checkout セッションで [allow_promotion_codes](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-allow_promotion_codes) パラメーターを使用して有効にできます。Checkout セッションで `allow_promotion_codes` が有効になっている場合、Checkout には顧客が利用するためのプロモーションコードの入力欄が表示されます。[クーポン](https://docs.stripe.com/billing/subscriptions/coupons.md)およびプロモーションコードは、顧客が Checkout で引き換えられるようにダッシュボードまたは API で作成します。 #### curl ```bash curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d "payment_method_types[]"="paypal" \ -d "line_items[0][price_data][unit_amount]"=2000 \ -d "line_items[0][price_data][currency]"="eur" \ -d "line_items[0][price_data][product]={{PRODUCT_ID}}" \ -d "line_items[0][price_data][recurring][interval]=month" \ -d "line_items[0][quantity]"=1 \-d "allow_promotion_codes"="true" \ -d "mode"="subscription" \ -d "success_url"="https://example.com/success" \ ``` ## See also - [自社のシステムを構築する](https://docs.stripe.com/payments/checkout/customization.md) - [カスタマーポータルでサブスクリプションを管理する](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=checkout&ui=stripe-hosted) # ダイレクト API > This is a ダイレクト API for when payments-ui-type is direct-api. View the full page at https://docs.stripe.com/billing/subscriptions/paypal?payments-ui-type=direct-api. このガイドを使用して、支払い方法として [PayPal](https://docs.stripe.com/payments/paypal.md) を使用する*サブスクリプション* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)を設定します。 ## Before you begin - Stripe で PayPal サブスクリプションを受け付けるには、ダッシュボードで PayPal 継続支払いを[有効にする必要](https://docs.stripe.com/payments/paypal/set-up-future-payments.md?platform=web#enable-recurring-payments)があります。 - この機能は、特定の企業の店舗でのみ利用できます。[企業の店舗を確認して、利用資格を確認](https://docs.stripe.com/payments/paypal.md)してください。 ## 商品と価格を作成する [ダッシュボード] [Products (商品)](https://docs.stripe.com/api/products.md) は、販売しているアイテムまたはサービスを表します。[Prices (価格)](https://docs.stripe.com/api/prices.md) は、商品の価格と請求頻度を定義します。これには、商品の価格、受け付ける通貨、および 1 回限りの支払いか継続支払いかが含まれます。商品と価格が数個のみの場合は、ダッシュボードでそれらを作成および管理します。 このガイドでは、例としてストックフォトサービスを使用し、15 EUR の月次サブスクリプションを顧客に請求します。これをモデル化するには、次のようにします。 1. [商品](https://dashboard.stripe.com/products?active=true)ページに移動し、**商品を作成**をクリックします。 1. 商品の**名前**を入力します。オプションで**説明**を追加して、商品の画像をアップロードできます。 1. **商品税コード**を選択します。[商品税コード](https://docs.stripe.com/tax/tax-codes.md)の詳細をご確認ください。 1. **継続**を選択します。次に、価格に**15**を入力し、通貨として**\**を選択します。 1. **価格に税金を含める**かどうかを選択します。[税金設定](https://dashboard.stripe.com/test/settings/tax)のデフォルト値を使用するか、値を手動で設定できます。この例では、**自動**を選択します。 1. **請求期間**で**月次**を選択します。 1. **その他の料金体系オプション**をクリックします。次に、この例の料金体系モデルとして**定額**を選択します。[定額料金](https://docs.stripe.com/products-prices/pricing-models.md#flat-rate)とその他の[料金体系モデル](https://docs.stripe.com/products-prices/pricing-models.md)の詳細をご確認ください。 1. 将来的に特定の価格を整理、クエリ、更新するために、内部**価格の説明**と[検索キー](https://docs.stripe.com/products-prices/manage-prices.md#lookup-keys) 追加します。 1. **次へ**をクリックします。次に、**商品を追加**をクリックします。 商品と価格を作成したら、価格 ID を記録しておき、後続のステップで使用できるようにします。ID は料金体系ページで `price_G0FvDp6vZvdwRZ` のように表示されます。 ## 設定前に Customer を作成または取得する [サーバ側] 以降の支払いに PayPal の支払い方法を再利用するには、*Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) に関連付けます。 お客様のビジネスで顧客がアカウントを作成するときに、Customer オブジェクトを作成します。Customer オブジェクトの ID を、独自の内部的な顧客の表記に関連付けることにより、保存された支払い方法の詳細を後で取得して使用できます。顧客がアカウントを作成していない場合でも、すぐに Customer オブジェクトを作成し、後でこのオブジェクトを顧客のアカウントの内部表記に関連付けることができます。 ```curl curl -X POST https://api.stripe.com/v1/customers \ -u "<>:" ``` ## SetupIntent を作成する [サーバ側] [SetupIntent (支払い方法設定インテント)](https://docs.stripe.com/api/setup_intents.md) は、将来の支払いに備えて顧客の支払い方法を設定するという意図を示し、そのステップを追跡するオブジェクトです。 [payment_method_types](https://docs.stripe.com/api/setup_intents/create.md#create_setup_intent-payment_method_types) を `paypal` に設定してサーバーで [SetupIntent (支払い方法設定インテント)](https://docs.stripe.com/api/setup_intents.md) を作成し、*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)の [id](https://docs.stripe.com/api/customers/object.md#customer_object-id) を指定します。 ```curl curl https://api.stripe.com/v1/setup_intents \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "payment_method_types[]=paypal" \ -d "payment_method_data[type]=paypal" ``` SetupIntent オブジェクトには、[client_secret](https://docs.stripe.com/api/setup_intents/object.md#setup_intent_object-client_secret) が含まれています。これは、買い手を PayPal にリダイレクトして同意書の承認を得る際に、クライアント側で Stripe に渡す必要がある一意のキーです。 ## 顧客をリダイレクトする [クライアント側] 顧客が将来の支払いに備えて PayPal アカウントを設定する際に、[Stripe.js](https://docs.stripe.com/js.md) を使用して SetupIntent を確定することをお勧めします。Stripe.js は、決済フローを構築するための Stripe の基本的な JavaScript ライブラリです。これを使用することで、以下で説明するリダイレクトなどの複雑な処理を自動化でき、将来、お客様のシステムを他の支払い方法に簡単に拡張できます。 Stripe.js スクリプトを決済ページに含めるには、このスクリプトを HTML ファイルの head に追加します。 ```html Checkout ``` 決済ページで以下の JavaScript を使用して、Stripe.js のインスタンスを作成します。 ```javascript // Set your publishable key. Remember to change this to your live publishable key in production! // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>', {} ); ``` クライアント側で設定を確認するには、ステップ 3 で作成した SetupIntent オブジェクトの client secret を渡します。 client secret は、Stripe API リクエストを認証する API キーとは異なります。client secret は決済を完了できるため、慎重に取り扱う必要があります。ログに記録したり、URL に埋め込んだり、顧客以外に漏洩したりしないでください。 ### PayPal 設定を確認する 将来の支払いに PayPal アカウントを使用することを許可するため、顧客は PayPal 請求契約ページにリダイレクトされ、そのページで契約を承認してから、お客様のウェブサイトに戻る必要があります。[stripe.confirmPayPalSetup](https://docs.stripe.com/js/setup_intents/confirm_paypal_setup) を使用して、お客様のページからのリダイレクトを処理して設定を完了します。この機能に `return_url` を追加し、ユーザーが PayPal のウェブサイトで請求契約を承認した後にリダイレクトされる場所を指定します。 ```javascript // Redirects away from the client const {error} = await stripe.confirmPayPalSetup( '{{SETUP_INTENT_CLIENT_SECRET}}', { return_url: 'https://example.com/setup/complete', mandate_data: { customer_acceptance: { type: 'online', online: { infer_from_client: true } } }, } ); if (error) { // Inform the customer that there was an error. } ``` 決済手段の支払人 ID と請求契約 ID は、[payment_method_details](https://docs.stripe.com/api/mandates/object.md#mandate_object-payment_method_details-paypal) プロパティで生成される [Mandate (同意書)](https://docs.stripe.com/api/mandates/.md) にあります。買い手のメールアドレスと支払人 ID は、[PaymentMethod (決済手段)](https://docs.stripe.com/api/payment_methods.md) の [paypal](https://docs.stripe.com/api/payment_methods/object.md#payment_method_object-paypal) プロパティでも確認できます。 | フィールド | 値 | | ---------------------- | -------------------------------------------------------------------- | | `payer_email` | PayPal アカウントの支払人のメールアドレス。 | | `payer_id` | 支払人の PayPal アカウントの一意の ID。 | | `billing_agreement_id` | PayPal 請求契約 ID (BAID)。これは、PayPal によって生成される ID で、ビジネスと顧客の間の同意書に相当します。 | ## Webhook を監視する [サーバ側] 顧客が請求契約を正常に承認したことを確認するには、顧客が支払いステータスページに戻るのを期待するのではなく、[Webhook](https://docs.stripe.com/payments/payment-intents/verifying-status.md#webhooks) などの方法を使用します。利用者が請求契約を正常に承認すると、SetupIntent は [setup_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-setup_intent.succeeded) *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) イベントを送信します。請求契約の承認が正常に行われなかった場合、SetupIntent は [setup_intent.setup_failed](https://docs.stripe.com/api/events/types.md#event_types-setup_intent.setup_failed) Webhook イベントを送信し、`requires_payment_method` ステータスに戻ります。利用者が PayPal アカウントから請求契約を取り消すと、[mandate.updated](https://docs.stripe.com/api/events/types.md#event_types-mandate.updated) が送信されます。 ## サブスクリプションを作成する [サーバ側] 料金と顧客を指定して、[Subscription (サブスクリプション)](https://docs.stripe.com/api/subscriptions.md) を作成します。 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d customer=cus_Gk0uVzT2M4xOKD \ -d default_payment_method=pm_1F0c9v2eZvKYlo2CJDeTrB4n \ -d "items[0][price]=price_F52b2UdntfQsfR" \ -d "expand[0]=latest_invoice.confirmation_secret" \ -d off_session=true ``` [デフォルトの支払い方法](https://docs.stripe.com/api/customers/create.md#create_customer-invoice_settings-default_payment_method)が設定されているため、サブスクリプションを作成すると、自動的に顧客に対して請求が行われます。支払いが完了すると、[Stripe ダッシュボード](https://dashboard.stripe.com/test/subscriptions)内のステータスが**有効**に変わります。以前作成した料金によって、以降の請求が決定されます。 ## サブスクリプションステータスを管理する [クライアント側] 初回の支払いが完了すると、サブスクリプションのステータスは `active` になり、それ以上のアクションは不要になります。支払いが失敗した場合は、ステータスが [自動回収設定](https://docs.stripe.com/invoicing/automatic-collection.md) で設定された **Subscription status** に変わります。支払いが失敗した場合は顧客にその旨を通知して、[別の支払い方法で請求してください](https://docs.stripe.com/billing/subscriptions/overview.md#requires-payment-method)。 ## 定期支払いを更新 [サーバ側] サブスクリプションを更新する場合、`off_session=true` を指定する必要があります。そうしないと、新しい支払いでは、確定のためにユーザーを PayPal にリダイレクトする必要があります。たとえば、サブスクリプションに含まれるアイテムの数量を変更する場合、以下を使用できます。 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d customer=cus_Gk0uVzT2M4xOKD \ -d default_payment_method=pm_1F0c9v2eZvKYlo2CJDeTrB4n \ -d "items[0][price]=price_F52b2UdntfQsfR" \ -d "items[0][quantity]=2" \ -d off_session=true ``` ## 組み込みをテストする [テスト API キー](https://docs.stripe.com/keys.md#test-live-modes) を使用して PayPal の実装をテストするには、リダイレクトページを表示します。リダイレクトページで支払いを認証することにより、支払い成功のケースをテストできます。PaymentIntent は `requires_action` から `succeeded` に移行します。 ユーザが認証に失敗するケースをテストするには、テスト API キーを使用してリダイレクトページを表示します。リダイレクトページで **テスト支払い失敗** をクリックします。PaymentIntent は、`requires_action` から `requires_payment_method` に移行します。 ## Optional: 請求期間の設定 デフォルトでは、サブスクリプションの作成時にその請求サイクルが自動的に設定されます。たとえば、顧客が 9 月 7 日に月額プランのサブスクリプションに登録した場合、それ以降毎月 7 日に請求されます。一部のビジネスでは、顧客に対してサイクルごとに同時に請求できるように、請求サイクルの手動設定を希望する場合があります。[billing cycle anchor](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-billing_cycle_anchor) 引数を使用すると、これを実現できます。 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "items[0][price]={{PRICE_ID}}" \ -d billing_cycle_anchor=1611008505 ``` 請求サイクルを手動で設定すると、作成されたサブスクリプションと請求サイクルのアンカーとの間の期間の分として比例配分 (日割り / 秒割り計算) された金額が顧客に自動的に請求されます。この期間分を顧客に請求しない場合は、[proration_behavior](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-proration_behavior) 引数を `none` に設定できます。請求サイクルのアンカーを[トライアル期間](https://docs.stripe.com/billing/subscriptions/paypal.md#trial-periods)と組み合わせ、商品への無料アクセスをユーザーに提供してから、比例配分された金額を請求することもできます。 ## Optional: サブスクリプションのトライアル 無料トライアルを使用すると、顧客は商品に一定期間無料でアクセスできます。無料トライアルの使用は、[proration_behavior](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-proration_behavior) を `none` に設定した場合とは異なり、無料の継続期間をカスタマイズできます。トライアル期間を設定するには、[trial end](https://docs.stripe.com/api/subscriptions/create.md#create_subscription-trial_end) にタイムスタンプを渡します。 ```curl curl https://api.stripe.com/v1/subscriptions \ -u "<>:" \ -d "customer={{CUSTOMER_ID}}" \ -d "items[0][price]={{PRICE_ID}}" \ -d trial_end=1610403705 ``` 必要に応じて、[請求サイクルのアンカー](https://docs.stripe.com/billing/subscriptions/paypal.md#billing-cycle)を無料トライアルと組み合わせることができます。たとえば、現在が 9 月 15 日だとした場合、顧客に 7 日間の無料トライアルを付与してから、通常の請求サイクルを 10 月 1 日に開始するとします。この場合 9 月 22 日に無料トライアルが終了し、請求サイクルのアンカーが 10 月 1 日となるように設定できます。これにより顧客には 7 日間の無料トライアルが付与され、トライアル終了日から 10 月 1 日までの期間については比例配分を適用した金額が請求されます。10 月 1 日に、初めての完全な請求サイクルとして、顧客は通常のサブスクリプション金額を請求されます。 ## Optional: 保存された PayPal アカウントを削除する [detach](https://docs.stripe.com/api/payment_methods/detach.md) API を使用して、顧客が決済手段として保存した PayPal アカウントを削除できます。PayPal の決済手段の関連付けを解除すると、[同意書](https://docs.stripe.com/api/mandates.md)が取り消され、さらに関連付けられた PayPal 請求契約をキャンセルするための PayPal API の呼び出しも行われます。 ```curl curl -X POST https://api.stripe.com/v1/payment_methods/{{PAYMENT_METHOD_ID}}/detach \ -u "<>:" ```