# ステーブルコイン決済の受け付け 暗号資産による支払い方法を有効にして、ステーブルコインの受け入れを開始します。 *Payment Links* (A link to a secure, hosted payment page that you can generate without code. Share it directly with your customers, or point them to it with a button or QR code)、*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)、*Elements* (A set of UI components for building a web checkout flow. They adapt to your customer's locale, validate input, and use tokenization, keeping sensitive customer data from touching your server)、または *Payment Intents API* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) を通じて、*ステーブルコイン* (A cryptocurrency that's pegged to the value of a fiat currency or other asset in order to limit volatility) による決済を受け付けることができる。USDC などのステーブルコインで決済する場合、顧客は **crypto.stripe.com** にリダイレクトされ、暗号資産ウォレットを接続して取引を完了する。資金は USD で Stripe 残高に入金される。 ## Before you begin > 顧客は世界中でステーブルコインを決済に利用できますが、ステーブルコインの決済を受け付けることができるのはアメリカ企業のみです。 ステーブルコイン決済の受け付けを開始するには、以下のようにします: 1. [Stripe アカウントを設定](https://docs.stripe.com/get-started/account/set-up.md)していることを確認してください。 1. ダッシュボードの[決済手段](https://dashboard.stripe.com/settings/payment_methods)設定に移動し、**ステーブルコインと暗号資産**の決済手段をリクエストします。 1. Stripe はアクセスリクエストを審査し、必要に応じて詳細をご連絡する場合があります。リクエストを審査する間、決済手段は**保留中**と表示されます。 1. リクエストが承認されると、ダッシュボードで**ステーブルコインと暗号資産**が有効になります。 ## 動的支払い方法での使用 (Recommended) Stripe のデフォルト[動的支払い方法](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md) を Payment Links、Hosted Checkout、Embedded Checkout Forms、または Elements でご利用の場合、これ以上のアップデートは必要ありません。Stripe は、対象となる顧客にステーブルコインの支払いオプションを自動的に表示します。 ## カスタム導入する場合 必要に応じて、支払い導入に暗号資産による支払い方法を手動で追加することができます。 # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/accept-stablecoin-payments?payment-ui=checkout. 新しい [Checkout セッション](https://docs.stripe.com/api/checkout/sessions.md)を作成する際は、次のことを行う必要があります。 1. `crypto` を `payment_method_types` のリストに追加します。 1. すべての `line_items` が `usd` を使用していることを確認してください。 ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u <>: \ -d mode=payment \ -d "payment_method_types[0]"=crypto \ -d "line_items[0][price_data][currency]"=usd \ -d "line_items[0][price_data][product_data][name]"=T-shirt \ -d "line_items[0][price_data][unit_amount]"=2000 \ -d "line_items[0][quantity]"=1 \ --data-urlencode success_url="https://example.com/success" ``` ## 実装内容をテストする テスト API キーを使用して決済リダイレクトページを開き、暗号資産決済統合をテストします。[テストネットアセット](https://docs.stripe.com/payments/accept-stablecoin-payments.md#testnet-assets) を使用して、決済フローの成功を無料でテストできます。 1. *サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)で、選択した統合方法を使用して新しいトランザクションを作成し、そのリダイレクト URL を開きます。 1. 任意のウォレットと決済ネットワークを接続します。 1. 決済を完了し、想定する URL にリダイレクトされることを確認します。 ### テストネットアセットで決済をテストする ほとんどの暗号資産は、ブロックチェーントランザクションのテストに使用できるテストネットアセット (金銭的価値のないトークン) を提供しています。Stripe は、テストに MetaMask ウォレット、Polygon Amoy テストネット、Circle Faucet を推奨していますが、独自のサービスを使用することもできます。 #### ウォレットをインストールする 1. Web ブラウザ用の [MetaMask 拡張機能をダウンロード](https://metamask.io/download) します。 1. [新しいウォレットを作成](https://support.metamask.io/start/creating-a-new-wallet/) するか、[既存のウォレットをインポート](https://support.metamask.io/start/use-an-existing-wallet/) します。 #### テストネットを有効にする 1. MetaMask ウォレットで、メインメニューから**ネットワーク**を選択します。 1. **カスタムネットワークを追加**をクリックします。 1. 次の詳細を入力します。 - **ネットワーク名**: `Amoy` - **デフォルトの RPC URL**: `https://rpc-amoy.polygon.technology/` - **チェーン ID**: `80002` - **通貨シンボル**: `POL` - **ブロックエクスプローラーの URL**: `https://amoy.polygonscan.com/` 1. **保存** をクリックします。 #### トークンをインポートする 1. MetaMask ウォレットの**トークン**で、ネットワークドロップダウンから **Amoy** を選択します。 1. オーバーフローメニュー (⋯) をクリックし、**トークンのインポート**を選択します。 1. **ネットワークを選択** > **Amoy** をクリックします。 1. **トークンコントラクトアドレス**に、Polygon Amoy のテストネットコントラクトアドレスを貼り付けます。 ``` 0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582 ``` **トークンシンボル**フィールドは `USDC` で自動的に更新され、**小数点以下桁数**フィールドは `6` で更新されます。 1. **次へ** をクリックします。 1. `USDC` トークンをインポートしていることを確認し、**インポート**をクリックします。 MetaMask ウォレットのトークンリストに **POL** と **USDC** が表示されるようになりました。 返金をテストする際、ウォレットに送信されるトークンの契約が、決済に使用されるものとは異なることがあります。ブロックエクスプローラーで返金したトークンの [transaction_hash](https://docs.stripe.com/api/refunds/object.md?rds=1#refund_object-destination_details-crypto-reference) を確認し、そのトークンの契約をウォレットに追加することをお勧めします。たとえば、Sepolia ETH USDC 返金の `0x58277ebcabbe2a6694fbca8daf9e23163dbacf3e` トークンの契約アドレスを確認できます。 #### テストネットアセットを取得する > 一部のテストネットのフォーセットを使用するには、少量のメインネットトークンを保有する必要がある場合があります。 1. [faucet.circle.com](https://faucet.circle.com/) を開きます 1. **USDC** をクリックします。 1. **ネットワーク**で、**Polygon PoS Amoy** を選択します。 1. **送信先**にウォレットアドレスを貼り付けます。 1. **20 USDC を送金**をクリックします。 決済を行うための USDC に加えて、トランザクションコストを支払うための POL が必要です。 1. [faucet.polygon.technology](https://faucet.polygon.technology/) を開きます。 1. **チェーンとトークンの選択**で、**Polygon Amoy** と **POL** を選択します。 1. **本人確認**で、認証に使用するサードパーティプラットフォームをクリックし、ログインプロセスを完了します。 1. **ウォレットアドレスの入力**に、ウォレットアドレスを貼り付けます。 1. **Claim** をクリックします。 テストネットトランザクションの完了には数分かかる場合があります。ウォレットを確認して、USDC と POL が送金されたことを確認してください。 ### その他のテストネット Faucet より多くのテストトークンオプションについては、次の Faucet サービスを確認してください。 - [Paxos USDP](https://faucet.paxos.com/) - [Devnet SOL](https://faucet.solana.com/) - [Sepolia ETH](https://faucets.chain.link/sepolia) - [Amoy POL](https://faucet.polygon.technology/) # Checkout Sessions API > This is a Checkout Sessions API for when payment-ui is elements and api-integration is checkout. View the full page at https://docs.stripe.com/payments/accept-stablecoin-payments?payment-ui=elements&api-integration=checkout. ビジネス ニーズに合った API を判断するには、[比較ガイド](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md) を参照してください。 [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、ウェブサイトまたはアプリケーションにカスタムの Stripe 決済フォームを埋め込み、顧客に決済手段を提供します。高度な設定とカスタマイズについては、[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md)に関する導入ガイドをご覧ください。 [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、ウェブサイトやアプリケーションにカスタム決済フォームを埋め込みます。Payment Element は暗号資産やその他の決済手段に自動的に対応します。追加の設定やカスタマイズオプションについては、[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=checkout)を参照してください。 ## サーバーを設定する [サーバー側] アプリケーションから API にアクセスするには、公式の Stripe ライブラリを使用します。 #### 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' ``` ## Checkout Session を作成する [サーバー側] [Checkout セッション](https://docs.stripe.com/api/checkout/sessions/create.md)を作成してその [Client Secret](https://docs.stripe.com/api/checkout/sessions/object.md#checkout_session_object-client_secret) をフロントエンドに返すエンドポイントを、サーバーに追加します。Checkout セッションは、顧客が 1 回限りの購入またはサブスクリプションの支払いを行う際のセッションを表します。Checkout セッションは作成後 24 時間で期限切れとなります。 [動的支払い方法](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md) を使用して、各顧客に最も関連性の高い支払い方法を動的に表示し、コンバージョンを最大化することをお勧めします。[支払い方法を手動でリスト](https://docs.stripe.com/payments/payment-methods/integration-options.md#listing-payment-methods-manually) して、動的支払い方法を無効にすることもできます。 #### ダッシュボードで支払い方法を管理する #### TypeScript ```javascript import express, {Express} from 'express'; const app: Express = express(); app.post('/create-checkout-session', async (req: Express.Request, res: Express.Response) => { const session = await stripe.checkout.sessions.create({ line_items: [ { price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 1099, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'elements', return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}' }); res.json({checkoutSessionClientSecret: session.client_secret}); }); app.listen(3000, () => { console.log('Running on port 3000'); }); ``` #### 決済手段を手動で一覧表示する #### TypeScript ```javascript import express, {Express} from 'express'; const app: Express = express(); app.post('/create-checkout-session', async (req: Express.Request, res: Express.Response) => { const session = await stripe.checkout.sessions.create({ line_items: [ { price_data: { currency: 'usd', product_data: { name: 'T-shirt', }, unit_amount: 1099, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'elements', payment_method_types: ['crypto'], return_url: 'https://example.com/return?session_id={CHECKOUT_SESSION_ID}' }); res.json({checkoutSessionClientSecret: session.client_secret}); }); app.listen(3000, () => { console.log('Running on port 3000'); }); ``` ## フロントエンドを設定する [クライアント側] #### HTML + JS HTML ファイルの `head` に Stripe.js スクリプトを追加し、チェックアウトページに含めます。PCI への準拠を維持するために、常に js.stripe.com から Stripe.js を直接読み込んでください。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 最新の Stripe.js バージョンであることをご確認の上、以下のスクリプトタグ `` を読み込んでください。詳しくは[Stripe.js バージョン管理](https://docs.stripe.com/sdks/stripejs-versioning.md)をご覧ください。 ```html Checkout ``` > Stripe では npm パッケージをご用意しており、これを使用して Stripe.js をモジュールとして読み込むことができます。[GitHub のプロジェクト](https://github.com/stripe/stripe-js)をご覧ください。バージョン [7.0.0](https://www.npmjs.com/package/%40stripe/stripe-js/v/7.0.0) 以降が必要です。 stripe.js の初期化 ```js // 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( '<>', ); ``` #### React npm のパブリックレジストリーから [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) と [Stripe.js ローダー](https://www.npmjs.com/package/@stripe/stripe-js)をインストールします。バージョン 5.0.0 以上の React Stripe.js と、バージョン 8.0.0 以上の Stripe.js ローダーが必要です。 ```bash npm install --save @stripe/react-stripe-js@^5.0.0 @stripe/stripe-js@^8.0.0 ``` 公開可能キーを使用してフロントエンドで `stripe` インスタンスを初期化します。 ```javascript import {loadStripe} from '@stripe/stripe-js'; const stripe = loadStripe("<>"); ``` ## Checkout を初期化する [クライアント側] #### HTML + JS [initCheckoutElementsSdk](https://docs.stripe.com/js/custom_checkout/init) を呼び出し、`clientSecret` を渡します。 `initCheckoutElementsSdk` は、Checkout Session のデータとそれを更新するメソッドを含む [Checkout](https://docs.stripe.com/js/custom_checkout) オブジェクトを返します。 [actions.getSession()](https://docs.stripe.com/js/custom_checkout/session) から `total` と `lineItems` を読み取り、UI に表示します。これにより、コードの変更を最小限に抑えて新機能を有効にできます。たとえば、[手動通貨価格](https://docs.stripe.com/payments/custom/localize-prices/manual-currency-prices.md)を追加する場合、`total` を表示すれば UI を変更する必要はありません。 ```html
``` ```javascript const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); const checkout = stripe.initCheckoutElementsSdk({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const session = loadActionsResult.actions.getSession(); const checkoutContainer = document.getElementById('checkout-container'); checkoutContainer.append(JSON.stringify(session.lineItems, null, 2)); checkoutContainer.append(document.createElement('br')); checkoutContainer.append(`Total: ${session.total.total.amount}`); } ``` #### React [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) コンポーネントでアプリケーションをラップし、`clientSecret` と `stripe` インスタンスを渡します。 ```jsx import React from 'react'; import {CheckoutElementsProvider} from '@stripe/react-stripe-js/checkout'; import CheckoutForm from './CheckoutForm'; const clientSecret = fetch('/create-checkout-session', {method: 'POST'}) .then((response) => response.json()) .then((json) => json.client_secret); const App = () => { return ( ); }; export default App; ``` [Checkout](https://docs.stripe.com/js/custom_checkout) オブジェクトには、`useCheckoutElements()` フックを使用して決済フォームコンポーネントからアクセスできます。`Checkout` オブジェクトには、Checkout Session のデータとそれを更新するメソッドが含まれています。 `Checkout` オブジェクトから `lineItems` と `lineItems` を読み取り、UI に表示します。これにより、コードの変更を最小限に抑えて機能を有効にできます。たとえば、[手動通貨価格](https://docs.stripe.com/payments/custom/localize-prices/manual-currency-prices.md)を追加する場合、`total` を表示すると UI を変更する必要はありません。 ```jsx import React from 'react'; import {useCheckoutElements} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => {const checkoutState = useCheckoutElements(); if (checkoutState.type === 'loading') { return (
Loading...
); } if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } return (
{JSON.stringify(checkoutState.checkout.lineItems, null, 2)} {/* A formatted total amount */} Total: {checkoutState.checkout.total.total.amount}
); }; ``` ## 顧客のメールアドレスを収集する [クライアント側] #### HTML + JS Checkout Session を完了するには、有効な顧客のメールアドレスを指定する必要があります。 これらの手順では、メールアドレス入力欄を作成し、`Checkout` オブジェクトの [updateEmail](https://docs.stripe.com/js/custom_checkout/update_email) を使用します。 または、以下を実行してください。 - Checkout Session の作成時に、[customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email)、[customer_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) (顧客設定の `Account` オブジェクトとして表される顧客の場合)、または [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) (`Customer` オブジェクトとして表される顧客の場合) を渡します。Stripe はこの方法で提供されたメールアドレスを検証します。 - [checkout.confirm](https://docs.stripe.com/js/custom_checkout/confirm) で既に検証済みのメールアドレスを渡します。 ```html
``` ```javascript const checkout = stripe.initCheckoutElementsSdk({clientSecret}); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const emailInput = document.getElementById('email'); const emailErrors = document.getElementById('email-errors'); emailInput.addEventListener('input', () => { // Clear any validation errors emailErrors.textContent = ''; }); emailInput.addEventListener('blur', () => { const newEmail = emailInput.value;actions.updateEmail(newEmail).then((result) => { if (result.error) { emailErrors.textContent = result.error.message; } }); }); } ``` #### React Checkout Session を完了するには、有効な顧客のメールアドレスを指定する必要があります。 これらの手順では、メールアドレス入力欄を作成し、`Checkout` オブジェクトの [updateEmail](https://docs.stripe.com/js/react_stripe_js/checkout/update_email) を使用します。 または、以下を実行してください。 - Checkout Session の作成時に、[customer_email](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_email)、[customer_account](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer_account) (顧客設定の `Account` オブジェクトとして表される顧客の場合)、または [customer](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-customer) (`Customer` オブジェクトとして表される顧客の場合) を渡します。Stripe はこの方法で提供されたメールアドレスを検証します。 - [confirm](https://docs.stripe.com/js/react_stripe_js/checkout/confirm) で既に検証済みのメールアドレスを渡します。 ```jsx import React from 'react'; import {useCheckoutElements} from '@stripe/react-stripe-js/checkout'; const EmailInput = () => { const checkoutState = useCheckoutElements(); const [email, setEmail] = React.useState(''); const [error, setError] = React.useState(null); if (checkoutState.type === 'loading') { return (
Loading...
); } else if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } const handleBlur = () => {checkoutState.checkout.updateEmail(email).then((result) => { if (result.type === 'error') { setError(result.error); } }) }; const handleChange = (e) => { setError(null); setEmail(e.target.value); }; return (
{error &&
{error.message}
}
); }; export default EmailInput; ``` ## 決済情報を収集する [クライアント側] [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、クライアントで支払い情報を収集します。Payment Element は、さまざまな決済手段で支払い情報の収集を簡略化する事前構築済みの UI コンポーネントです。 Payment Element には、HTTPS 接続を介して支払い情報を Stripe に安全に送信する iframe が含まれています。一部の支払い方法では、支払いを確定するために別のページにリダイレクトする必要があるため、Payment Element を別の iframe 内に配置しないでください。 iframe を使用して Apple Pay または Google Pay を受け付けたい場合は、iframe の [allow](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-allowpaymentrequest) 属性を `"payment *"` と等しく設定する必要があります。 構築済みのシステムを機能させるには、決済ページのアドレスの先頭を `http://` ではなく `https://` にする必要があります。HTTPS を使用しなくてもシステムをテストできますが、本番環境で決済を受け付ける準備が整ったら、必ず、HTTPS を[有効](https://docs.stripe.com/security/guide.md#tls)にしてください。 #### HTML + JS まず、コンテナーの DOM 要素を作成して、[Payment Element](https://docs.stripe.com/payments/payment-element.md) をマウントします。次に、[checkout.createPaymentElement](https://docs.stripe.com/js/custom_checkout/create_payment_element) を使用して `Payment Element` のインスタンスを作成し、[element.mount](https://docs.stripe.com/js/element/mount) を呼び出してマウントし、CSS セレクターまたはコンテナーの DOM 要素を指定します。 ```html
``` ```javascript const paymentElement = checkout.createPaymentElement(); paymentElement.mount('#payment-element'); ``` 対応しているオプションについては、[Stripe.js のドキュメント](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options) をご覧ください。 フロントエンドで Checkout を初期化するときに [elementsOptions.appearance](https://docs.stripe.com/js/custom_checkout/init#custom_checkout_init-options-elementsOptions-appearance) を渡すことで、すべての Elements の[デザインをカスタマイズ](https://docs.stripe.com/payments/checkout/customization/appearance.md)できるようになります。 #### React [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) 内に [Payment Element](https://docs.stripe.com/payments/payment-element.md) コンポーネントをマウントします。 ```jsx import React from 'react';import {PaymentElement, useCheckoutElements} from '@stripe/react-stripe-js/checkout'; const CheckoutForm = () => { const checkoutState = useCheckoutElements(); if (checkoutState.type === 'loading') { return (
Loading...
); } if (checkoutState.type === 'error') { return (
Error: {checkoutState.error.message}
); } return (
{JSON.stringify(checkoutState.checkout.lineItems, null, 2)} {/* A formatted total amount */} Total: {checkoutState.checkout.total.total.amount} ); }; export default CheckoutForm; ``` 対応しているオプションについては、[Stripe.js のドキュメント](https://docs.stripe.com/js/custom_checkout/create_payment_element#custom_checkout_create_payment_element-options) をご覧ください。 [elementsOptions.appearance](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider#react_checkout_provider-options-elementsOptions-appearance) を [CheckoutElementsProvider](https://docs.stripe.com/js/react_stripe_js/checkout/checkout_provider) に渡すことで、すべての Elements の[外観をカスタマイズ](https://docs.stripe.com/payments/checkout/customization/appearance.md)できます。 ## 決済を送信する [クライアント側] #### HTML + JS `Checkout` インスタンスから [確定](https://docs.stripe.com/js/custom_checkout/confirm) を呼び出す**支払う** ボタンをレンダリングして、決済を送信します。 ```html
``` ```js const checkout = stripe.initCheckoutElementsSdk({clientSecret}); checkout.on('change', (session) => { document.getElementById('pay-button').disabled = !session.canConfirm; }); const loadActionsResult = await checkout.loadActions(); if (loadActionsResult.type === 'success') { const {actions} = loadActionsResult; const button = document.getElementById('pay-button'); const errors = document.getElementById('confirm-errors'); button.addEventListener('click', () => { // Clear any validation errors errors.textContent = ''; actions.confirm().then((result) => { if (result.type === 'error') { errors.textContent = result.error.message; } }); }); } ``` #### React 決済を送信するために、[useCheckoutElements](https://docs.stripe.com/js/react_stripe_js/checkout/use_checkout_elements) から [confirm](https://docs.stripe.com/js/custom_checkout/confirm) を呼び出す **Pay** ボタンをレンダリングします。 ```jsx import React from 'react'; import {useCheckoutElements} from '@stripe/react-stripe-js/checkout'; const PayButton = () => { const checkoutState = useCheckoutElements(); const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState(null); if (checkoutState.type !== "success") { return null; } const handleClick = () => { setLoading(true);checkoutState.checkout.confirm().then((result) => { if (result.type === 'error') { setError(result.error) } setLoading(false); }) }; return (
{error &&
{error.message}
}
) }; export default PayButton; ``` ## 導入内容をテストする テスト API キーを使用して決済リダイレクトページを開き、暗号資産決済統合をテストします。[テストネットアセット](https://docs.stripe.com/payments/accept-stablecoin-payments.md#testnet-assets) を使用して、決済フローの成功を無料でテストできます。 1. *サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)で、選択した統合方法を使用して新しいトランザクションを作成し、そのリダイレクト URL を開きます。 1. 任意のウォレットと決済ネットワークを接続します。 1. 決済を完了し、想定する URL にリダイレクトされることを確認します。 ### テストネットアセットで決済をテストする ほとんどの暗号資産は、ブロックチェーントランザクションのテストに使用できるテストネットアセット (金銭的価値のないトークン) を提供しています。Stripe は、テストに MetaMask ウォレット、Polygon Amoy テストネット、Circle Faucet を推奨していますが、独自のサービスを使用することもできます。 #### ウォレットをインストールする 1. Web ブラウザ用の [MetaMask 拡張機能をダウンロード](https://metamask.io/download) します。 1. [新しいウォレットを作成](https://support.metamask.io/start/creating-a-new-wallet/) するか、[既存のウォレットをインポート](https://support.metamask.io/start/use-an-existing-wallet/) します。 #### テストネットを有効にする 1. MetaMask ウォレットで、メインメニューから**ネットワーク**を選択します。 1. **カスタムネットワークを追加**をクリックします。 1. 次の詳細を入力します。 - **ネットワーク名**: `Amoy` - **デフォルトの RPC URL**: `https://rpc-amoy.polygon.technology/` - **チェーン ID**: `80002` - **通貨シンボル**: `POL` - **ブロックエクスプローラーの URL**: `https://amoy.polygonscan.com/` 1. **保存** をクリックします。 #### トークンをインポートする 1. MetaMask ウォレットの**トークン**で、ネットワークドロップダウンから **Amoy** を選択します。 1. オーバーフローメニュー (⋯) をクリックし、**トークンのインポート**を選択します。 1. **ネットワークを選択** > **Amoy** をクリックします。 1. **トークンコントラクトアドレス**に、Polygon Amoy のテストネットコントラクトアドレスを貼り付けます。 ``` 0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582 ``` **トークンシンボル**フィールドは `USDC` で自動的に更新され、**小数点以下桁数**フィールドは `6` で更新されます。 1. **次へ** をクリックします。 1. `USDC` トークンをインポートしていることを確認し、**インポート**をクリックします。 MetaMask ウォレットのトークンリストに **POL** と **USDC** が表示されるようになりました。 返金をテストする際、ウォレットに送信されるトークンの契約が、決済に使用されるものとは異なることがあります。ブロックエクスプローラーで返金したトークンの [transaction_hash](https://docs.stripe.com/api/refunds/object.md?rds=1#refund_object-destination_details-crypto-reference) を確認し、そのトークンの契約をウォレットに追加することをお勧めします。たとえば、Sepolia ETH USDC 返金の `0x58277ebcabbe2a6694fbca8daf9e23163dbacf3e` トークンの契約アドレスを確認できます。 #### テストネットアセットを取得する > 一部のテストネットのフォーセットを使用するには、少量のメインネットトークンを保有する必要がある場合があります。 1. [faucet.circle.com](https://faucet.circle.com/) を開きます 1. **USDC** をクリックします。 1. **ネットワーク**で、**Polygon PoS Amoy** を選択します。 1. **送信先**にウォレットアドレスを貼り付けます。 1. **20 USDC を送金**をクリックします。 決済を行うための USDC に加えて、トランザクションコストを支払うための POL が必要です。 1. [faucet.polygon.technology](https://faucet.polygon.technology/) を開きます。 1. **チェーンとトークンの選択**で、**Polygon Amoy** と **POL** を選択します。 1. **本人確認**で、認証に使用するサードパーティプラットフォームをクリックし、ログインプロセスを完了します。 1. **ウォレットアドレスの入力**に、ウォレットアドレスを貼り付けます。 1. **Claim** をクリックします。 テストネットトランザクションの完了には数分かかる場合があります。ウォレットを確認して、USDC と POL が送金されたことを確認してください。 ### その他のテストネット Faucet より多くのテストトークンオプションについては、次の Faucet サービスを確認してください。 - [Paxos USDP](https://faucet.paxos.com/) - [Devnet SOL](https://faucet.solana.com/) - [Sepolia ETH](https://faucets.chain.link/sepolia) - [Amoy POL](https://faucet.polygon.technology/) # Payment Intents API > This is a Payment Intents API for when payment-ui is elements and api-integration is paymentintents. View the full page at https://docs.stripe.com/payments/accept-stablecoin-payments?payment-ui=elements&api-integration=paymentintents. ビジネス ニーズに合った API を判断するには、[比較ガイド](https://docs.stripe.com/payments/checkout-sessions-and-payment-intents-comparison.md) を参照してください。 [Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、ウェブサイトまたはアプリケーションにカスタムの Stripe 決済フォームを埋め込み、顧客に決済手段を提供します。高度な設定とカスタマイズについては、[決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md)に関する導入ガイドをご覧ください。 ## 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' ``` ## 決済情報を収集する [クライアント側] Payment Element を使用してクライアントで支払い詳細を収集する準備ができました。Payment Element は事前構築された UI コンポーネントであり、多様な支払い方法の支払い詳細の収集を容易にします。 Payment Element には、HTTPS 接続を介して支払い情報を Stripe に安全に送信する iframe が含まれています。決済手段によっては、支払い確認のために別のページにリダイレクトする必要があるため、Payment Element を別の iframe 内に配置しないでください。 実装を機能させるには、決済ページのアドレスの先頭を `http://` ではなく `https://` にする必要があります。HTTPS を使用せずに実装をテストすることはできますが、本番環境で支払いを受け付ける準備が整ったら、忘れずに[有効にしてください](https://docs.stripe.com/security/guide.md#tls)。 #### HTML + JS ### Stripe.js を設定する Payment Element は Stripe.js の機能として自動的に使用できるようになります。決済ページに Stripe.js スクリプトを含めるには、HTML ファイルの `head` にスクリプトを追加します。常に js.stripe.com から Stripe.js を直接読み込むことにより、PCI 準拠が維持されます。スクリプトをバンドルに含めたり、そのコピーを自身でホストしたりしないでください。 ```html Checkout ``` 購入ページで次の JavaScript を使用して、Stripe のインスタンスを作成します。 ```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('<>'); ``` ### Payment Element を決済ページに追加する 決済ページに Payment Element を配置する場所が必要です。決済フォームで、一意の ID を持つ空の DOM ノード (コンテナー) を作成します。 ```html
``` #### ダッシュボードから決済手段を管理する 上記のフォームが読み込まれたら、`mode`、`amount`、`currency` を指定して Elements インスタンスを作成します。これらの値によって、顧客に表示される決済手段が決まります。フォームで新しい決済手段を指定するには、必ず[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で有効にしてください。 ```javascript const options = {mode:'payment', amount:1099, currency: 'usd', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout formconst elements = stripe.elements(options); // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### 支払い方法を手動で一覧表示する 使用可能にしたい決済方法を手動でリストするには、それぞれを `paymentMethodTypes` に追加してください。 次に、Payment Element のインスタンスを作成し、コンテナーの DOM ノードにマウントします。 ```javascript const options = {mode:'payment', amount:1099, currency: 'usd', paymentMethodTypes: ['crypto'], // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout formconst elements = stripe.elements(options); // Create and mount the Payment Element const paymentElementOptions = { layout: 'accordion'}; const paymentElement = elements.create('payment', paymentElementOptions); paymentElement.mount('#payment-element'); ``` #### React ### Stripe.js を設定する npm パブリックレジストリーから [React Stripe.js](https://www.npmjs.com/package/@stripe/react-stripe-js) と [Stripe.js ローダー](https://www.npmjs.com/package/@stripe/stripe-js)をインストールします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Elements プロバイダーを決済ページに追加して設定する Payment Element コンポーネントを使用するには、購入ページコンポーネントを [Elements プロバイダー](https://docs.stripe.com/sdks/stripejs-react.md#elements-provider)でラップします。公開可能キーを使用して `loadStripe` を呼び出し、返された `Promise` を `Elements` プロバイダーに渡します。 #### ダッシュボードから決済手段を管理する `Elements` プロバイダーは、`mode`、`amount`、`currency` も受け入れます。これらの値によって、顧客に表示される決済手段が決まります。フォームで新しい決済手段を指定するには、[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で有効にしてください。 ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const options = {mode:'payment', amount:1099, currency: 'usd', // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` #### 支払い方法を手動で一覧表示する ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import {Elements} from '@stripe/react-stripe-js'; import {loadStripe} from '@stripe/stripe-js'; import CheckoutForm from './CheckoutForm'; // Make sure to call `loadStripe` outside of a component’s render to avoid // recreating the `Stripe` object on every render. const stripePromise = loadStripe('<>'); function App() { const options = {mode:'payment', amount:1099, currency: 'usd', paymentMethodTypes: ['crypto'], // Fully customizable with appearance API. appearance: {/*...*/}, }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Payment Element コンポーネントを追加 `PaymentElement` コンポーネントを使用して、フォームを構築します。 ```jsx import React from 'react'; import {PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { return (
); }; export default CheckoutForm; ``` `Elements` プロバイダーを作成する際に [Appearance (デザイン) オブジェクト](https://docs.stripe.com/elements/appearance-api.md) を `options` に渡すことで、サイトのデザインに合わせて Payment Element をカスタマイズできます。 ### 住所を収集 デフォルトでは、Payment Element は必要な請求住所の詳細のみを収集します。[税金の計算](https://docs.stripe.com/api/tax/calculations/create.md)、配送先情報を入力するなどの一部の動作では、顧客の完全な住所が必要です。次のように対応できます。 - [Address Element](https://docs.stripe.com/elements/address-element.md) を使用して、オートコンプリートとローカリゼーションの機能を利用して、顧客の完全な住所を収集します。これにより、最も正確な税金計算が可能になります。 - 独自のカスタムフォームを使用して住所の詳細を収集する。 ## PaymentIntent を作成する [サーバー側] > #### 支払い確定の直前にカスタムのビジネスロジックを実行する > > 支払いの確定ガイドの[ステップ 5](https://docs.stripe.com/payments/finalize-payments-on-the-server.md?platform=web&type=payment#submit-payment) に移動して、支払い確定の直前にカスタムのビジネスロジックを実行します。または、以下のステップに従って既存のシステムをシンプルにします。ここでは、クライアント側で `stripe.confirmPayment` を使用して、支払いの確定と次のアクションの処理の両方を行います。 #### ダッシュボードから決済手段を管理する 顧客が支払いフォームを送信したら、*PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) を使用して確認と支払いのプロセスを適切に管理します。`amount` と `currency` を指定してサーバー側で PaymentIntent を作成します。悪意のある顧客が独自の価格を選択できないように、請求金額はクライアント側ではなく、常にサーバー側 (信頼できる環境) で決定してください。 `PaymentIntent` には、*client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) が含まれています。Stripe.js がこの値を使用して決済プロセスを安全に完了できるように、この値をクライアントに返します。 #### Accounts v2 #### Ruby ```ruby require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = Stripe::StripeClient.new('<>') post '/create-intent' do intent = client.v1.payment_intents.create({ # To allow saving and retrieving payment methods, provide the customer's Account ID. customer_account: "{{CUSTOMER_ACCOUNT_ID}}", amount: 1099, currency: 'usd', }) {client_secret: intent.client_secret}.to_json end ``` #### Customers v1 #### Ruby ```ruby require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = Stripe::StripeClient.new('<>') post '/create-intent' do intent = client.v1.payment_intents.create({ # To allow saving and retrieving payment methods, provide the Customer ID. customer: customer.id, amount: 1099, currency: 'usd', }) {client_secret: intent.client_secret}.to_json end ``` #### 支払い方法を手動で一覧表示する 顧客が決済フォームを送信したら、*PaymentIntent* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) を使用して確認と決済のプロセスがスムーズに進むようにします。`amount`、`currency`、および `payment_method_types` で 1 つ以上の決済手段を指定して、サーバーで PaymentIntent を作成します。悪意のある顧客が価格を操作できないように、請求金額はクライアント側ではなく、常にサーバー側 (信頼できる環境) で決定してください。 PaymentIntent には、*client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) が含まれています。 この値をクライアントに返し、Stripe.js がこれを使用して支払いプロセスを安全に完了できるようにします。 #### Accounts v2 #### Ruby ```ruby require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = Stripe::StripeClient.new('<>') post '/create-intent' do intent = client.v1.payment_intents.create({ # To allow saving and retrieving payment methods, provide the customer's Account ID. customer_account: customer_account.id, amount: 1099, currency: 'usd', payment_method_types: ['crypto'], }) {client_secret: intent.client_secret}.to_json end ``` #### Customers v1 #### Ruby ```ruby require 'stripe' # Don't put any keys in code. See https://docs.stripe.com/keys-best-practices. client = Stripe::StripeClient.new('<>') post '/create-intent' do intent = client.v1.payment_intents.create({ # To allow saving and retrieving payment methods, provide the Customer ID. customer: customer.id, amount: 1099, currency: 'usd', payment_method_types: ['crypto'], }) {client_secret: intent.client_secret}.to_json end ``` ## Stripe に支払いをする [クライアント側] [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を使用して、Payment Element の詳細を使って支払いを完了します。 この関数に [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を指定して、支払い完了後に Stripe がユーザーをリダイレクトする場所を示します。ユーザーは、最初に銀行の認証ページなどの中間サイトにリダイレクトされてから、`return_url` にリダイレクトされる場合があります。カード支払いでは、支払いが成功するとすぐに `return_url` にリダイレクトされます。 支払い完了後にカード支払いのリダイレクトを行わない場合は、[redirect](https://docs.stripe.com/js/payment_intents/confirm_payment#confirm_payment_intent-options-redirect) を `if_required` に設定できます。これにより、リダイレクトベースの決済手段で購入した顧客のみがリダイレクトされます。 #### HTML + JS ```javascript const form = document.getElementById('payment-form'); const submitBtn = document.getElementById('submit'); const handleError = (error) => { const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; submitBtn.disabled = false; } form.addEventListener('submit', async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); // Prevent multiple form submissions if (submitBtn.disabled) { return; } // Disable form submission while loading submitBtn.disabled = true; // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create the PaymentIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent using the details collected by the Payment Element const {error} = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(error); } else { // Your customer is redirected to your `return_url`. For some payment // methods like iDEAL, your customer is redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }); ``` #### React ```jsx import React, {useState} from 'react'; import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js'; export default function CheckoutForm() { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(); const [loading, setLoading] = useState(false); const handleError = (error) => { setLoading(false); setErrorMessage(error.message); } const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } setLoading(true); // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { handleError(submitError); return; } // Create the PaymentIntent and obtain clientSecret const res = await fetch("/create-intent", { method: "POST", }); const {client_secret: clientSecret} = await res.json(); // Confirm the PaymentIntent using the details collected by the Payment Element const {error} = await stripe.confirmPayment({ elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point is only reached if there's an immediate error when // confirming the payment. Show the error to your customer (for example, payment details incomplete) handleError(error); } else { // Your customer is redirected to your `return_url`. For some payment // methods like iDEAL, your customer is redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return (
{errorMessage &&
{errorMessage}
} ); } ``` ## Optional: サーバーから更新を取得する [クライアント側] Payment Element が表示された後、PaymentIntent の [amount](https://docs.stripe.com/api/payment_intents/update.md#update_payment_intent-amount) などの属性を更新することができます (割引コードや配送料金など)。サーバー側で [PaymentIntent を更新](https://docs.stripe.com/api/payment_intents/update.md)して、[elements.fetchUpdates](https://docs.stripe.com/js/elements_object/fetch_updates) を呼び出すと、Payment Element に反映された新しい金額を確認できます。次の例では、PaymentIntent の amount (金額) を更新するサーバーエンドポイントを作成する方法を示しています。 #### 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. client = Stripe::StripeClient.new('<>') get '/update' do intent = client.v1.payment_intents.update( '{{PAYMENT_INTENT_ID}}', {amount: 1499}, ) {status: intent.status}.to_json end ``` この例は、クライアント側でこれらの変更を反映するために UI を更新する方法を示しています。 ```javascript (async () => { const response = await fetch('/update'); if (response.status === 'requires_payment_method') { const {error} = await elements.fetchUpdates(); } })(); ``` ## Optional: リダイレクトを手動で処理する [サーバー側] リダイレクトを処理するには、`confirmPayment` を指定して Stripe.js を使用することをお勧めします。顧客を手動でリダイレクトする場合の方法を紹介します。 1. 顧客が支払いを完了した後にリダイレクトされる URL を指定します。 ```curl curl https://api.stripe.com/v1/payment_intents/pi_1DRuHnHgsMRlo4MtwuIAUe6u/confirm \ -u "<>:" \ -d payment_method=pm_1EnPf7AfTbPYpBIFLxIc8SD9 \ --data-urlencode "return_url=https://shop.example.com/crtA6B28E1" ``` 1. `PaymentIntent` のステータスが `requires_action` であることを確認します。`next_action` のタイプは `redirect_to_url` になります。 ```json "next_action": { "type": "redirect_to_url", "redirect_to_url": { "url": "https://hooks.stripe.com/...", "return_url": "https://example.com/checkout/complete" } } ``` 1. `next_action` プロパティで指定された URL に顧客をリダイレクトします。 支払いプロセスを完了した顧客は、`return_url` の指定先に送られます。`payment_intent` と `payment_intent_client_secret` の URL クエリパラメーターが含まれます。上記のように、自社で作成したクエリパラメーターを渡すことができます。 ## Optional: 支払い後のイベントを処理する 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。ダッシュボード、カスタム *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests)、またはパートナーソリューションを使用してこれらのイベントを受信し、また、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアント側では、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了したりする可能性があります。また、悪意を持つクライアントがレスポンスを不正操作する恐れもあります。非同期型のイベントをリッスンするよう構築済みのシステムを設定することで、これ以降はより多くの決済手段を簡単に受け付けられるようになります。[サポートされているすべての決済手段の違い](https://stripe.com/payments/payment-methods-guide)をご確認ください。 - **ダッシュボードでイベントを手動で処理する** ダッシュボードを使用して、テスト決済を[ダッシュボードで表示](https://dashboard.stripe.com/test/payments)したり、メール領収書を送信したり、入金を処理したり、失敗した決済を再試行したりできます。 - **Custom Webhook を構築する** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **構築済みアプリを導入する** パートナーアプリケーションを統合することで、[自動化](https://stripe.partners/?f_category=automation)や[マーケティング/セールス](https://stripe.partners/?f_category=marketing-and-sales)などの一般的なビジネスイベントを処理します。 ## 導入内容をテストする テスト API キーを使用して決済リダイレクトページを開き、暗号資産決済統合をテストします。[テストネットアセット](https://docs.stripe.com/payments/accept-stablecoin-payments.md#testnet-assets) を使用して、決済フローの成功を無料でテストできます。 1. *サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)で、選択した統合方法を使用して新しいトランザクションを作成し、そのリダイレクト URL を開きます。 1. 任意のウォレットと決済ネットワークを接続します。 1. 決済を完了し、想定する URL にリダイレクトされることを確認します。 ### テストネットアセットで決済をテストする ほとんどの暗号資産は、ブロックチェーントランザクションのテストに使用できるテストネットアセット (金銭的価値のないトークン) を提供しています。Stripe は、テストに MetaMask ウォレット、Polygon Amoy テストネット、Circle Faucet を推奨していますが、独自のサービスを使用することもできます。 #### ウォレットをインストールする 1. Web ブラウザ用の [MetaMask 拡張機能をダウンロード](https://metamask.io/download) します。 1. [新しいウォレットを作成](https://support.metamask.io/start/creating-a-new-wallet/) するか、[既存のウォレットをインポート](https://support.metamask.io/start/use-an-existing-wallet/) します。 #### テストネットを有効にする 1. MetaMask ウォレットで、メインメニューから**ネットワーク**を選択します。 1. **カスタムネットワークを追加**をクリックします。 1. 次の詳細を入力します。 - **ネットワーク名**: `Amoy` - **デフォルトの RPC URL**: `https://rpc-amoy.polygon.technology/` - **チェーン ID**: `80002` - **通貨シンボル**: `POL` - **ブロックエクスプローラーの URL**: `https://amoy.polygonscan.com/` 1. **保存** をクリックします。 #### トークンをインポートする 1. MetaMask ウォレットの**トークン**で、ネットワークドロップダウンから **Amoy** を選択します。 1. オーバーフローメニュー (⋯) をクリックし、**トークンのインポート**を選択します。 1. **ネットワークを選択** > **Amoy** をクリックします。 1. **トークンコントラクトアドレス**に、Polygon Amoy のテストネットコントラクトアドレスを貼り付けます。 ``` 0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582 ``` **トークンシンボル**フィールドは `USDC` で自動的に更新され、**小数点以下桁数**フィールドは `6` で更新されます。 1. **次へ** をクリックします。 1. `USDC` トークンをインポートしていることを確認し、**インポート**をクリックします。 MetaMask ウォレットのトークンリストに **POL** と **USDC** が表示されるようになりました。 返金をテストする際、ウォレットに送信されるトークンの契約が、決済に使用されるものとは異なることがあります。ブロックエクスプローラーで返金したトークンの [transaction_hash](https://docs.stripe.com/api/refunds/object.md?rds=1#refund_object-destination_details-crypto-reference) を確認し、そのトークンの契約をウォレットに追加することをお勧めします。たとえば、Sepolia ETH USDC 返金の `0x58277ebcabbe2a6694fbca8daf9e23163dbacf3e` トークンの契約アドレスを確認できます。 #### テストネットアセットを取得する > 一部のテストネットのフォーセットを使用するには、少量のメインネットトークンを保有する必要がある場合があります。 1. [faucet.circle.com](https://faucet.circle.com/) を開きます 1. **USDC** をクリックします。 1. **ネットワーク**で、**Polygon PoS Amoy** を選択します。 1. **送信先**にウォレットアドレスを貼り付けます。 1. **20 USDC を送金**をクリックします。 決済を行うための USDC に加えて、トランザクションコストを支払うための POL が必要です。 1. [faucet.polygon.technology](https://faucet.polygon.technology/) を開きます。 1. **チェーンとトークンの選択**で、**Polygon Amoy** と **POL** を選択します。 1. **本人確認**で、認証に使用するサードパーティプラットフォームをクリックし、ログインプロセスを完了します。 1. **ウォレットアドレスの入力**に、ウォレットアドレスを貼り付けます。 1. **Claim** をクリックします。 テストネットトランザクションの完了には数分かかる場合があります。ウォレットを確認して、USDC と POL が送金されたことを確認してください。 ### その他のテストネット Faucet より多くのテストトークンオプションについては、次の Faucet サービスを確認してください。 - [Paxos USDP](https://faucet.paxos.com/) - [Devnet SOL](https://faucet.solana.com/) - [Sepolia ETH](https://faucets.chain.link/sepolia) - [Amoy POL](https://faucet.polygon.technology/) ## エラーコード 次の表に、一般的なエラーコードと推奨される対応の詳細を示します。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent_invalid_currency` | 対応している通貨を入力してください。 | | `missing_required_parameter` | 必須パラメーターの詳細については、エラーメッセージをご確認ください。 | | `payment_intent_payment_attempt_failed` | このコードは、PaymentIntent の [last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) フィールドに表示されることがあります。エラーメッセージで、エラーの詳細な理由とエラー処理に関する提案を確認してください。 | | `payment_intent_authentication_failure` | このコードは、PaymentIntent の[last_payment_error.code](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-last_payment_error-code) フィールドに表示されることがあります。エラーメッセージで、詳細な失敗理由とエラー処理に関する推奨事項を確認してください。このエラーは、統合のテスト時に失敗を手動でトリガーした場合に発生します。 | | `payment_intent_redirect_confirmation_without_return_url` | PaymentIntent を確定する際は、`return_url` を指定します。 | # ダイレクト API > This is a ダイレクト API for when payment-ui is direct-api. View the full page at https://docs.stripe.com/payments/accept-stablecoin-payments?payment-ui=direct-api. *Payment Intents API* (The Payment Intents API tracks the lifecycle of a customer checkout flow and triggers additional authentication steps when required by regulatory mandates, custom Radar fraud rules, or redirect-based payment methods) を通じて、Pay with Crypto を直接統合します。 ## Stripe を設定する [サーバ側] まず、[Stripe アカウントを作成する](https://dashboard.stripe.com/register)か[サインイン](https://dashboard.stripe.com/login)します。 アプリケーションから Stripe API にアクセスするには、Stripe の公式ライブラリを使用します。 #### 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' ``` ## PaymentIntent を作成し、client secret を取得する [サーバー側] [PaymentIntent](https://docs.stripe.com/api/payment_intents.md) オブジェクトは、顧客から支払いを徴収する意図を表し、支払いプロセスのライフサイクルを追跡します。サーバーにPaymentIntentを作成し、徴収する金額と対応する通貨を指定します。既存の PaymentIntent を導入している場合は、[payment_method_types](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types) のリストに `crypto` を追加します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=crypto" ``` ### client secret を取得する PaymentIntent には、*client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) が含まれています。これは、支払いプロセスを安全に完了するためにクライアント側で使用されます。client secret をクライアント側に渡す際は、いくつかの方法を使用できます。 #### 1 ページのアプリケーション ブラウザーの `fetch` 関数を使用して、サーバーのエンドポイントから client secret を取得します。この方法は、クライアント側が 1 ページのアプリケーションで、特に React などの最新のフロントエンドフレームワークで構築されている場合に最適です。client secret を処理するサーバーのエンドポイントを作成します。 #### Ruby ```ruby get '/secret' do intent = # ... Create or retrieve the PaymentIntent {client_secret: intent.client_secret}.to_json end ``` その後、クライアント側で JavaScript を使用して client secret を取得します。 ```javascript (async () => { const response = await fetch('/secret'); const {client_secret: clientSecret} = await response.json(); // Render the form using the clientSecret })(); ``` #### サーバ側のレンダリング サーバーからクライアントに client secret を渡します。この方法は、アプリケーションがブラウザーへの送信前に静的なコンテンツをサーバーで生成する場合に最適です。 決済フォームに [client_secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を追加します。サーバー側のコードで、PaymentIntent から client secret を取得します。 #### Ruby ```erb
``` ```ruby get '/checkout' do @intent = # ... Fetch or create the PaymentIntent erb :checkout end ``` ## ステーブルコインの支払いページへのリダイレクト 顧客が支払い方法として **仮想通貨** を選択した場合に、[Stripe.js](https://docs.stripe.com/js.md) を使用して Stripe に支払いを送信します。Stripe.js は、支払いフローを構築するための基本的な JavaScript ライブラリです。このライブラリにより、以下で説明するリダイレクトなどの複雑な処理が自動的に行われ、実装を他の支払い方法にも拡張できます。Stripe.js スクリプトは、HTML ファイルの `` に追加して、Checkout ページに含めます。 ```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('<>'); ``` PaymentIntent の [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を使用して `stripe.confirmPayment` を呼び出し、Pay with Crypto のリダイレクトを処理します。`return_url` を追加して、決済完了後に顧客をリダイレクトする場所を指定します。 ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async function(event) { event.preventDefault(); // Set the clientSecret of the PaymentIntent const { error } = await stripe.confirmPayment({ clientSecret: clientSecret, confirmParams: { payment_method_data: { type: 'crypto', }, // Return URL where the customer should be redirected after the authorization return_url: `${window.location.href}`, }, }); if (error) { // Inform the customer that there was an error. const errorElement = document.getElementById('error-message'); errorElement.textContent = result.error.message; } }); ``` `return_url` は、支払いの結果を表示する、お客様のウェブサイトのページに相当します。PaymentIntent の[ステータスを確認](https://docs.stripe.com/payments/payment-intents/verifying-status.md#checking-status)して、表示する内容を決定します。ステータス確認のために Stripe がリダイレクトする `return_url` には、次の URL クエリパラメーターが含まれています。また、独自のクエリパラメーターを `return_url` に追加することもできます。設定したパラメーターは、リダイレクトプロセス全体にわたって保持されます。 | | | | | `payment_intent` | `PaymentIntent` の一意の ID。 | | `payment_intent_client_secret` | `PaymentIntent` オブジェクトの [Client Secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。 | ## Optional: 支払い後のイベントを処理する 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。ダッシュボード、カスタム [Webhook](https://docs.stripe.com/webhooks.md)、またはパートナーソリューションを使用して、これらのイベントを受信し、顧客への注文確認メールの送信、データベースへの販売の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待たずにこれらのイベントをリッスンします。クライアント側では、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了したりする可能性があるだけでなく、不正なクライアントによってレスポンスが操作される可能性もあります。非同期イベントをリッスンするようにシステムを設定すると、今後より多くの決済手段を受け付けられるようになります。サポートされている決済手段のそれぞれの違いについては、[決済手段](https://stripe.com/payments/payment-methods-guide)ガイドをご確認ください。 ### イベントを受信し、ビジネスアクションを実行する ビジネスアクションを受信して実行するためのオプションとして、以下をご利用いただけます。 - **手動処理:** [Stripe ダッシュボード](https://dashboard.stripe.com/test/payments)を使用して、Stripe Payments の表示、メール領収書の送信、入金処理、失敗した支払いの再試行などを処理します。 - **カスタムコード:** [Webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) ハンドラを構築してイベントを受信し、非同期型のカスタムの決済フローを作成します。Stripe CLI を使用して、ローカルで Webhook の実装のテストとデバッグを行います。 - **事前構築済みアプリ:** パートナーアプリケーションと連携して、[自動化](https://stripe.partners/?f_category=automation)や[マーケティングセールス](https://stripe.partners/?f_category=marketing-and-sales)などの一般的なビジネスイベントを処理します。 ### サポートされている通貨 顧客の国に対応する通貨で暗号資産での支払いを作成できます。暗号資産のデフォルトの現地通貨は USD ですが、顧客は購入金額をこの通貨でも確認できます。 ## Optional: リダイレクトを手動で処理する [サーバー側] リダイレクトを処理するには、`confirmPayment` を指定して Stripe.js を使用することをお勧めします。顧客を手動でリダイレクトする場合の方法を紹介します。 1. 顧客が支払いを完了した後にリダイレクトされる URL を指定します。 ```curl curl https://api.stripe.com/v1/payment_intents/pi_1DRuHnHgsMRlo4MtwuIAUe6u/confirm \ -u "<>:" \ -d payment_method=pm_1EnPf7AfTbPYpBIFLxIc8SD9 \ --data-urlencode "return_url=https://shop.example.com/crtA6B28E1" ``` 1. `PaymentIntent` のステータスが `requires_action` であることを確認します。`next_action` のタイプは `redirect_to_url` になります。 ```json "next_action": { "type": "redirect_to_url", "redirect_to_url": { "url": "https://hooks.stripe.com/...", "return_url": "https://example.com/checkout/complete" } } ``` 1. `next_action` プロパティで指定された URL に顧客をリダイレクトします。 支払いプロセスを完了した顧客は、`return_url` の指定先に送られます。`payment_intent` と `payment_intent_client_secret` の URL クエリパラメーターが含まれます。上記のように、自社で作成したクエリパラメーターを渡すことができます。 ## 実装内容をテストする テスト API キーを使用して決済リダイレクトページを開き、暗号資産決済統合をテストします。[テストネットアセット](https://docs.stripe.com/payments/accept-stablecoin-payments.md#testnet-assets) を使用して、決済フローの成功を無料でテストできます。 1. *サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)で、選択した統合方法を使用して新しいトランザクションを作成し、そのリダイレクト URL を開きます。 1. 任意のウォレットと決済ネットワークを接続します。 1. 決済を完了し、想定する URL にリダイレクトされることを確認します。 ### テストネットアセットで決済をテストする ほとんどの暗号資産は、ブロックチェーントランザクションのテストに使用できるテストネットアセット (金銭的価値のないトークン) を提供しています。Stripe は、テストに MetaMask ウォレット、Polygon Amoy テストネット、Circle Faucet を推奨していますが、独自のサービスを使用することもできます。 #### ウォレットをインストールする 1. Web ブラウザ用の [MetaMask 拡張機能をダウンロード](https://metamask.io/download) します。 1. [新しいウォレットを作成](https://support.metamask.io/start/creating-a-new-wallet/) するか、[既存のウォレットをインポート](https://support.metamask.io/start/use-an-existing-wallet/) します。 #### テストネットを有効にする 1. MetaMask ウォレットで、メインメニューから**ネットワーク**を選択します。 1. **カスタムネットワークを追加**をクリックします。 1. 次の詳細を入力します。 - **ネットワーク名**: `Amoy` - **デフォルトの RPC URL**: `https://rpc-amoy.polygon.technology/` - **チェーン ID**: `80002` - **通貨シンボル**: `POL` - **ブロックエクスプローラーの URL**: `https://amoy.polygonscan.com/` 1. **保存** をクリックします。 #### トークンをインポートする 1. MetaMask ウォレットの**トークン**で、ネットワークドロップダウンから **Amoy** を選択します。 1. オーバーフローメニュー (⋯) をクリックし、**トークンのインポート**を選択します。 1. **ネットワークを選択** > **Amoy** をクリックします。 1. **トークンコントラクトアドレス**に、Polygon Amoy のテストネットコントラクトアドレスを貼り付けます。 ``` 0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582 ``` **トークンシンボル**フィールドは `USDC` で自動的に更新され、**小数点以下桁数**フィールドは `6` で更新されます。 1. **次へ** をクリックします。 1. `USDC` トークンをインポートしていることを確認し、**インポート**をクリックします。 MetaMask ウォレットのトークンリストに **POL** と **USDC** が表示されるようになりました。 返金をテストする際、ウォレットに送信されるトークンの契約が、決済に使用されるものとは異なることがあります。ブロックエクスプローラーで返金したトークンの [transaction_hash](https://docs.stripe.com/api/refunds/object.md?rds=1#refund_object-destination_details-crypto-reference) を確認し、そのトークンの契約をウォレットに追加することをお勧めします。たとえば、Sepolia ETH USDC 返金の `0x58277ebcabbe2a6694fbca8daf9e23163dbacf3e` トークンの契約アドレスを確認できます。 #### テストネットアセットを取得する > 一部のテストネットのフォーセットを使用するには、少量のメインネットトークンを保有する必要がある場合があります。 1. [faucet.circle.com](https://faucet.circle.com/) を開きます 1. **USDC** をクリックします。 1. **ネットワーク**で、**Polygon PoS Amoy** を選択します。 1. **送信先**にウォレットアドレスを貼り付けます。 1. **20 USDC を送金**をクリックします。 決済を行うための USDC に加えて、トランザクションコストを支払うための POL が必要です。 1. [faucet.polygon.technology](https://faucet.polygon.technology/) を開きます。 1. **チェーンとトークンの選択**で、**Polygon Amoy** と **POL** を選択します。 1. **本人確認**で、認証に使用するサードパーティプラットフォームをクリックし、ログインプロセスを完了します。 1. **ウォレットアドレスの入力**に、ウォレットアドレスを貼り付けます。 1. **Claim** をクリックします。 テストネットトランザクションの完了には数分かかる場合があります。ウォレットを確認して、USDC と POL が送金されたことを確認してください。 ### その他のテストネット Faucet より多くのテストトークンオプションについては、次の Faucet サービスを確認してください。 - [Paxos USDP](https://faucet.paxos.com/) - [Devnet SOL](https://faucet.solana.com/) - [Sepolia ETH](https://faucets.chain.link/sepolia) - [Amoy POL](https://faucet.polygon.technology/) # iOS > This is a iOS for when payment-ui is mobile and platform is ios. View the full page at https://docs.stripe.com/payments/accept-stablecoin-payments?payment-ui=mobile&platform=ios. Stripe では、埋め込み可能な決済フォームである [Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?=ios) の使用を推奨しています。Pay with Crypto やその他の決済手段を最小限の労力でシステムに追加することが可能です。 Pay with Crypto は、支払いの[認証](https://docs.stripe.com/payments/payment-methods.md#customer-actions)が顧客に義務付けられている、[1 回限り](https://docs.stripe.com/payments/payment-methods.md#usage)の決済手段です。顧客はアプリからリダイレクトされ、Stripe Crypto で支払いをオーソリしてから、またアプリに戻ります。支払いが成功または失敗すると、[すぐに通知](https://docs.stripe.com/payments/payment-methods.md#payment-notification)されます。 ## Stripe を設定する [サーバ側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 ### サーバ側 この組み込みには、サーバ上に Stripe API と通信するエンドポイントが必要です。サーバから Stripe API にアクセスするには、Stripe の公式ライブラリを使用します。 #### 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 iOS SDK](https://github.com/stripe/stripe-ios) はオープンソースです。[詳細なドキュメントが提供されており](https://stripe.dev/stripe-ios/index.html)、iOS 13 以降をサポートするアプリと互換性があります。 #### Swift Package Manager SDK をインストールするには、以下のステップに従います。 1. Xcode で、**File (ファイル)** > **Add Package Dependencies… (パッケージ依存関係を追加)** を選択し、リポジトリー URL として `https://github.com/stripe/stripe-ios-spm` を入力します。 1. [リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択します。 1. **StripePaymentsUI** 製品を[アプリのターゲット](https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app)に追加します。 #### CocoaPods 1. まだインストールしていない場合は、[CocoaPods](https://guides.cocoapods.org/using/getting-started.html) の最新バージョンをインストールします。 1. 既存の [Podfile](https://guides.cocoapods.org/syntax/podfile.html) がない場合は、以下のコマンドを実行して作成します。 ```bash pod init ``` 1. この行を `Podfile` に追加します。 ```podfile pod 'StripePaymentsUI' ``` 1. 以下のコマンドを実行します。 ```bash pod install ``` 1. これ以降は、Xcode でプロジェクトを開く際に、`.xcodeproj` ファイルではなく、必ず `.xcworkspace` ファイルを使用するということを忘れないでください。 1. 今後、SDK の最新バージョンに更新するには、以下を実行します。 ```bash pod update StripePaymentsUI ``` #### Carthage 1. まだインストールしていない場合は、[Carthage](https://github.com/Carthage/Carthage#installing-carthage) の最新バージョンをインストールします。 1. この行を `Cartfile` に追加します。 ```cartfile github "stripe/stripe-ios" ``` 1. [Carthage のインストール手順](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos)に従います。必ず、[こちら](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking)にリストされている必要なフレームワークのすべてを埋め込んでください。 1. 今後、SDK の最新バージョンに更新するには、以下のコマンドを実行します。 ```bash carthage update stripe-ios --platform ios ``` #### 手動のフレームワーク 1. Stripe の [GitHub リリースページ](https://github.com/stripe/stripe-ios/releases/latest)に移動して、**Stripe.xcframework.zip** をダウンロードして解凍します。 1. **StripePaymentsUI.xcframework** を、Xcode プロジェクトの **General (一般) ** 設定の **Embedded Binaries (埋め込みバイナリー)** セクションにドラッグします。**Copy items if needed (必要に応じてアイテムをコピーする)** を必ず選択してください。 1. [こちら](https://github.com/stripe/stripe-ios/tree/master/StripePaymentsUI/README.md#manual-linking)にリストされている必要なフレームワークのすべてに対して、ステップ 2 を繰り返します。 1. 今後、Stripe の SDK の最新バージョンに更新するには、ステップ 1 から 3 を繰り返します。 > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases (リリース)](https://github.com/stripe/stripe-ios/releases) ページをご覧ください。リポジトリの[リリースをウォッチ](https://help.github.com/en/articles/watching-and-unwatching-releases-for-a-repository#watching-releases-for-a-repository)して、新しいリリースの公開時に通知を受け取ることも可能です。 アプリの起動時に Stripe [公開可能キー](https://dashboard.stripe.com/test/apikeys)を使用して SDK を設定します。これにより、アプリが Stripe API にリクエストを送信できるようになります。 #### Swift ```swift import UIKitimportStripePaymentsUI @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {StripeAPI.defaultPublishableKey = "<>" // do any other necessary launch configuration return true } } ``` > テストおよび開発時には[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。 ## PaymentIntent を作成する [サーバー側] [クライアント側] ### サーバー側 [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) は、顧客から支払いを回収する意図を表すオブジェクトであり、支払いプロセスのライフサイクルをステージごとに追跡します。 #### ダッシュボードで決済手段を管理する 決済手段は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は、取引金額、通貨、決済フローなどの要素に基づいて、決済手段の戻り値を処理します。 金額と通貨を指定してサーバー上に PaymentIntent を作成します。PaymentIntent を作成する前に、[決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)で **Pay with Crypto** をオンにしてください。 > 請求金額は、クライアント側ではなく、信頼できる環境であるサーバー側で常に決定するようにしてください。これにより、顧客は独自の価格を選択できなくなります。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" ``` #### 決済手段を手動でリスト化する ダッシュボードを使用しない場合や、決済手段を手動で指定する場合は、`payment_method_types` 属性を使用して決済手段をリストできます。 金額、通貨、決済手段リストを指定して、サーバー上に PaymentIntent を作成します。 > 請求金額は、クライアント側ではなく、信頼できる環境であるサーバー側で常に決定するようにしてください。これにより、顧客は独自の価格を選択できなくなります。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=crypto" ``` ### クライアント側 クライアント側でサーバーに PaymentIntent をリクエストし、その *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) を保存します。 #### Swift ```swift class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? // ...continued from previous step override func viewDidLoad() { // ...continued from previous step startCheckout() } func startCheckout() { // Request a PaymentIntent from your server and store its client secret // Click View full sample to see a complete implementation } } ``` ## Stripe に支払いをする [クライアント側] 顧客が Pay with Crypto での支払いを選択したら、`PaymentIntent` を確定して支払いを完了します。`STPPaymentIntentParams` オブジェクトを `PaymentIntent` の [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) で構成します。 client secret は、Stripe API リクエストを認証する API キーとは異なります。支払いが完了してしまう可能性があるため、client secret の処理には十分注意してください。ログに記録したり、URL に埋め込んだり、顧客以外に公開したりすることはできません。 ### 戻り先 URL を設定する iOS SDK では、アプリに WebView を表示して、Pay with Crypto 決済を完了します。認証が完了すると WebView は自動的に閉じられるため、顧客が閉じる必要はありません。この動作を有効にするには、カスタム URL スキームまたはユニバーサルリンクを構成して、URL を SDK に転送するようにアプリのデリゲートを設定します。 #### Swift ```swift // This method handles opening custom URL schemes (for example, "your-app://stripe-redirect") func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } return false } // This method handles opening universal link URLs (for example, "https://example.com/stripe_ios_callback") func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if userActivity.activityType == NSUserActivityTypeBrowsingWeb { if let url = userActivity.webpageURL { let stripeHandled = StripeAPI.handleURLCallback(with: url) if (stripeHandled) { return true } else { // This was not a Stripe url – handle the URL normally as you would } } } return false } ``` PaymentIntent を確定する際に、URL を `return_url` として渡します。WebView での認証が完了すると、Stripe はユーザを `return_url` にリダイレクトします。 ### Pay with Crypto での支払いを確定する `STPPaymentHandler.confirmPayment` を呼び出して支払いを完了します。WebView が表示され、顧客はそこで Pay with Crypto での支払いを完了できます。決済完了後、Stripe は支払いの結果を表す完了ブロックを呼び出します。 #### Swift ```swift let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) // Pay with Crypto does not require additional parameters so we only need to pass the initialized // STPPaymentMethodCryptoParams instance to STPPaymentMethodParams let crypto = STPPaymentMethodCryptoParams() let paymentMethodParams = STPPaymentMethodParams(crypto: crypto, billingDetails: nil, metadata: nil) paymentIntentParams.paymentMethodParams = paymentMethodParams paymentIntentParams.returnURL = "payments-example://stripe-redirect" STPPaymentHandler.shared().confirmPayment(paymentIntentParams, with: self) { (handlerStatus, paymentIntent, error) in switch handlerStatus { case .succeeded: // Payment succeeded // ... case .canceled: // Payment canceled // ... case .failed: // Payment failed // ... @unknown default: fatalError() } } ``` ## Optional: リダイレクトを手動で処理する [サーバー側] リダイレクトを処理するには、`confirmPayment` を指定して Stripe.js を使用することをお勧めします。顧客を手動でリダイレクトする場合の方法を紹介します。 1. 顧客が支払いを完了した後にリダイレクトされる URL を指定します。 ```curl curl https://api.stripe.com/v1/payment_intents/pi_1DRuHnHgsMRlo4MtwuIAUe6u/confirm \ -u "<>:" \ -d payment_method=pm_1EnPf7AfTbPYpBIFLxIc8SD9 \ --data-urlencode "return_url=https://shop.example.com/crtA6B28E1" ``` 1. `PaymentIntent` のステータスが `requires_action` であることを確認します。`next_action` のタイプは `redirect_to_url` になります。 ```json "next_action": { "type": "redirect_to_url", "redirect_to_url": { "url": "https://hooks.stripe.com/...", "return_url": "https://example.com/checkout/complete" } } ``` 1. `next_action` プロパティで指定された URL に顧客をリダイレクトします。 支払いプロセスを完了した顧客は、`return_url` の指定先に送られます。`payment_intent` と `payment_intent_client_secret` の URL クエリパラメーターが含まれます。上記のように、自社で作成したクエリパラメーターを渡すことができます。 ## Optional: 支払い後のイベントを処理する 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。ダッシュボード、カスタム *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests)、またはパートナーソリューションを使用してこれらのイベントを受信し、また、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアント側では、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了したりする可能性があります。また、悪意を持つクライアントがレスポンスを不正操作する恐れもあります。非同期型のイベントをリッスンするよう構築済みのシステムを設定することで、これ以降はより多くの決済手段を簡単に受け付けられるようになります。[サポートされているすべての決済手段の違い](https://stripe.com/payments/payment-methods-guide)をご確認ください。 - **ダッシュボードでイベントを手動で処理する** ダッシュボードを使用して、テスト決済を[ダッシュボードで表示](https://dashboard.stripe.com/test/payments)したり、メール領収書を送信したり、入金を処理したり、失敗した決済を再試行したりできます。 - **Custom Webhook を構築する** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **構築済みアプリを導入する** パートナーアプリケーションを統合することで、[自動化](https://stripe.partners/?f_category=automation)や[マーケティング/セールス](https://stripe.partners/?f_category=marketing-and-sales)などの一般的なビジネスイベントを処理します。 # Android > This is a Android for when payment-ui is mobile and platform is android. View the full page at https://docs.stripe.com/payments/accept-stablecoin-payments?payment-ui=mobile&platform=android. 埋め込み型の決済フォーム、[Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android)を使用して暗号資産 Pay やその他の決済手段を、最小限の作業で貴社連携機能に追加できます。 Pay with Crypto は、支払いの[認証](https://docs.stripe.com/payments/payment-methods.md#customer-actions)が顧客に義務付けられている、[1 回限り](https://docs.stripe.com/payments/payment-methods.md#usage)の決済手段です。顧客はアプリからリダイレクトされ、Stripe で支払いをオーソリしてから、またアプリに戻ります。支払いが成功または失敗すると、[すぐに通知](https://docs.stripe.com/payments/payment-methods.md#payment-notification)されます。 ## Stripe を設定する [サーバ側] [クライアント側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/register)してください。 ### サーバ側 この組み込みには、サーバ上に Stripe API と通信するエンドポイントが必要です。サーバから Stripe API にアクセスするには、Stripe の公式ライブラリを使用します。 #### 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 Android SDK](https://github.com/stripe/stripe-android) はオープンソースであり、[詳細なドキュメントが提供されています](https://stripe.dev/stripe-android/)。 SDK をインストールするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの `dependencies` ブロックに `stripe-android` を追加します。 #### Kotlin ```kotlin plugins { id("com.android.application") } android { ... } dependencies { // ... // Stripe Android SDK implementation("com.stripe:stripe-android:23.7.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.7.0") } ``` > SDK の最新リリースおよび過去バージョンの詳細については、GitHub の [Releases](https://github.com/stripe/stripe-android/releases) ページをご覧ください。新しいリリースの公開時に通知を受け取るには、[リポジトリのリリースを確認](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)してください。 Stripe の[公開可能キー](https://dashboard.stripe.com/apikeys)を使用して SDK を設定し、 `Application` サブクラスなどで、Stripe API へのリクエストを実行できるようにします。 #### Kotlin ```kotlin import com.stripe.android.PaymentConfiguration class MyApp : Application() { override fun onCreate() { super.onCreate() PaymentConfiguration.init( applicationContext, "<>" ) } } ``` > テストおよび開発時には[テストキー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用し、アプリの公開時には[本番環境](https://docs.stripe.com/keys.md#test-live-modes)キーを使用します。 Stripe サンプルでは、サーバへの HTTP リクエストの作成に、[OkHttp](https://github.com/square/okhttp) および [GSON](https://github.com/google/gson) も使用します。 ## PaymentIntent を作成する [サーバー側] [クライアント側] ### サーバー側 [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) は、顧客から支払いを回収する意図を表すオブジェクトであり、支払いプロセスのライフサイクルをステージごとに追跡します。 #### ダッシュボードで決済手段を管理する 決済手段は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は、取引金額、通貨、決済フローなどの要素に基づいて、決済手段の戻り値を処理します。 金額と通貨を指定してサーバー上に PaymentIntent を作成します。PaymentIntent を作成する前に、[決済手段の設定](https://dashboard.stripe.com/settings/payment_methods)ページで **Pay with Crypto** をオンにしてください。 > 請求金額は、クライアント側ではなく、信頼できる環境であるサーバー側で常に決定するようにしてください。これにより、顧客は独自の価格を選択できなくなります。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "automatic_payment_methods[enabled]=true" ``` #### 決済手段を手動でリスト化する ダッシュボードを使用しない場合や、決済手段を手動で指定する場合は、`payment_method_types` 属性を使用して決済手段をリストできます。 金額、通貨、決済手段リストを指定して、サーバー上に PaymentIntent を作成します。 > 請求金額は、クライアント側ではなく、信頼できる環境であるサーバー側で常に決定するようにしてください。これにより、顧客は独自の価格を選択できなくなります。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=1099 \ -d currency=usd \ -d "payment_method_types[]=crypto" ``` ### クライアント側 クライアント側でサーバーに PaymentIntent をリクエストし、その *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) を保存します。 #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { private lateinit var paymentIntentClientSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... startCheckout() } private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret in paymentIntentClientSecret // Click View full sample to see a complete implementation } } ``` ## Stripe に支払いをする [クライアント側] 顧客が Pay with Crypto での支払いを選択したら、`PaymentIntent` を確定して支払いを完了します。`ConfirmPaymentIntentParams` オブジェクトを `PaymentIntent` の [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) で構成します。 client secret は、Stripe API リクエストを認証する API キーとは異なります。支払いが完了してしまう可能性があるため、client secret の処理には十分注意してください。ログに記録したり、URL に埋め込んだり、顧客以外に公開したりすることはできません。 ### Pay with Crypto での支払いを確定する [PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/confirm.html) を呼び出して決済を完了します。これにより、顧客は **https://crypto.stripe.com/pay**, にリダイレクトされ、そこで暗号資産での決済を完了できます。完了後、Stripe は決済結果を使用して設定した `PaymentResultCallback` を呼び出します。 #### Kotlin ```kotlin class CheckoutActivity : AppCompatActivity() { // ... private val paymentLauncher: PaymentLauncher by lazy { val paymentConfiguration = PaymentConfiguration.getInstance(applicationContext) PaymentLauncher.create( activity = this, publishableKey = paymentConfiguration.publishableKey, stripeAccountId = paymentConfiguration.stripeAccountId, callback = ::onPaymentResult, ) } // … private fun startCheckout() { // ... val cryptoParams = PaymentMethodCreateParams.createCrypto() val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = cryptoParams, clientSecret = paymentIntentClientSecret, ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { // Handle the payment result… } } ``` ## Optional: リダイレクトを手動で処理する [サーバー側] リダイレクトを処理するには、`confirmPayment` を指定して Stripe.js を使用することをお勧めします。顧客を手動でリダイレクトする場合の方法を紹介します。 1. 顧客が支払いを完了した後にリダイレクトされる URL を指定します。 ```curl curl https://api.stripe.com/v1/payment_intents/pi_1DRuHnHgsMRlo4MtwuIAUe6u/confirm \ -u "<>:" \ -d payment_method=pm_1EnPf7AfTbPYpBIFLxIc8SD9 \ --data-urlencode "return_url=https://shop.example.com/crtA6B28E1" ``` 1. `PaymentIntent` のステータスが `requires_action` であることを確認します。`next_action` のタイプは `redirect_to_url` になります。 ```json "next_action": { "type": "redirect_to_url", "redirect_to_url": { "url": "https://hooks.stripe.com/...", "return_url": "https://example.com/checkout/complete" } } ``` 1. `next_action` プロパティで指定された URL に顧客をリダイレクトします。 支払いプロセスを完了した顧客は、`return_url` の指定先に送られます。`payment_intent` と `payment_intent_client_secret` の URL クエリパラメーターが含まれます。上記のように、自社で作成したクエリパラメーターを渡すことができます。 ## Optional: 支払い後のイベントを処理する 支払いが完了すると、Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) イベントを送信します。ダッシュボード、カスタム *Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests)、またはパートナーソリューションを使用してこれらのイベントを受信し、また、顧客への注文確認メールの送信、データベースでの売上の記録、配送ワークフローの開始などのアクションを実行します。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアント側では、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了したりする可能性があります。また、悪意を持つクライアントがレスポンスを不正操作する恐れもあります。非同期型のイベントをリッスンするよう構築済みのシステムを設定することで、これ以降はより多くの決済手段を簡単に受け付けられるようになります。[サポートされているすべての決済手段の違い](https://stripe.com/payments/payment-methods-guide)をご確認ください。 - **ダッシュボードでイベントを手動で処理する** ダッシュボードを使用して、テスト決済を[ダッシュボードで表示](https://dashboard.stripe.com/test/payments)したり、メール領収書を送信したり、入金を処理したり、失敗した決済を再試行したりできます。 - **Custom Webhook を構築する** [Build a custom webhook](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) handler to listen for events and build custom asynchronous payment flows. Test and debug your webhook integration locally with the Stripe CLI. - **構築済みアプリを導入する** パートナーアプリケーションを統合することで、[自動化](https://stripe.partners/?f_category=automation)や[マーケティング/セールス](https://stripe.partners/?f_category=marketing-and-sales)などの一般的なビジネスイベントを処理します。 ### 実装内容をテストする テスト API キーを使用して決済リダイレクトページを開き、暗号資産決済統合をテストします。[テストネットアセット](https://docs.stripe.com/payments/accept-stablecoin-payments.md#testnet-assets) を使用して、決済フローの成功を無料でテストできます。 1. *サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)で、選択した統合方法を使用して新しいトランザクションを作成し、そのリダイレクト URL を開きます。 1. 任意のウォレットと決済ネットワークを接続します。 1. 決済を完了し、想定する URL にリダイレクトされることを確認します。 ### テストネットアセットで決済をテストする ほとんどの暗号資産は、ブロックチェーントランザクションのテストに使用できるテストネットアセット (金銭的価値のないトークン) を提供しています。Stripe は、テストに MetaMask ウォレット、Polygon Amoy テストネット、Circle Faucet を推奨していますが、独自のサービスを使用することもできます。 #### ウォレットをインストールする 1. Web ブラウザ用の [MetaMask 拡張機能をダウンロード](https://metamask.io/download) します。 1. [新しいウォレットを作成](https://support.metamask.io/start/creating-a-new-wallet/) するか、[既存のウォレットをインポート](https://support.metamask.io/start/use-an-existing-wallet/) します。 #### テストネットを有効にする 1. MetaMask ウォレットで、メインメニューから**ネットワーク**を選択します。 1. **カスタムネットワークを追加**をクリックします。 1. 次の詳細を入力します。 - **ネットワーク名**: `Amoy` - **デフォルトの RPC URL**: `https://rpc-amoy.polygon.technology/` - **チェーン ID**: `80002` - **通貨シンボル**: `POL` - **ブロックエクスプローラーの URL**: `https://amoy.polygonscan.com/` 1. **保存** をクリックします。 #### トークンをインポートする 1. MetaMask ウォレットの**トークン**で、ネットワークドロップダウンから **Amoy** を選択します。 1. オーバーフローメニュー (⋯) をクリックし、**トークンのインポート**を選択します。 1. **ネットワークを選択** > **Amoy** をクリックします。 1. **トークンコントラクトアドレス**に、Polygon Amoy のテストネットコントラクトアドレスを貼り付けます。 ``` 0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582 ``` **トークンシンボル**フィールドは `USDC` で自動的に更新され、**小数点以下桁数**フィールドは `6` で更新されます。 1. **次へ** をクリックします。 1. `USDC` トークンをインポートしていることを確認し、**インポート**をクリックします。 MetaMask ウォレットのトークンリストに **POL** と **USDC** が表示されるようになりました。 返金をテストする際、ウォレットに送信されるトークンの契約が、決済に使用されるものとは異なることがあります。ブロックエクスプローラーで返金したトークンの [transaction_hash](https://docs.stripe.com/api/refunds/object.md?rds=1#refund_object-destination_details-crypto-reference) を確認し、そのトークンの契約をウォレットに追加することをお勧めします。たとえば、Sepolia ETH USDC 返金の `0x58277ebcabbe2a6694fbca8daf9e23163dbacf3e` トークンの契約アドレスを確認できます。 #### テストネットアセットを取得する > 一部のテストネットのフォーセットを使用するには、少量のメインネットトークンを保有する必要がある場合があります。 1. [faucet.circle.com](https://faucet.circle.com/) を開きます 1. **USDC** をクリックします。 1. **ネットワーク**で、**Polygon PoS Amoy** を選択します。 1. **送信先**にウォレットアドレスを貼り付けます。 1. **20 USDC を送金**をクリックします。 決済を行うための USDC に加えて、トランザクションコストを支払うための POL が必要です。 1. [faucet.polygon.technology](https://faucet.polygon.technology/) を開きます。 1. **チェーンとトークンの選択**で、**Polygon Amoy** と **POL** を選択します。 1. **本人確認**で、認証に使用するサードパーティプラットフォームをクリックし、ログインプロセスを完了します。 1. **ウォレットアドレスの入力**に、ウォレットアドレスを貼り付けます。 1. **Claim** をクリックします。 テストネットトランザクションの完了には数分かかる場合があります。ウォレットを確認して、USDC と POL が送金されたことを確認してください。 ### その他のテストネット Faucet より多くのテストトークンオプションについては、次の Faucet サービスを確認してください。 - [Paxos USDP](https://faucet.paxos.com/) - [Devnet SOL](https://faucet.solana.com/) - [Sepolia ETH](https://faucets.chain.link/sepolia) - [Amoy POL](https://faucet.polygon.technology/)