# 決済ページをサイトに埋め込む # 完全埋め込みページ [Stripe Checkout](https://docs.stripe.com/payments/checkout.md) の導入を可能にするコードのサンプルをご覧ください。顧客が自社ウェブサイトの埋め込みフォームで支払いを完了できます。この例には、クライアント側およびサーバー側のコードが含まれており、埋め込み可能な UI コンポーネントによって決済画面が表示されます。 ### Stripe Node ライブラリーをインストールする パッケージをインストールし、それをコードにインポートします。また、まったくゼロから開始していて package.json ファイルが必要な場合には、コードエディターのダウンロードリンクを使用してプロジェクトファイルをダウンロードします。 #### npm ライブラリーをインストールします。 ```bash npm install --save stripe ``` #### GitHub または、stripe-node ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-node)ダウンロードします。 ### Stripe Ruby ライブラリーをインストールする Stripe ruby gem をインストールし、require を指定してコードに読み込みます。または、まったくゼロから開始していて Gemfile が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Terminal gem をインストールします。 ```bash gem install stripe ``` #### Bundler この行を Gemfile に追加します。 ```bash gem 'stripe' ``` #### GitHub または、stripe-ruby gem のソースコードを直接 [GitHub から](https://github.com/stripe/stripe-ruby)ダウンロードします。 ### Stripe Java ライブラリーをインストールする ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していてサンプルの pom.xml ファイル (Maven 用) が必要な場合は、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Maven POM に以下の依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle build.gradle ファイルに依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub JAR を直接 [GitHub から](https://github.com/stripe/stripe-java/releases/latest)ダウンロードします。 ### Stripe Python パッケージをインストールする Stripe パッケージをインストールし、コードにインポートします。まったくゼロから開始していて requirements.txt が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### pip pip を使用してパッケージをインストールします。 ```bash pip3 install stripe ``` #### GitHub stripe-python ライブラリのソースコードを [GitHub から](https://github.com/stripe/stripe-python)直接ダウンロードします。 ### Stripe PHP ライブラリーをインストールする Composer を使用してライブラリーをインストールし、シークレット API キーで初期化します。まったくゼロから開始していて composer.json ファイルが必要な場合には、コードエディターのリンクを使用してファイルをダウンロードします。 #### Composer ライブラリーをインストールします。 ```bash composer require stripe/stripe-php ``` #### GitHub または、stripe-php ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-php)ダウンロードします。 ### サーバーを設定する ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していて go.mod ファイルが必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Go 必ず Go モジュールを使用してを初期化してください。 ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub または、stripe-go モジュールのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-go)ダウンロードします。 ### Stripe.net ライブラリーをインストールする .NET または NuGet でパッケージをインストールします。まったくゼロから開始する場合には、設定済みの .csproj ファイルが含まれるファイルをダウンロードします。 #### dotnet ライブラリーをインストールします。 ```bash dotnet add package Stripe.net ``` #### NuGet ライブラリーをインストールします。 ```bash Install-Package Stripe.net ``` #### GitHub または、Stripe.net ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-dotnet)ダウンロードします。 ### Stripe ライブラリーをインストールする パッケージをインストールし、コードにインポートします。まったくゼロから開始していて `package.json` が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 ライブラリーをインストールします。 ```bash npm install --save stripe @stripe/stripe-js next ``` ### Checkout セッションを作成する サーバーに、*Checkout Session* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription) を作成するエンドポイントを追加し、[ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) を `embedded_page` に設定します。 Checkout セッションのレスポンスには client secret が含まれています。クライアントはこのシークレットを使用して Checkout をマウントします。レスポンスで [client_secret](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) を返します。 ### Checkout セッションを作成する アプリケーションに、*Checkout Session* (A Checkout Session represents your customer's session as they pay for one-time purchases or subscriptions through Checkout. After a successful payment, the Checkout Session contains a reference to the Customer, and either the successful PaymentIntent or an active Subscription) を作成する [Server Action](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) を追加し、[ui_mode](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-ui_mode) を `embedded_page` に設定します。 Checkout セッションのレスポンスには client secret が含まれています。クライアントはこのシークレットを使用して Checkout をマウントします。関数から [client_secret](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) を返します。 ### 戻り先 URL を指定する 支払い後の顧客のリダイレクト方法を定義するには、Checkout セッションの作成時に [return_url](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-return_url) パラメーターに戻り先ページの URL を指定します。支払いが試行された後で、自社ウェブサイトの戻り先ページに顧客がリダイレクトされます。 URL に `{CHECKOUT_SESSION_ID}` テンプレート変数を含めます。Checkout はこの変数を Checkout セッション ID に置き換えてから、顧客をリダイレクトします。自社のウェブサイトに戻り先ページを作成してホストすることはお客様の責任で行います。 ### 販売する商品を定義する Checkout Session の作成時に、[事前定義された価格 ID](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=embedded-page#create-product-prices-upfront) を使用して販売する商品を定義してください。 価格や在庫状況など、商品在庫に関する機密情報は常に自社のサーバーに置き、顧客がクライアントから操作できないようにします。 ### モードを選択する さまざまな取引タイプを処理するには、`mode` パラメーターを調整します。1 回限りの決済には、`payment` を使用します。[サブスクリプション](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=checkout&ui=embedded-page)で継続課金を開始するには、`mode` を `subscription` に切り替えます。[今後の決済を設定する](https://docs.stripe.com/payments/save-and-reuse.md?platform=web&ui=embedded-page)場合は、`mode` を `setup` に設定します。 ### React アプリに Stripe を追加する *PCI 準拠* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business)を維持するには、[React Stripe.js](https://docs.stripe.com/sdks/stripejs-react.md) をインストールし、支払い情報がサーバーを介することなく Stripe に直接送信されるようにします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Stripe.js を読み込む Stripe ライブラリを設定するには、Stripe の公開可能 API キーを使用して `loadStripe()` を呼び出します。 ### Stripe.js を読み込む *PCI 準拠* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business)を維持するには、*Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) を使用して、支払い詳細がお客様のサーバーを経由せずに直接 Stripe に送られるようにします。Stripe.js を常に「js.stripe.com」から読み込むことにより、PCI 準拠が維持されます。このスクリプトをバンドルに含めたり、自分でホストしたりしないでください。 ### 支払いフォームを定義する 顧客の情報を安全に収集するには、空のプレースホルダー `div` を作成します。Stripe はこの `div` に iframe を挿入します。 ### Stripe.js を初期化する [公開可能な API キー](https://docs.stripe.com/keys.md#obtain-api-keys)で Stripe.js を初期化します。 ### Checkout セッションの client secret を取得する サーバーに [Checkoutセッションの作成](https://docs.stripe.com/api/checkout/sessions/create.md)をリクエストする非同期の `fetchClientSecret` 関数を作成し、client secret を取得します。 ### Checkout セッションの client secret を取得する サーバーアクションをインポートして [Checkout Session を作成](https://docs.stripe.com/api/checkout/sessions/create.md)し、client secret を取得して、[`fetchClientSecret`](https://docs.stripe.com/js/embedded_checkout/create#embedded_checkout_create-options-fetchClientSecret) パラメーターに渡します。 ### Checkout を初期化する `fetchClientSecret` 関数を使用して Checkout を初期化し、決済フォームのプレースホルダー `
` にマウントします。Checkout が iframe でレンダリングされ、支払い情報が HTTPS 接続経由で Stripe に安全に送信されます。 Checkout を別の iframe 内に配置しないでください。一部の支払い方法では支払いを確定するために別のページにリダイレクトする必要があるからです。 ### Checkout を初期化する 子コンポーネントが埋め込み型 Checkout コンシューマーを介して Stripe サービスにアクセスできるようにするには、`loadStripe` の結果として生成された promise と、`option` として client secret を埋め込み型 Checkout プロバイダーに渡します。 ### エンドポイントを作成して Checkout セッションを取得する エンドポイントを追加して Checkout セッションのステータスを取得します。 ### 戻り先ページを追加する 顧客に注文情報を表示するには、Checkout セッション `return_url` として提供する URL の戻り先ページを作成します。顧客は支払いが完了すると、このページにリダイレクトされます。 ### 戻り先コンポーネントを追加する 顧客に注文情報を表示するには、Checkout セッション `return_url` として提供する URL の新しいルートと戻り先コンポーネントを追加します。顧客は支払いが完了すると、このページにリダイレクトされます。 ### 戻り先ページを追加する 顧客に注文情報を表示するには、Checkout セッションの `return_url` として指定した URL の `pages/` にファイルを追加します。顧客は購入後にこのページにリダイレクトされます。 ### Checkout セッションを取得する 戻り先ページが読み込まれたらすぐに、サーバー上のエンドポイントにリクエストを行います。URL の Checkout セッション ID を使用して Checkout セッションのステータスを取得します。 ### セッションを処理する 次のステータスを使用してセッションの結果を処理します。 - `complete`: 支払いが成功しました。Checkout セッションの情報を使用して成功ページをレンダリングします。 - `open`: 支払いが失敗またはキャンセルされました。 顧客がやり直せるように Checkout を再マウントします。 ### 環境変数を設定する 公開可能キーとシークレットキーを `.env` ファイルに追加します。これは Next.js によって自動的に[環境変数](https://nextjs.org/docs/basic-features/environment-variables)としてアプリケーションに読み込まれます。 Webhook エンドポイントごとに一意の署名シークレットがあります。Webhook は、ダッシュボードの[ワークベンチ](https://docs.stripe.com/workbench.md)で管理されます。ワークベンチの [Webhook タブ](https://dashboard.stripe.com/workbench/webhooks)にある Webhook エンドポイントの送信先の詳細ビューでシークレットを確認できます。Stripe CLI を使用してローカルでテストしている場合は、`stripe listen` コマンドを使用して CLI 出力からシークレットを取得することもできます。 Webhook エンドポイント署名シークレットを含めて[イベント](https://docs.stripe.com/event-destinations.md)をリッスンするには、ワークベンチの[イベントの送信先](https://dashboard.stripe.com/workbench/webhooks)タブに移動するか、[Stripe CLI](https://docs.stripe.com/stripe-cli.md) を使用します。 ### アプリケーションを実行する サーバーを起動し、 に移動します ### アプリケーションを実行する サーバーを起動し、 に移動します ### アプリケーションを実行する `npm run dev` でアプリを起動し、 に移動します ### 試してみる 支払いボタンをクリックして支払いを完了します。指定した戻り先ページにリダイレクトされます。 戻り先ページが表示され、ダッシュボードで[成功した支払い](https://dashboard.stripe.com/test/payments?status%5B0%5D=successful)の一覧に支払いが表示されれば、実装は正常に機能しています。以下のテストカードを使用し、支払いをシミュレーションします。 | Scenario | Card Number | | ----------------------------------- | ---------------- | | Payment succeeds | 4242424242424242 | | Payment requires 3DS authentication | 4000002500003155 | | Payment is declined | 4000000000009995 | ## これで完了です。 Checkout の基本的な実装が機能するようになりました。次に、決済ページのデザインをカスタマイズする方法をご紹介します。 ### 決済ページをカスタマイズする 以下の方法で、埋め込みフォームのデザインを[カスタマイズ](https://docs.stripe.com/payments/checkout/customization.md) します。 - [ブランディング設定](https://dashboard.stripe.com/settings/branding/checkout)でカラーテーマとフォントを追加する。 - [Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions/create.md) を使用し、住所の収集や顧客データの事前入力などの追加機能を有効化します。 ### 顧客データを事前入力する [customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email) を使用して、メールの入力フィールドに顧客のメールアドレスを事前入力します。また、[Customer (顧客)](https://docs.stripe.com/api/customers.md) ID を `customer` フィールドに渡して、Customer に保存されたメールアドレスをメールアドレスのフィールドに事前入力することもできます。 ### 送信ボタンを選択する Checkout の送信ボタンのテキストを `pay`、`donate`、`book` のいずれかに変更するため、[submit_type](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-submit_type) を設定します。デフォルトのテキストは `pay` です。 ### 請求先詳細および配送先詳細を収集する [billing_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-billing_address_collection) と [shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) を使用して、顧客の住所を収集します。[shipping_address_collection](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-shipping_address_collection) には、`allowed_countries` のリストが必要です。Checkout では、これらの国がページのドロップダウンメニューに表示されます。 ### 税金の徴収を自動化する Stripe 取引の適切な税額を計算して徴収します。[Stripe Tax](https://docs.stripe.com/tax.md) と [Checkout への追加方法](https://docs.stripe.com/tax/checkout.md)の詳細をご確認ください。 ### ダッシュボードで Stripe Tax を設定する [Stripe Tax を有効にする](https://dashboard.stripe.com/tax)ことで、納税義務を監視し、税金を自動徴収し、還付申告に必要な申告書を利用できます。 ### 税金の自動計算パラメーターを追加する `automatic_tax` パラメーターを `enabled: true` に設定します。 ### 新規顧客とリピーター デフォルトでは、Checkout は必要な場合にのみ (サブスクリプションの場合など) [Customer (顧客)](https://docs.stripe.com/api/customers.md) を作成します。それ以外の場合、Checkout は[ゲスト顧客](https://docs.stripe.com/payments/checkout/guest-customers.md)を使用してダッシュボードで支払いをグループ化します。必要に応じて、必ず新規顧客を作成するか、リピーターを指定するように Checkout を設定できます。 ### 必ず顧客を作成する 顧客が指定されていない場合でも必ず顧客を作成するには、[customer_creation](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_creation) に `'always'` を設定します。 ### リピーターを指定する Checkout Session を既存の顧客に関連付けるには、セッションの作成時に[顧客](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer)を指定します。Accounts v2 を使用して顧客をモデル化する場合は、[customer_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) フィールドに Account ID を渡して、関連付けられたメールアドレスを事前入力することもできます。[v1 Customer と v2 Account の違い](https://docs.stripe.com/accounts-v2/use-accounts-as-customers.md)について、詳細をご確認ください。 // This test secret API key is a placeholder. Don't include personal details in requests with this key. // To see your test secret API key embedded in code samples, sign in to your Stripe account. // You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. const stripe = require('stripe')('<>'); const YOUR_DOMAIN = 'http://localhost:4242'; const YOUR_DOMAIN = 'http://localhost:3000'; const session = await stripe.checkout.sessions.create({ ui_mode: 'embedded_page', customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'auto', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [ { // Provide the exact Price ID (for example, price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }, ], mode: {{CHECKOUT_MODE}}, return_url: `${YOUR_DOMAIN}/return?session_id={CHECKOUT_SESSION_ID}`, return_url: `${YOUR_DOMAIN}/return.html?session_id={CHECKOUT_SESSION_ID}`, automatic_tax: {enabled: true}, customer_creation: 'always', // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // customer: '{{CUSTOMER_ID}}' }); res.send({clientSecret: session.client_secret}); app.get('/session-status', async (req, res) => { const session = await stripe.checkout.sessions.retrieve(req.query.session_id); res.send({ status: session.status, customer_email: session.customer_details.email }); }); { "name": "stripe-sample", "version": "1.0.0", "description": "A sample Stripe implementation", "main": "server.js", "scripts": { "start": "node server.js" }, "author": "stripe-samples", "license": "ISC", "dependencies": { "express": "^4.17.1", "stripe": "^21.0.1" } } { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.17.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^3.4.0", "stripe": "21.0.1" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } \# This test secret API key is a placeholder. Don't include personal details in requests with this key. # To see your test secret API key embedded in code samples, sign in to your Stripe account. # You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. \# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = Stripe::StripeClient.new('<>') YOUR_DOMAIN = 'http://localhost:4242' YOUR_DOMAIN = 'http://localhost:3000' session = client.v1.checkout.sessions.create({ ui_mode: 'embedded_page', customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'required', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [{ \# Provide the exact Price ID (for example, price_1234) of the product you want to sell price: '{{PRICE_ID}}', quantity: 1, }], mode: {{CHECKOUT_MODE}}, return_url: YOUR_DOMAIN + '/return.html?session_id={CHECKOUT_SESSION_ID}', return_url: YOUR_DOMAIN + '/return?session_id={CHECKOUT_SESSION_ID}', automatic_tax: {enabled: true}, customer_creation: 'always', \# Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # customer: '{{CUSTOMER_ID}}' }) {clientSecret: session.client_secret}.to_json get '/session-status' do session = client.v1.checkout.sessions.retrieve(params[:session_id]) {status: session.status, customer_email: session.customer_details.email}.to_json end import stripe \# This test secret API key is a placeholder. Don't include personal details in requests with this key. # To see your test secret API key embedded in code samples, sign in to your Stripe account. # You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. \# Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = stripe.StripeClient('<>') YOUR_DOMAIN = 'http://localhost:4242' YOUR_DOMAIN = 'http://localhost:3000' session = client.v1.checkout.sessions.create(params={ 'ui_mode': 'embedded_page', 'customer_email': 'customer@example.com', 'submit_type': 'donate', 'billing_address_collection': 'auto', 'shipping_address_collection': { 'allowed_countries': ['US', 'CA'], }, 'line_items': [ { \# Provide the exact Price ID (for example, price_1234) of the product you want to sell 'price': '{{PRICE_ID}}', 'quantity': 1, }, ], 'mode': {{CHECKOUT_MODE}}, 'return_url': YOUR_DOMAIN + '/return.html?session_id={CHECKOUT_SESSION_ID}', 'return_url': YOUR_DOMAIN + '/return?session_id={CHECKOUT_SESSION_ID}', 'automatic_tax': {'enabled': True}, 'customer_creation': 'always', \# Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # 'customer': '{{CUSTOMER_ID}}' }) return jsonify(clientSecret=session.client_secret) @app.route('/session-status', methods=['GET']) def session_status(): session = client.v1.checkout.sessions.retrieve(request.args.get('session_id')) return jsonify(status=session.status, customer_email=session.customer_details.email) certifi==2026.1.4 chardet==5.2.0 click==8.3.1 Flask==3.1.2 idna==3.11 itsdangerous==2.2.0 Jinja2==3.1.6 MarkupSafe==3.0.3 requests==2.32.5 stripe==15.0.0 toml==0.10.2 Werkzeug==3.1.5 $stripe = new \Stripe\StripeClient($stripeSecretKey); $YOUR_DOMAIN = 'http://localhost:4242'; $YOUR_DOMAIN = 'http://localhost:3000'; $checkout_session = $stripe->checkout->sessions->create([ 'ui_mode' => 'embedded_page', 'customer_email' => 'customer@example.com', 'submit_type' => 'donate', 'billing_address_collection' => 'required', 'shipping_address_collection' => [ 'allowed_countries' => ['US', 'CA'], ], 'line_items' => [[ \# Provide the exact Price ID (for example, price_1234) of the product you want to sell 'price' => '{{PRICE_ID}}', 'quantity' => 1, ]], 'mode' => {{CHECKOUT_MODE}}, 'return_url' => $YOUR_DOMAIN . '/return.html?session_id={CHECKOUT_SESSION_ID}', 'return_url' => $YOUR_DOMAIN . '/return?session_id={CHECKOUT_SESSION_ID}', 'automatic_tax' => [ 'enabled' => true, ], 'customer_creation' => 'always', \# Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session # 'customer' => '{{CUSTOMER_ID}}' ]); echo json_encode(array('clientSecret' => $checkout_session->client_secret)); try { // retrieve JSON from POST body $jsonStr = file_get_contents('php://input'); $jsonObj = json_decode($jsonStr); $session = $stripe->checkout->sessions->retrieve($jsonObj->session_id); echo json_encode(['status' => $session->status, 'customer_email' => $session->customer_details->email]); http_response_code(200); } catch (Error $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); } // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. $stripeSecretKey = '<>'; // This test secret API key is a placeholder. Don't include personal details in requests with this key. // To see your test secret API key embedded in code samples, sign in to your Stripe account. // You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. services.AddSingleton(new StripeClient("<>")); var domain = "http://localhost:4242"; var domain = "http://localhost:3000"; UiMode = "embedded_page", CustomerEmail = "customer@example.com", SubmitType = "donate", BillingAddressCollection = "auto", ShippingAddressCollection = new SessionShippingAddressCollectionOptions { AllowedCountries = new List { "US", "CA", }, }, LineItems = new List { new SessionLineItemOptions { // Provide the exact Price ID (for example, price_1234) of the product you want to sell Price = "{{PRICE_ID}}", Quantity = 1, }, }, Mode = {{CHECKOUT_MODE}}, ReturnUrl = domain + "/return.html?session_id={CHECKOUT_SESSION_ID}", ReturnUrl = domain + "/return?session_id={CHECKOUT_SESSION_ID}", AutomaticTax = new SessionAutomaticTaxOptions { Enabled = true }, CustomerCreation = "always", // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // Customer="cus_RnhPlBnbBbXapY", Session session = _client.V1.Checkout.Sessions.Create(options); return Json(new {clientSecret = session.ClientSecret}); [Route("session-status")] [ApiController] public class SessionStatusController : Controller { private readonly StripeClient _client; public SessionStatusController(StripeClient client) { _client = client; } [HttpGet] public ActionResult SessionStatus([FromQuery] string session_id) { Session session = _client.V1.Checkout.Sessions.Get(session_id); return Json(new {status = session.Status, customer_email = session.CustomerDetails.Email}); } } "github.com/stripe/stripe-go/v85" // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. sc := stripe.NewClient("<>") domain := "http://localhost:4242" domain := "http://localhost:3000" params := &stripe.CheckoutSessionCreateParams{ UIMode: stripe.String("embedded_page"), ReturnURL: stripe.String(domain + "/return.html?session_id={CHECKOUT_SESSION_ID}"), ReturnURL: stripe.String(domain + "/return?session_id={CHECKOUT_SESSION_ID}"), CustomerEmail: stripe.String("customer@example.com"), SubmitType: stripe.String("donate"), BillingAddressCollection: stripe.String("auto"), ShippingAddressCollection: &stripe.CheckoutSessionShippingAddressCollectionParams{ AllowedCountries: stripe.StringSlice([]string{ "US", "CA", }), }, LineItems: []*stripe.CheckoutSessionCreateLineItemParams{ { // Provide the exact Price ID (for example, price_1234) of the product you want to sell Price: stripe.String("{{PRICE_ID}}"), Quantity: stripe.Int64(1), }, }, Mode: stripe.String("{{CHECKOUT_MODE}}"), AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{Enabled: stripe.Bool(true)}, CustomerCreation: stripe.String(stripe.CheckoutSessionCustomerCreationAlways), // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // Customer: stripe.String("{{CUSTOMER_ID}}"), } s, err := sc.V1CheckoutSessions.Create(context.TODO(), params) if err != nil { log.Printf("sc.V1CheckoutSessions.Create: %v", err) } writeJSON(w, struct { ClientSecret string `json:"clientSecret"` }{ ClientSecret: s.ClientSecret, }) func retrieveCheckoutSession(sc *stripe.Client, w http.ResponseWriter, r *http.Request) { s, _ := sc.V1CheckoutSessions.Retrieve(context.TODO(), r.URL.Query().Get("session_id"), nil) writeJSON(w, struct { Status string `json:"status"` CustomerEmail string `json:"customer_email"` }{ Status: string(s.Status), CustomerEmail: string(s.CustomerDetails.Email), }) } require github.com/stripe/stripe-go/v85 v85.0.0 // This test secret API key is a placeholder. Don't include personal details in requests with this key. // To see your test secret API key embedded in code samples, sign in to your Stripe account. // You can also find your test secret API key at https://dashboard.stripe.com/test/apikeys. // Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. StripeClient client = new StripeClient("<>"); String YOUR_DOMAIN = "http://localhost:4242"; String YOUR_DOMAIN = "http://localhost:3000"; SessionCreateParams params = SessionCreateParams.builder() .setUiMode(SessionCreateParams.UiMode.EMBEDDED_PAGE) .setCustomerEmail("customer@example.com") .setSubmitType(SessionCreateParams.SubmitType.DONATE) .setBillingAddressCollection(SessionCreateParams.BillingAddressCollection.REQUIRED) .setShippingAddressCollection( SessionCreateParams.ShippingAddressCollection.builder() .addAllowedCountry(SessionCreateParams.ShippingAddressCollection.AllowedCountry.CA) .addAllowedCountry(SessionCreateParams.ShippingAddressCollection.AllowedCountry.US) .build()) .setMode({{CHECKOUT_MODE}}) .setReturnUrl(YOUR_DOMAIN + "/return?session_id={CHECKOUT_SESSION_ID}") .setReturnUrl(YOUR_DOMAIN + "/return.html?session_id={CHECKOUT_SESSION_ID}") .setAutomaticTax( SessionCreateParams.AutomaticTax.builder() .setEnabled(true) .build()) .setCustomerCreation(SessionCreateParams.CustomerCreation.ALWAYS) // Provide the Customer ID (for example, cus_1234) for an existing customer to associate it with this session // .setCustomer("{{CUSTOMER_ID}}") .addLineItem( SessionCreateParams.LineItem.builder() .setQuantity(1L) // Provide the exact Price ID (for example, price_1234) of the product you want to sell .setPrice("{{PRICE_ID}}") .build()) .build(); Map map = new HashMap(); map.put("clientSecret", session.getRawJsonObject().getAsJsonPrimitive("client_secret").getAsString()); return map; get("/session-status", (request, response) -> { Session session = client.v1().checkout().sessions().retrieve(request.queryParams("session_id")); Map map = new HashMap(); map.put("status", session.getRawJsonObject().getAsJsonPrimitive("status").getAsString()); map.put("customer_email", session.getRawJsonObject().getAsJsonObject("customer_details").getAsJsonPrimitive("email").getAsString()); return map; }, gson::toJson);
const stripe = Stripe("<>"); initialize(); // Create a Checkout Session async function initialize() { const fetchClientSecret = async () => { const response = await fetch("/create-checkout-session", { method: "POST", }); const response = await fetch("/checkout.php", { method: "POST", }); const { clientSecret } = await response.json(); return clientSecret; }; const checkout = await stripe.createEmbeddedCheckoutPage({ fetchClientSecret, }); // Mount Checkout checkout.mount('#checkout'); } Thanks for your order! initialize(); async function initialize() { const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const sessionId = urlParams.get('session_id'); const response = await fetch(`/session-status?session_id=${sessionId}`); const response = await fetch("/status.php", { headers: { Accept: "application/json", "Content-Type": "application/json", }, method: "POST", body: JSON.stringify({ session_id: sessionId }), }); const session = await response.json(); if (session.status == 'open') { window.location.replace('http://localhost:4242/checkout.html') } else if (session.status == 'complete') { document.getElementById('success').classList.remove('hidden'); document.getElementById('customer-email').textContent = session.customer_email } } { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.17.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^5.0.1", "react-router-dom": "^6.16.0", "stripe": "^8.202.0" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^5.0.1", "react-router-dom": "^6.16.0" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242/", "scripts": { "start": "react-scripts start --ignore client", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } import React, { useCallback, useState, useEffect } from "react"; import {loadStripe} from '@stripe/stripe-js'; import { EmbeddedCheckoutProvider, EmbeddedCheckout } from '@stripe/react-stripe-js'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. const stripePromise = loadStripe("<>"); const fetchClientSecret = useCallback(() => { // Create a Checkout Session return fetch("/create-checkout-session", { method: "POST", }) return fetch("/checkout.php", { method: "POST", }) .then((res) => res.json()) .then((data) => data.clientSecret); }, []); const options = {fetchClientSecret}; const Return = () => { const [status, setStatus] = useState(null); const [customerEmail, setCustomerEmail] = useState(''); useEffect(() => { const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const sessionId = urlParams.get('session_id'); fetch(`/session-status?session_id=${sessionId}`) fetch("/status.php", { headers: { Accept: "application/json", "Content-Type": "application/json", }, method: "POST", body: JSON.stringify({ session_id: sessionId }), }) .then((res) => res.json()) .then((data) => { setStatus(data.status); setCustomerEmail(data.customer_email); }); }, []); if (status === 'open') { return ( ) } if (status === 'complete') { return (

We appreciate your business! A confirmation email will be sent to {customerEmail}. If you have any questions, please email orders@example.com.

) } return null; } } /> { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.17.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^3.4.0", "stripe": "^8.202.0" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^3.4.0" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } // Create Checkout Sessions from body params. const session = await stripe.checkout.sessions.create({ ui_mode: 'embedded_page', customer_email: 'customer@example.com', submit_type: 'donate', billing_address_collection: 'auto', shipping_address_collection: { allowed_countries: ['US', 'CA'], }, line_items: [ { // Provide the exact Price ID (for example, price_1234) of // the product you want to sell price: '{{PRICE_ID}}', quantity: 1 } ], mode: 'payment', return_url: `${origin}/return?session_id={CHECKOUT_SESSION_ID}`, automatic_tax: {enabled: true}, }) import { EmbeddedCheckout, EmbeddedCheckoutProvider } from '@stripe/react-stripe-js' import { loadStripe } from '@stripe/stripe-js' import { fetchClientSecret } from '../actions/stripe' const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) \# https://dashboard.stripe.com/apikeys NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=<> STRIPE_SECRET_KEY=<> \# Set this environment variable to support webhooks — https://stripe.com/docs/webhooks#verify-events # STRIPE_WEBHOOK_SECRET=whsec_12345 export default async function Return({ searchParams }) { const { status, customer_details: { email: customerEmail } } = await stripe.checkout.sessions.retrieve(session_id, { expand: ['line_items', 'payment_intent'] }) if (status === 'open') { return redirect('/') } if (status === 'complete') { return (

We appreciate your business! A confirmation email will be sent to{' '} {customerEmail}. If you have any questions, please email{' '}

orders@example.com.
) } import 'server-only' import Stripe from 'stripe' export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY) 1. Build the server ~~~ pip3 install -r requirements.txt ~~~ 1. Build the server ~~~ bundle install ~~~ 1. Build the server ~~~ composer install ~~~ 1. Build the server ~~~ dotnet restore ~~~ 1. Build the server ~~~ mvn package ~~~ 2. Run the server ~~~ export FLASK_APP=server.py python3 -m flask run --port=4242 ~~~ 2. Run the server ~~~ ruby server.rb -o 0.0.0.0 ~~~ 2. Run the server ~~~ php -S 127.0.0.1:4242 --docroot=public ~~~ 2. Run the server ~~~ dotnet run ~~~ 2. Run the server ~~~ java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ~~~ 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ If you run into an error, when running npm start, try running the following code and starting again: ~~~ export NODE_OPTIONS=--openssl-legacy-provider ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Run the server ~~~ go run server.go ~~~ 2. Build the client app ~~~ npm install ~~~ 3. Run the client app ~~~ npm start ~~~ 4. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 1. Run the server ~~~ go run server.go ~~~ 2. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Build the application ~~~ npm install ~~~ 2. Run the application ~~~ npm start ~~~ 3. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 1. Build the server ~~~ npm install ~~~ 2. Run the server ~~~ npm start ~~~ 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) \### Development 1. Build the application ~~~shell $ npm install ~~~ 2. _Optional_: download and run the [Stripe CLI](https://stripe.com/docs/stripe-cli) ~~~shell $ stripe listen --forward-to localhost:3000/api/webhooks ~~~ 3. Run the application ~~~shell $ STRIPE_WEBHOOK_SECRET=$(stripe listen --print-secret) npm run dev ~~~ 4. Go to [localhost:3000](http://localhost:3000) ### Production 1. Build the application ~~~shell $ npm install $ npm build ~~~ 2. Run the application ~~~shell $ npm start ~~~ ## 次のステップ #### [注文のフルフィルメントを履行](https://docs.stripe.com/checkout/fulfillment.md) 支払いの成功後に注文のフルフィルメントを実行するための Webhook を設定します。Webhook は、ビジネスで重要なイベントを処理するための非常に信頼性に優れた手段です。 #### [入金を受け取る](https://docs.stripe.com/payouts.md) Stripe アカウントから銀行口座に売上を移動する方法をご紹介します。 #### [支払いの返金とキャンセル](https://docs.stripe.com/refunds.md) Stripe API またはダッシュボードを使用し、返金のリクエストを処理します。 #### [顧客管理](https://docs.stripe.com/customer-management.md) 顧客が決済情報、請求書、サブスクリプションを自分で管理できるようにします