# 事前構築済みの決済ページを使用して、iOS でデジタル商品の決済を受け付けます ブラウザで Stripe Checkout を開き、アプリ内デジタル商品または Subscriptions を販売します。 > Stripeの*マーチャントオブレコード* (The legal entity responsible for facilitating the sale of products to a customer that handles any applicable regulations and liabilities, including sales taxes. In a Connect integration, it can be the platform or a connected account)ソリューションである [Managed Paymentsを使用して、同様の連携を構築する方法 ](https://docs.stripe.com/payments/managed-payments/set-up-mobile.md) をご確認ください。 アメリカでデジタル商品、コンテンツ、サブスクリプションを販売する iOS アプリでは、顧客を外部の決済画面にリダイレクトして、[Stripe Checkout](https://docs.stripe.com/payments/checkout.md) を使用して決済を受け付けることができます。アプリのダウンロード元のストアフロントを検出するには、[StoreKit の Storefront](https://developer.apple.com/documentation/storekit/storefront) プロパティを使用します。このガイドでは、[Stripe がホストする決済ページ](https://docs.stripe.com/checkout/quickstart.md)に顧客をリダイレクトして、iOS アプリでクレジット購入の決済を受け付ける方法を説明します。 アメリカのAndroid開発者は、サードパーティーの決済代行業者を利用してアプリ内で直接決済を処理できます。Stripeでアプリ内で直接決済を受け付けるには、[アプリ内決済](https://docs.stripe.com/payments/mobile.md)をご覧ください。 このガイドでは、iOS 開発者がアプリ内デジタル商品を販売するプロセスのみを説明します。以下を販売する場合は、[ネイティブ アプリ支払いガイド](https://docs.stripe.com/payments/mobile.md)を使用してください。 - 物品アイテム - アプリ外での使用を目的とする商品やサービス - 2 人の個人間の、対人リアルタイムサービス このガイドでは以下の方法について説明します。 - 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)、*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)を使用したクレジットパッケージのモデル化。 - *ユニバーサルリンク* (Use Universal links on iOS and macOS to link directly to in-app content. They're standard HTTPS links, so the same URL works for your website and your app)の使用による Checkout からアプリへの直接のリダイレクト。 - *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) のモニタリングによる顧客のアプリ内通貨残高の更新。 ![1 回限りの支払い](https://b.stripecdn.com/docs-statics-srv/assets/one_time_hero.e9d6a86d35345553ed008f0bd442c6b2.png) 1 回限りの決済のためにアプリからリンクアウトする ![継続支払い](https://b.stripecdn.com/docs-statics-srv/assets/recurring_hero.6dff3f5076ca832cde57ac0757110291.png) 定期決済やサブスクリプション決済のためのアプリ外リンク ## 仕組み 次の図は、アプリからウェブへの決済フロー全体の概要を示しています。 アプリ内購入向けの、アプリからウェブへの決済フローの概要 (See full diagram at https://docs.stripe.com/mobile/digital-goods/checkout) ## 対象範囲外の内容 このガイドでは、既存のアプリ内購入システムと並列的に Stripe Checkout を追加する方法を説明します。以下はこのガイドの対象範囲には含まれません。 - ユーザーの認証。既存の認証プロバイダーがない場合には、[Sign in with Apple (Apple にサインイン)](https://developer.apple.com/sign-in-with-apple/) や [Firebase Authentication](https://firebase.google.com/docs/auth) などのサードパーティープロバイダーを使用できます。 - ネイティブのアプリ内購入。StoreKit を使用してアプリ内購入を実装するには、[Apple のアプリ内課金](https://developer.apple.com/in-app-purchase/) ガイドをご覧ください。 ## 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' ``` 次に Stripe CLI をインストールします。CLI は必要な [Webhook](https://docs.stripe.com/webhooks.md#test-webhook) のテストを提供します。これを実行することで商品と価格を作成できます。 その他のインストールオプションについては、[Stripe CLI を使ってみる](https://docs.stripe.com/stripe-cli.md)をご覧ください。 ## 商品および価格を作成する ダッシュボードまたは Stripe CLI で*商品* (Products represent items your customer can subscribe to with a Subscription. An associated Price object describes the pricing and other terms of the subscription) とその*価格* (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 回限りの価格を使用してデジタル商品をモデル化し、継続価格を使用してサブスクリプションをモデル化できます。**顧客が支払い金額を選択する** を選択して、顧客が希望する金額を支払えるようにすることもできます (たとえば、購入するクレジットの数を決定するなど)。 この例では、1 つの「商品」と「価格」を使用して、100 コインのバンドルを表します。 #### ダッシュボード [商品を追加](https://dashboard.stripe.com/test/products/create)ページに移動して、コインのバンドルを作成します。10 USD の 1 回限りの価格を追加します。 - 100 コイン: アプリ内の 100 コインのバンドル - 価格: 標準モデル | 10 USD | 1 回限り 価格を作成したら、価格 ID を記録しておき、後続のステップで使用できるようにします。価格 ID は、`price_G0FvDp6vZvdwRZ` のように表示されます。 準備ができたら、ページの右上にある **本番環境にコピー** ボタンを使用して、[テスト環境から本番環境](https://docs.stripe.com/keys.md#test-live-modes)に製品を複製します。 #### Stripe CLI 次に、Product オブジェクトを作成します。 ```bash stripe products create \ --name="100 coins" \ --description="Bundle of 100 in-app coins" ``` Stripe CLI は、商品 ID を含む商品詳細を返します。 ```json { "id": "prod_H94k5odtwJXMtQ", "object": "product", "active": true, "attributes": [ ], "created": 1587577341, "description": "Bundle of 100 in-app coins", "images": [ ], "livemode": false, "metadata": { }, "name": "100 coins", "statement_descriptor": null, "type": "service", "unit_label": null, "updated": 1587577341 } ``` 商品 ID を使用して価格を作成します。`unit_amount` はセント単位であるため、たとえば `1000` は 10 USD になります。 ```bash stripe prices create \ -d product=prod_H94k5odtwJXMtQ \ -d unit_amount=1000 \ -d currency=usd ``` 各価格の価格 ID を記録しておき、後続のステップで使用できるようにします。これは次のように表示されます。 ```json { "id": "price_1Jh0tjEmNk5jCjFGCkLnNYGO", "object": "price", "active": true, "billing_scheme": "per_unit", "created": 1633391323, "currency": "usd", "livemode": false, "lookup_key": null, "metadata": { }, "nickname": null, "product": "prod_H94k5odtwJXMtQ", "recurring": null, "tax_behavior": "unspecified", "tiers_mode": null, "transform_quantity": null, "type": "one_time", "unit_amount": 1000, "unit_amount_decimal": "1000" } ``` ## 顧客を作成する [サーバー側] Checkout セッションを作成するたびに、そのユーザーにまだ設定されていなければ *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) オブジェクトを作成します。 #### Node.js ```javascript // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. // Find your keys at https://dashboard.stripe.com/apikeys. const stripe = require('stripe')('<>'); // This assumes your app has an existing user database, which we'll call `myUserDB`. const user = myUserDB.getUser("jennyrosen"); if (!user.stripeCustomerID) { const customer = await stripe.customers.create({ name: user.name, email: user.email, }); // Set the user's Stripe Customer ID for later retrieval. user.stripeCustomerID = customer.id; } ``` > ユーザーアカウントと Stripe 顧客 ID との関連付けを、サーバーに必ず保存してください。顧客を購入に関連付ける方法がなければ、顧客は購入を回復できなくなります。 > > アプリが既存の認証プロバイダーを持たない場合は、代わりに [Apple でサインイン](https://developer.apple.com/sign-in-with-apple/)を利用できます。 [支払い方法の詳細を保存](https://docs.stripe.com/payments/save-during-payment.md?platform=checkout)し、Checkout で Customer に支払い方法を自動的に関連付け、その後の支払いに再利用できます。 ## ユニバーサルリンクを設定する [クライアント側] [サーバー側] *ユニバーサルリンク* (Use Universal links on iOS and macOS to link directly to in-app content. They're standard HTTPS links, so the same URL works for your website and your app)を使用すると、Checkout をお使いのアプリにディープリンクできます。ユニバーサルリンクを設定するには、次の手順を行います。 1. ドメインに `apple-app-site-association` ファイルを追加します。 1. アプリに Associated Domains エンタイトルメントを追加します。 1. Checkout リダイレクト URL のフォールバックページを追加します。 #### 関連ドメインを定義する **.well-known/apple-app-site-association** メインにファイルを追加し、アプリで処理する URL を定義します。アプリ ID の前にチーム ID を付加します。チーム IDは、[Apple Developer Portal のメンバーシップページ](https://developer.apple.com/account)にあります。 ```json { "applinks": { "apps": [], "details": [ { "appIDs": [ "A28BC3DEF9.com.example.MyApp1", "A28BC3DEF9.com.example.MyApp1-Debug" ], "components": [ { "/": "/checkout_redirect*", "comment": "Matches any URL whose path starts with /checkout_redirect" } ] } ] } } ``` このファイルは、MIME タイプ `application/json` で提供する必要があります。`curl -I` を使用してコンテンツタイプを確認します。 ```bash curl -I https://example.com/.well-known/apple-app-site-association ``` 詳細については、[関連ドメインのサポート](https://developer.apple.com/documentation/xcode/supporting-associated-domains)に関する Apple のページを参照してください。 #### アプリに Associated Domains エンタイトルメントを追加する 1. アプリのターゲットの、**Signing & Capabilities (署名とケイパビリティ)** ウィンドウを開きます。 1. **+ ケイパビリティ** をクリックし、**関連ドメイン** を選択します。 1. `applinks:example.com` のエントリーを **Associated Domains** リストに追加します。 ユニバーサルリンクの詳細については、Apple の [Universal Links for Developers (開発者のためのユニバーサルリンク) (英語)](https://developer.apple.com/ios/universal-links/) ページをご覧ください。 iOS は、`apple-app-site-association` ファイルで定義された URL へのリンクをインターセプトしますが、リダイレクトでアプリを開くことができないケースが発生することがあります。 必ず `success_url` に[フォールバックページ](https://docs.stripe.com/payments/checkout/custom-success-page.md?payment-ui=stripe-hosted)を作成してください。たとえば、[アプリにカスタム URL スキームを定義](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)し、ユニバーサルリンクが失敗した場合にリンクバックに使用できます。 ## Checkout セッションを作成する [サーバー側] [Checkout Session](https://docs.stripe.com/api/checkout/Sessions/create.md)は、支払いフォームにリダイレクトされた顧客に表示される内容をプログラムで表現したものです。Checkout Session は作成後 24 時間で有効期限が切れます。以下のように設定してください。 - 顧客 ID - 商品 ID (1 回限りの支払いまたはサブスクリプション) - `origin_context` が `mobile_app` に設定され、アプリから Web への購入に最適化された UI にオプトインします。 - `success_url`。支払いが完了した後に、顧客をお客様のアプリにリダイレクトする*ユニバーサルリンク* (Use Universal links on iOS and macOS to link directly to in-app content. They're standard HTTPS links, so the same URL works for your website and your app)です。 > `origin_context: "mobile_app"`を使用して決済セッションを作成し、アプリからウェブへの購入に最適化された UI にオプトインします。 Checkout セッションを作成したら、レスポンスからの [URL](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-url) をお客様のアプリに返します。 #### 1 回限りの支払い #### Node.js ```javascript // This example sets up an endpoint using the Express framework. const express = require('express'); const app = express(); const stripe = require('stripe')('<>'); app.post('/create-checkout-session', async (req, res) => { // Fetch the Stripe customer ID for the customer associated with this request. // This assumes your app has an existing user database, which we'll call `myUserDB`. const user = myUserDB.getUserFromToken(req.query.token); const customerId = user.stripeCustomerID; // The price ID from the previous step const priceId = '{{PRICE_ID}}'; const session = await stripe.checkout.sessions.create({ line_items: [ { price: priceId, quantity: 1, }, ], mode: 'payment', origin_context: 'mobile_app', customer: customerId, success_url: 'https://example.com/checkout_redirect/success', }); res.json({url: session.url}); }); app.post('/login', async (req, res) => { // This assumes your app has an existing user database, which we'll call `myUserDB`. const token = myUserDB.login(req.body.login_details) res.json({token: token}) }); app.listen(4242, () => console.log(`Listening on port ${4242}!`)); ``` #### サブスクリプション #### Node.js ```javascript // This example sets up an endpoint using the Express framework. const express = require('express'); const app = express(); const stripe = require('stripe')('<>'); app.post('/create-checkout-session', async (req, res) => {// Fetch the Stripe customer ID for the customer associated with this request. // This assumes your app has an existing user database, which we'll call `myUserDB`. const user = myUserDB.getUserFromToken(req.query.token); const customerId = user.stripeCustomerID; // The price ID from the previous step const priceId = '{{SUBSCRIPTION_PRICE_ID}}'; const session = await stripe.checkout.sessions.create({ line_items: [ { price: priceId, quantity: 1, }, ], mode: 'subscription', origin_context: 'mobile_app', customer: customerId, success_url: 'https://example.com/checkout_redirect/success', }); res.json({url: session.url}); }); app.post('/login', async (req, res) => { // This assumes your app has an existing user database, which we'll call `myUserDB`. const token = myUserDB.login(req.body.login_details) res.json({token: token}) }); app.listen(4242, () => console.log(`Listening on port ${4242}!`)); ``` > [Apple Pay はデフォルトで有効](https://dashboard.stripe.com/settings/checkout)になっており、顧客が対応デバイスを使用すると決済に自動的に表示されます。[動的決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用して、追加の決済手段を受け付けることができます。 ## Safari で Checkout を開く [クライアント側] アプリに決済ボタンを追加します。このボタンは以下を行います。 1. サーバー側のエンドポイントを呼び出して、Checkout セッションを作成します。 1. クライアントに Checkout セッションを返します。 1. Safari でセッション URL を開きます。 ```swift import Foundation import SwiftUI import StoreKit struct BuyCoinsView: View { @EnvironmentObject var myBackend: MyServer @State var paymentComplete = false var body: some View { // Check if payments are blocked by Parental Controls on this device. if !SKPaymentQueue.canMakePayments() { Text("Payments are disabled on this device.") } else { if paymentComplete { Text("Payment complete!") } else { Button { myBackend.createCheckoutSession { url in UIApplication.shared.open(url, options: [:], completionHandler: nil) } } label: { Text("Buy 100 coins") }.onOpenURL { url in // Handle the universal link from Checkout. if url.absoluteString.contains("success") { // The payment was completed. Show a success // page and fetch the latest customer entitlements // from your server. paymentComplete = true } } } } } } ``` ### クライアントで Checkout URL を取得する サーバーエンドポイントを使用して、Checkout セッションを取得します。 ```swift class MyServer: ObservableObject { // The cached login token var token: String? func createCheckoutSession(completion: @escaping (URL) -> Void) { // Send the login token to the `/create_checkout_session` endpoint let request = URLRequest(url: URL(string: "https://example.com/create-checkout-session?token=\(self.token)")!) let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in guard let unwrappedData = data, let json = try? JSONSerialization.jsonObject(with: unwrappedData, options: []) as? [String : Any], let urlString = json["url"] as? String, let url = URL(string: urlString) else { // Handle error return } DispatchQueue.main.async { // Call the completion block with the Checkout session URL returned from the backend completion(url) } }) task.resume() } func login() { // Login using the server and set the login token. let request = URLRequest(url: URL(string: "https://example.com/login")!) let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in guard let unwrappedData = data, let json = try? JSONSerialization.jsonObject(with: unwrappedData, options: []) as? [String : Any], let token = json["token"] as? String else { // Handle error return } self.token = token }) task.resume() } } ``` ## 注文のフルフィルメントを処理する [サーバー側] 購入が成功すると、Stripe は `checkout.session.completed` *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) を送信します。このイベントを受け取ったら、サーバー上の顧客にコインを追加できます。 [イベントを受信したことを確認](https://docs.stripe.com/webhooks.md#acknowledge-events-immediately)すると、Checkout は購入者を `success_url` にリダイレクトします。エンドポイントが停止していたり、イベントが正しく確認されない場合、Checkout は支払い成功の 10 秒後に購入者を `success_url` にリダイレクトします。 テスト目的の場合は、[ダッシュボード](https://dashboard.stripe.com/events)または [Stripe CLI](https://docs.stripe.com/webhooks.md#test-webhook) を使用してイベントをモニタリングできます。本番環境では、Webhook エンドポイントを設定して、適切なイベントタイプに登録します。`STRIPE_WEBHOOK_SECRET` キーが不明な場合は、ダッシュボードで [Webhook](https://dashboard.stripe.com/webhooks) をクリックして表示します。 #### Node.js ```javascript // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. // Find your keys at https://dashboard.stripe.com/apikeys. const stripe = require('stripe')('<>'); app.post("/webhook", async (req, res) => { let data; let eventType; // Check if webhook signing is configured. const webhookSecret = "{{STRIPE_WEBHOOK_SECRET}}" // 例: whsec_c7681Dm if (webhookSecret) { // Retrieve the event by verifying the signature using the raw body and secret. let event; let signature = req.headers["stripe-signature"]; try { event = stripe.webhooks.constructEvent( req.body, signature, webhookSecret ); } catch (err) { console.log(`⚠️ Webhook signature verification failed.`); return res.sendStatus(400); } // Extract the object from the event. data = event.data; eventType = event.type; } else { // Webhook signing is recommended, but if the secret is not configured in `config.js`, // retrieve the event data directly from the request body. data = req.body.data; eventType = req.body.type; } switch (eventType) { case 'checkout.session.completed': const session = event.data.object; // Payment is successful. // Update the customer in your database to reflect this purchase. const user = myUserDB.userForStripeCustomerID(session.customer); user.addCoinsTransaction(100, session.id); break; default: // Unhandled event type } res.sendStatus(200); }); ``` ### テスト 顧客をStripe Checkout にリダイレクトする決済ボタンをテストします。 1. 決済ボタンをクリックすると、Stripe Checkout 支払いフォームにリダイレクトされます。 1. 4242 4242 4242 4242 のテストカード番号、3 桁のセキュリティコード、将来の有効期限日、および任意の有効な郵便番号を入力します。 1. **支払う** をタップします。 1. `checkout.session.completed` Webhook が起動して、Stripe は取引についてお客様のサーバーに通知します。 1. リダイレクトによってアプリへと戻されます。 実装が機能していない場合には、以下の[その他のテスト用リソース](https://docs.stripe.com/mobile/digital-goods/checkout.md#additional-testing-resources)のセクションをご覧ください。 ## Optional: その他のテスト用リソース 実装を本番環境に移行する準備ができたかの確認に使用できる、テスト用の番号がいくつかあります。任意のセキュリティコード、郵便番号、および今後の有効期限を指定して使用します。 | 数字 | 説明 | | ------------------- | --------------------------------------- | | 4242 4242 4242 4242 | 支払いが成功し、すぐに処理されます。 | | 4000 0000 0000 3220 | 支払いを正常に完了させるために、3D セキュア 2 認証を実行します。 | | 4000 0000 0000 9995 | 常に支払い拒否コード `insufficient_funds` で失敗します。 | 全テストカードの一覧については、[テスト](https://docs.stripe.com/testing.md)に関するガイドをご覧ください。 ### ユニバーサルリンクをテストする ユニバーサルリンクで Checkout からアプリにリダイレクトされない場合は、`SharedWebCredentials` ログでエラーがないかを確認してください。 1. Associated Domains エンタイトルメントにデバッグパラメーターを追加する - アプリのターゲットの、**Signing & Capabilities (署名とケイパビリティ)** ウィンドウを開きます。 - 関連ドメインのエントリーに `?mode=developer` フラグを追加します。「(例: `applinks:example.com?mode=developer`)」 1. デバイスを開発者モードに設定します。 - デバイスで Xcode からアプリを実行し、開発者メニューを有効にします。 - iPhone で、**Settings (設定)** を開き、**Developer (開発者)** をタップし、**Associated Domains Development (関連ドメイン開発)** を有効にします。 1. アプリを削除して、再インストールします。これにより、iOS は apple-app-site-association ファイルを再取得します。 1. アプリで決済フローを完了します。 1. Checkout によってアプリにリダイレクトされます。そうでない場合は、sysdiagnose を取得します。 1. 音量アップ、音量ダウン、および電源ボタンを同時に 1 秒間押してから離します。短い振動を感じますが、視覚的なフィードバックは表示されません。 1. 5 分間待ってから、**Settings (設定)** > **Privacy (プライバシー)** > **Analytics & Improvement (分析と改善)** > **Analytics Data (分析データ)** に移動し、リストの最後の sysdiagnose ファイルまでスクロールします。 1. 共有ボタンをタップして、お使いのコンピューターにファイルを AirDrop (エアドロップ) します。 1. sysdiagnose アーカイブを開き、次に `swcutil_show.txt` を開きます 1. このファイルでアプリ ID を検索します。アプリのデバッグ情報のセクションが表示されます。エラーがある場合には、それも含まれます。 ``` Service: applinks App ID: Y28TH9SHX7.com.stripe.FruitStore App Version: 1.0 App PI: { v = 0, t = 0x8, u = 0xc98, db = E335D78F-D49E-4F19-A150-F657E50DEDAE, {length = 8, bytes = 0x980c000000000000} } Domain: example.com?mode=developer User Approval: unspecified Site/Fmwk Approval: unspecified Flags: developer Last Checked: 2021-09-23 18:16:58 +0000 Next Check: 2021-09-23 21:21:34 +0000 Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set. around line 1, column 0." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set. around line 1, column 0., NSJSONSerializationErrorIndex=0} Retries: 1 ``` ## Optional: Managed Payments を使用したアプリ内購入 Managed Paymentsを利用して決済いを受け付けることができます。Managed Payments は、税務処理や不審請求の申し立て対応など、多くのビジネス機能を代行できます。アプリ内課金で Stripeのマーチャントオブレコードソリューションである [Managed Paymentsを利用する方法 ](https://docs.stripe.com/payments/managed-payments/set-up-mobile.md) について、詳しくはこちらをご参照ください。 ## See also - [割引を追加する](https://docs.stripe.com/payments/checkout/discounts.md) - [税金を徴収する](https://docs.stripe.com/payments/checkout/taxes.md) - [納税者番号を収集する](https://docs.stripe.com/tax/checkout/tax-ids.md) - [ブランディングをカスタマイズする](https://docs.stripe.com/payments/checkout/customization.md) - [成功ページをカスタマイズする](https://docs.stripe.com/payments/checkout/custom-success-page.md)