# Cash App Pay 支払い システムに Cash App Pay のサポートを追加します。 > Stripe は、通貨、支払い方法の制限、その他のパラメーターを評価することで、適切な支払い方法を顧客に自動的に提示できます。 > > - [決済の受け付け](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=checkout&ui=stripe-hosted)ガイドに従って、[動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用するチェックアウトの統合機能を構築します。 - 動的な決済手段を使用しない場合は、チェックアウトの導入で、決済方法を手動で設定するために以下のステップに従ってください。 このガイドでは、Stripe がホストする決済フォームである [Checkout](https://docs.stripe.com/payments/checkout.md) で Cash App Pay を有効にする方法について手順を追って説明し、カード支払いを受け付ける場合と Cash App Pay の支払いを受け付ける場合の違いを説明します。 ## 互換性を判断する **サポート対象のビジネスの所在地**: US **対応可能な通貨**: `usd` **取引通貨**: `usd` **支払いモード**: Yes **セットアップモード**: Yes **サブスクリプションモード**: Yes Cash App Pay での支払いに対応するには、Checkout セッションが次の条件をすべて満たしている必要があります。 - すべてのラインアイテムの*価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions)は USD で表示する必要があります。 ## Stripe を設定する [サーバー側] まず、Stripe アカウントが必要です。[今すぐご登録ください](https://dashboard.stripe.com/register)。 アプリケーションから 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' ``` ## 決済を受け付ける > このガイドは、基本的な[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout) Checkout の実装を基盤にしています。 ### 支払い方法として Cash App Pay を有効にする 新しい [Checkout セッション](https://docs.stripe.com/api/checkout/sessions.md)を作成する際は、以下を行う必要があります。 1. `cashapp` を `payment_method_types` の一覧に追加します。 1. すべての `line_items` が `usd` を通貨として使用していることを確認してください。 #### Stripe ホスト型ページ ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=cashapp" \ --data-urlencode "success_url=https://example.com/success" ``` #### 完全埋め込みページ ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -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" \ -d mode=payment \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=cashapp" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### 注文のフルフィルメント 決済受け付け後に、[注文のフルフィルメントを実行](https://docs.stripe.com/checkout/fulfillment.md)する方法を説明します。 ## 組み込みをテストする #### モバイル版ウェブアプリのテスト 実装内容をテストするには、決済手段として Cash App Pay を選択し、**支払う**をタップします。テスト時はテスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。リダイレクトされた後、支払いは自動的に承認されます。 #### デスクトップ版ウェブアプリのテスト 実装をテストするには、モバイルデバイスの QR コードスキャンアプリケーションを使用して QR コードを読み取ります。テスト時は、QR コードのペイロードに URL が含まれ、テスト決済ページにリダイレクトされます。ここでテスト決済を承認または拒否できます。 本番環境では、QR コードをスキャンすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。QR コードをスキャンすると、支払いは自動的に承認されます。 ## See also - [Checkout のフルフィルメント](https://docs.stripe.com/checkout/fulfillment.md) - [決済フローをカスタマイズする](https://docs.stripe.com/payments/checkout/customization.md) # 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/cash-app-pay/accept-a-payment?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)に関する導入ガイドをご覧ください。 ## 互換性の判断 **サポート対象のビジネスの所在地**: US **対応可能な通貨**: `usd` **取引通貨**: `usd` **支払いモード**: Yes **セットアップモード**: Yes **サブスクリプションモード**: Yes Cash App Pay 支払いに対応するには、Checkout セッションが次の条件をすべて満たしている必要があります。 - すべてのラインアイテムの *価格* (Prices define how much and how often to charge for products. This includes how much the product costs, what currency to use, and the interval if the price is for subscriptions) は米ドルで表示する必要があります。 ## サーバーを設定する [サーバー側] 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' ``` ## 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)を使用して、各顧客に最も適した決済手段を動的に表示してコンバージョンを最大化しましょう。Stripe ではこの方法をお勧めしています。[決済手段を手動で一覧表示](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: ['cashapp'], 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; ``` ## 導入をテストする #### モバイル版ウェブアプリのテスト 実装内容をテストするには、決済手段として Cash App Pay を選択し、**支払う**をタップします。テスト時はテスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。リダイレクトされた後、支払いは自動的に承認されます。 #### デスクトップ版ウェブアプリのテスト 実装をテストするには、モバイルデバイスの QR コードスキャンアプリケーションを使用して QR コードを読み取ります。テスト時は、QR コードのペイロードに URL が含まれ、テスト決済ページにリダイレクトされます。ここでテスト決済を承認または拒否できます。 本番環境では、QR コードをスキャンすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。QR コードをスキャンすると、支払いは自動的に承認されます。 # 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/cash-app-pay/accept-a-payment?payment-ui=elements&api-integration=paymentintents. このガイドでは、[Payment Element](https://docs.stripe.com/payments/payment-element.md) を使用して、ウェブサイトまたはアプリケーションにカスタムの Stripe 決済フォームを埋め込む方法をご紹介します。Payment Element では、Cash App Pay とその他の支払い方法に自動的に対応できます。高度な設定やカスタマイズについては、[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md)の導入ガイドをご覧ください。 ## Stripe を設定する [サーバー側] まず、Stripe アカウントが必要です。[今すぐご登録ください](https://dashboard.stripe.com/register)。 アプリケーションから 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 を作成する [サーバー側] Stripe は [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md) オブジェクトを使用して、顧客から支払いを回収する意図を示し、プロセス全体を通して請求の実施と支払い状態の変化を追跡します。 #### ダッシュボードで支払い方法を管理する amount および currency を指定して、サーバーで PaymentIntent を作成します。支払い方法は[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で管理できます。Stripe は取引額、通貨、決済フローなどの要素に基づいて、適切な支払い方法が返されるように処理します。Payment Intent を作成する前に、[支払い方法の設定](https://dashboard.stripe.com/settings/payment_methods)ページで **Cash App Pay** が有効になっていることを確認してください。 支払い額は常に、クライアント側ではなく、信頼性の高い環境であるサーバー側で決定してください。このようにすることで、悪意のある顧客が価格を操作できないようにすることができます。 ```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[]=cashapp" ``` ### 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 ``` ## 支払いの詳細を収集する [クライアント側] [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 ### 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
``` 前のフォームが読み込まれたら、Payment Element のインスタンスを作成して、それをコンテナーの DOM ノードにマウントします。[Elements](https://docs.stripe.com/js/elements_object/create) インスタンスを作成する際に、前のステップからの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を `options` に渡します。 client secret は支払いを完了できるため、慎重に取り扱う必要があります。記録したり、URL に埋め込んだり、当該の顧客以外に漏洩することがないようにしてください。 ```javascript const options = { clientSecret: '{{CLIENT_SECRET}}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in a previous stepconst elements = stripe.elements(options); // Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement on mount: // // linkAuthenticationElement.mount("#link-authentication-element", { // defaultValues: { // email: 'jenny.rosen@example.com', // } // }) // 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` プロバイダーに渡します。加えて、前のステップの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を `options` にして `Elements` プロバイダーに渡します。 ```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 = { // passing the client secret obtained in step 3 clientSecret: '{{CLIENT_SECRET}}', // 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 (
// Optional: Autofill user's saved payment methods. If the customer's // email is known when the page is loaded, you can pass the email // to the linkAuthenticationElement // // ); }; export default CheckoutForm; ``` ## Stripe に支払いを送信する [クライアント側] Payment Element からの詳細を指定して [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を使用し、支払いを完了します。ユーザーが支払いを完了した後に Stripe がユーザーをリダイレクトする場所を指定するには、この関数に [return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を指定します。ユーザーはまず、銀行のオーソリページなどの中間サイトにリダイレクトされ、その後 `return_url` にリダイレクトされます。カード支払いでは、支払いが正常に完了するとすぐに `return_url` にリダイレクトします。 #### HTML + JS ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }); ``` #### React 支払いフォームコンポーネントから [stripe.confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を呼び出すには、[useStripe](https://docs.stripe.com/sdks/stripejs-react.md#usestripe-hook) フックと [useElements](https://docs.stripe.com/sdks/stripejs-react.md#useelements-hook) フックを使用します。 フックではなく従来のクラスコンポーネントを使用する場合は、代わりに [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) を使用します。 ```jsx import React, {useState} from 'react'; import {useStripe, useElements, PaymentElement} from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { // We don't want to let default form submission happen here, // which would refresh the page. event.preventDefault(); if (!stripe || !elements) { // Stripe.js hasn't yet loaded. // Make sure to disable form submission until Stripe.js has loaded. return; } const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return (
{/* Show error message to your customers */} {errorMessage &&
{errorMessage}
} ); }; export default CheckoutForm; ``` `return_url` が、Web サイト上の支払いステータスを表示するページと対応していることを確認します。Stripe が顧客を `return_url` にリダイレクトするときは、以下の URL クエリーパラメーターが指定されます。 | パラメーター | 説明 | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | | `payment_intent` | `PaymentIntent` の一意の識別子。 | | `payment_intent_client_secret` | `PaymentIntent` オブジェクトの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。 | > 顧客のブラウザーセッションを追跡するツールを利用している場合、リファラー除外リストに `stripe.com` ドメインの追加が必要になる場合があります。リダイレクトを行うと、一部のツールでは新しいセッションが作成され、セッション全体の追跡ができなくなります。 クエリパラメーターのいずれか 1 つを使用して PaymentIntent を取得します。[PaymentIntent のステータス](https://docs.stripe.com/payments/paymentintents/lifecycle.md)を調べて、顧客に表示する内容を決定します。また、`return_url` を指定するときにカスタムのクエリパラメーターを追加することもできます。このパラメーターはリダイレクトプロセスの間維持されます。 #### HTML + JS ```javascript // Initialize Stripe.js using your publishable key const stripe = Stripe('<>'); // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { const message = document.querySelector('#message') // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': message.innerText = 'Success! Payment received.'; break; case 'processing': message.innerText = "Payment processing. We'll update you when payment is received."; break; case 'requires_payment_method': message.innerText = 'Payment failed. Please try another payment method.'; // Redirect your user back to your payment page to attempt collecting // payment again break; default: message.innerText = 'Something went wrong.'; break; } }); ``` #### React ```jsx import React, {useState, useEffect} from 'react'; import {useStripe} from '@stripe/react-stripe-js'; const PaymentStatus = () => { const stripe = useStripe(); const [message, setMessage] = useState(null); useEffect(() => { if (!stripe) { return; } // Retrieve the "payment_intent_client_secret" query parameter appended to // your return_url by Stripe.js const clientSecret = new URLSearchParams(window.location.search).get( 'payment_intent_client_secret' ); // Retrieve the PaymentIntent stripe .retrievePaymentIntent(clientSecret) .then(({paymentIntent}) => { // Inspect the PaymentIntent `status` to indicate the status of the payment // to your customer. // // Some payment methods will [immediately succeed or fail][0] upon // confirmation, while others will first enter a `processing` state. // // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification switch (paymentIntent.status) { case 'succeeded': setMessage('Success! Payment received.'); break; case 'processing': setMessage("Payment processing. We'll update you when payment is received."); break; case 'requires_payment_method': // Redirect your user back to your payment page to attempt collecting // payment again setMessage('Payment failed. Please try another payment method.'); break; default: setMessage('Something went wrong.'); break; } }); }, [stripe]); return message; }; export default PaymentStatus; ``` ## リダイレクトと取引の認証 顧客は、モバイルアプリまたはデスクトップアプリで Cash App Pay 取引を認証できます。`confirmPayment` の呼び出し後、顧客が使用するクライアントによって認証方法が決定されます。 #### モバイルアプリの認証 `confirmPayment` の呼び出し後、顧客は Cash App にリダイレクトされ、そこで支払いを承認または拒否します。顧客が支払いを承認すると、Payment Intent の `return_url` にリダイレクトされます。Stripe は `payment_intent`、`payment_intent_client_secret`、`redirect_pm_type`、`redirect_status` を URL クエリパラメーターとして (`return_url` の既存のクエリパラメーターとともに) 追加します。 認証セッションは 60 分後に期限切れになり、PaymentIntent のステータスは `require_payment_method` に戻ります。ステータスが移行すると、顧客には支払いエラーが表示され、支払いプロセスをもう一度開始する必要があります。 #### デスクトップ版ウェブアプリの認証 confirmPayment が呼び出されると、QR コードがウェブページに表示されます。顧客は、モバイルデバイスのカメラまたは Cash App モバイルアプリを使用して QR コードをスキャンし、Cash App Pay を使用して支払いを認証できます。顧客が支払いの認証に成功してから数秒後に、QR コードのモーダルが自動的に閉じられ、注文をフルフィルメントできるようになります。支払いが完了すると、Stripe は `return_url` へのリダイレクトを実行します。ウェブでの支払い後にリダイレクトを希望しない場合は、Payment Element に `redirect: if_required` を渡します。 認証セッションは 60 分後に期限切れになります。PaymentIntent のステータスが `require_payment_method` に戻る前に、最大 20 回まで QR コードを更新できます。ステータスの移行後、顧客には支払いエラーが表示され、顧客は支払いプロセスをもう一度開始する必要があります。 ## Optional: オーソリとキャプチャーを分離する 支払いをすぐ作成して、売上は後でキャプチャーするように、オーソリとキャプチャーを分離できます。7 日の期間内に支払いがキャプチャーされない場合、Stripe は PaymentIntent をキャンセルし、[payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) イベントを送信します。 支払いをキャプチャーできないことが分かっている場合は、7 日間経過するのを待つのではなく、[PaymentIntent をキャンセル](https://docs.stripe.com/refunds.md#cancel-payment)することをお勧めします。 ### オーソリのみを行うよう Stripe に指示する オーソリとキャプチャーの分離を指定するには、PaymentIntent の作成時に [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) を `manual` に設定します。このパラメーターは、顧客の Cash App Pay アカウントの金額のみをオーソリするように Stripe に指示します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 売上をキャプチャーする オーソリが成功すると、PaymentIntent の[ステータス](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status)は `requires_capture` に移行します。オーソリされた売上をキャプチャーするには、PaymentIntent の[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)リクエストを作成します。 ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` デフォルトでは、オーソリされた合計金額がキャプチャーされます。`amount_to_capture` を指定して、合計金額以下の金額を指定することもできます。 ### (任意)オーソリをキャンセルする オーソリをキャンセルする必要がある場合は、[PaymentIntent をキャンセル](https://docs.stripe.com/api/payment_intents/cancel.md)してください。 ## 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 を構築する** [カスタム 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)などの一般的なビジネスイベントを処理します。 ## 導入をテストする #### モバイル版ウェブアプリのテスト 実装内容をテストするには、決済手段として Cash App Pay を選択し、**支払う**をタップします。テスト時はテスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。リダイレクトされた後、支払いは自動的に承認されます。 #### デスクトップ版ウェブアプリのテスト 実装をテストするには、モバイルデバイスの QR コードスキャンアプリケーションを使用して QR コードを読み取ります。テスト時は、QR コードのペイロードに URL が含まれ、テスト決済ページにリダイレクトされます。ここでテスト決済を承認または拒否できます。 本番環境では、QR コードをスキャンすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。QR コードをスキャンすると、支払いは自動的に承認されます。 ## 失敗した支払い Cash App Pay は複数のデータポイントを使用して、取引を拒否する状況を判断します (たとえば、AI モデルが取引において消費者の高い不正利用リスクを検出した場合や、Cash App で請求する許可を消費者が取り消した場合など)。 このケースでは、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) は切り離され、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 支払いが拒否された場合を除き、Cash App Pay の [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) が `requires_action` ステータスである場合、顧客は Cash App にリダイレクトされてから 10 分以内に支払いを完了する必要があります。10 分経過してもアクションが行われない場合、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) の関連付けが解除され、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 これが発生すると、Payment Element はエラーメッセージを表示し、顧客に別の支払い方法で再試行するように求めます。 ## エラーコード 次の表は、一般的なエラーコードと推奨アクションの詳細を示しています。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `payment_intent_invalid_currency` | 適切な通貨を入力します。Cash App Pay は `usd` にのみ対応しています。 | | `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_redirect_confirmation_without_return_url` | Cash App Pay で 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/cash-app-pay/accept-a-payment?payment-ui=direct-api. [Elements](https://docs.stripe.com/payments/cash-app-pay/accept-a-payment.md?payment-ui=elements) の連携の導入をお勧めします。Elements を連携することで Cash App Pay などの決済方法を ダイレクト API の導入よりも大幅に少ない労力で追加できます。ダイレクト API の連携を利用して Cash App Pay を受け付ける手順は以下の通りです。 - [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトを作成して、支払いを追跡します。 - 支払いを Stripe に送信して処理します。 - 支払いを (モバイルアプリケーションのリダイレクトまたは QR コードを使用して) 認証します。 - 注文が成功または失敗した後に顧客をリダイレクトするために支払い後のイベントを処理します。 ## Stripe を設定する [サーバー側] まず、Stripe アカウントが必要です。[今すぐご登録ください](https://dashboard.stripe.com/register)。 アプリケーションから 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 を作成する [サーバー側] [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 サーバーで `PaymentIntent` を作成するには、次のようにします。 - 回収する金額と通貨を指定します。 - `PaymentIntent` の[支払い方法のタイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに `cashapp` を追加します。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で Cash App Pay が有効になっていることを確認してください。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" ``` ### 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 に支払いを送信して、クライアント側で取引を認証する このステップでは、[Stripe.js](https://docs.stripe.com/payments/elements.md) を使用してクライアント側で Cash App Pay の支払いを完了します。取引を認証するには、顧客を Cash App にリダイレクトする必要があります。 Stripe.js スクリプトを決済ページに含めるには、このスクリプトを HTML ファイルの `head` に追加します。 ```html Checkout ``` 決済ページで以下の JavaScript を使用して、Stripe.js のインスタンスを作成します。 ```javascript // Set your publishable key. Remember to change this to your live publishable key in production! // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` クライアント側で PaymentIntent を確認するには、`stripe.confirmCashappPayment` を使用します。 ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); // Pass the clientSecret obtained from the server in step 2 as the first argument stripe.confirmCashappPayment( clientSecret, { payment_method: { type: 'cashapp', }, return_url: 'https://www.example.com/checkout/done', }, ); }); ``` > `confirmCashappPayment` は、`return_url` にモバイルブラウザーのみをリダイレクトし、デスクトップブラウザーのリダイレクトは行いません。デスクトップブラウザーを使用する顧客については、返されたプロミスが解決された後で、戻り先 URL に手動でリダイレクトできます。 顧客は、モバイルアプリまたはデスクトップアプリで Cash App Pay 取引を認証できます。`confirmCashappPayment` の呼び出し後、顧客が使用するクライアントによって認証方法が決定されます。 #### モバイルアプリケーションの認証 `confirmCashappPayment` の呼び出し後、顧客は Cash App にリダイレクトされ、そこで支払いを承認または拒否します。顧客が支払いを承認すると、Payment Intent の `return_url` にリダイレクトされます。Stripe は `payment_intent`、`payment_intent_client_secret`、`redirect_pm_type`、`redirect_status` を URL クエリパラメーターとして (`return_url` の既存のクエリパラメーターとともに) 追加します。 認証セッションは 60 分後に期限切れになり、PaymentIntent のステータスは `require_payment_method` に戻ります。ステータスが移行すると、顧客には支払いエラーが表示され、支払いプロセスをもう一度開始する必要があります。 #### デスクトップ版ウェブアプリの認証 `confirmCashappPayment` が呼び出されると、QR コードがウェブページに表示されます。顧客は、モバイルデバイスのカメラまたは Cash App モバイルアプリを使用して QR コードをスキャンし、支払いを認証できます。顧客が支払いの認証が成功してから数秒後に、QR コードのモーダルが自動的に閉じられ、注文をフルフィルメントできるようになります。 認証セッションは 60 分後に期限切れになります。PaymentIntent のステータスが `require_payment_method` に戻る前に、最大 20 回まで QR コードを更新できます。ステータスの移行後、顧客には支払いエラーが表示され、顧客は支払いプロセスをもう一度開始する必要があります。 ## Optional: リダイレクトと認証を手動で処理する `confirmCashappPayment` でリダイレクトと認証を処理するには、Stripe.js を利用することをお勧めします。ただし、自社のサーバーでリダイレクトと認証を手動で処理することもできます。 `confirmCashappPayment` コールで `handleActions: false` を指定します。 ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', function(event) { event.preventDefault(); // Set the clientSecret here you got in Step 2 stripe.confirmCashappPayment( clientSecret, { payment_method_data: { type: 'cashapp', }, return_url: 'https://www.example.com/checkout/done', }, { handleActions: false }, ).then((result) => { if (result.error) { // Display error to your customer. } else if (result.paymentIntent.status === "requires_action") { const nextAction = result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code; const expiresAt = nextAction.qr_code.expires_at; if (IS_MOBILE) { // This URL redirects the customer to Cash App to approve or decline the payment. const mobileAuthUrl = nextAction.mobile_auth_url; } else if (IS_DESKTOP) { // Render the QR code and display it to the customer using the below image source. const imageUrlSvg = nextAction.qr_code.image_url_svg; const imageUrlPng = nextAction.qr_code.image_url_png; } } }); }); ``` #### モバイルアプリケーションの認証 顧客がモバイルデバイスで Cash App Pay を使用して支払う場合: 1. `result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code.mobile_auth_url` プロパティとして設定された URL に顧客をリダイレクトします。これにより、顧客は支払いを承認または拒否するために Cash App にリダイレクトされます。 1. 顧客が支払いを承認すると、Payment Intent の `return_url` にリダイレクトされます。Stripe は `payment_intent`、`payment_intent_client_secret`、`redirect_pm_type`、`redirect_status` を URL クエリパラメーターとして (`return_url` の既存のクエリパラメーターとともに) 追加します。 1. `mobile_auth_url` は 30 秒後に有効期限が切れます。有効期限前に顧客が `mobile_auth_url` にリダイレクトされなかった場合は、[stripe.retrievePaymentIntent](https://docs.stripe.com/js/payment_intents/retrieve_payment_intent) を呼び出して新しい `mobile_auth_url` を取得してください。 #### デスクトップ版ウェブアプリの認証 顧客がデスクトップ版ウェブアプリから Cash App Pay を使用して支払う場合: 1. QR コードをレンダリングして顧客に表示します。画像ソースには `result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code.qr_code.image_url_png` または `image_url_svg` を使用します。たとえば、次のようになります。 ```html ``` 1. 顧客は、モバイルデバイスのカメラまたは Cash App モバイルアプリケーションを使用して QR コードをスキャンし、その後支払いを認証できます。 1. Stripe が注文を処理し、支払いの結果を確認するまで、顧客を QR コードページで待機させます。Stripe は [payment_intent.succeeded](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.succeeded) または [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) Webhook で結果を送信します。これらの PaymentIntent の Webhook をサーバー側で使用して結果をクライアントに返すことも (WebSocket を使用した永続的接続など)、ウェブページにクライアント側のポーリングを実装して、定期的に [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) のステータスを取得することもできます。 1. QR コードは 30 秒後に期限切れになります。期限が切れたら、[stripe.retrievePaymentIntent](https://docs.stripe.com/js/payment_intents/retrieve_payment_intent) を呼び出して、`result.paymentIntent.next_action.cashapp_handle_redirect_or_display_qr_code.qr_code` から新しい QR コードを取得します。 認証セッションは 60 分後に期限切れになります。PaymentIntent のステータスが `require_payment_method` に戻る前に、最大 20 回まで QR コードを更新できます。ステータスの移行後、顧客には支払いエラーが表示され、顧客は支払いプロセスをもう一度開始する必要があります。 ## Optional: オーソリとキャプチャーを分離する 支払いをすぐ作成して、売上は後でキャプチャーするように、オーソリとキャプチャーを分離できます。7 日の期間内に支払いがキャプチャーされない場合、Stripe は PaymentIntent をキャンセルし、[payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) イベントを送信します。 支払いをキャプチャーできないことが分かっている場合は、7 日間経過するのを待つのではなく、[PaymentIntent をキャンセル](https://docs.stripe.com/refunds.md#cancel-payment)することをお勧めします。 ### オーソリのみを行うよう Stripe に指示する オーソリとキャプチャーの分離を指定するには、PaymentIntent の作成時に [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) を `manual` に設定します。このパラメーターは、顧客の Cash App Pay アカウントの金額のみをオーソリするように Stripe に指示します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 売上をキャプチャーする オーソリが成功すると、PaymentIntent の[ステータス](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status)は `requires_capture` に移行します。オーソリされた売上をキャプチャーするには、PaymentIntent の[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)リクエストを作成します。 ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` デフォルトでは、オーソリされた合計金額がキャプチャーされます。`amount_to_capture` を指定して、合計金額以下の金額を指定することもできます。 ### (任意)オーソリをキャンセルする オーソリをキャンセルする必要がある場合は、[PaymentIntent をキャンセル](https://docs.stripe.com/api/payment_intents/cancel.md)してください。 ## 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 を構築する** [カスタム 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)などの一般的なビジネスイベントを処理します。 ## 導入をテストする #### モバイル版ウェブアプリのテスト 実装内容をテストするには、決済手段として Cash App Pay を選択し、**支払う**をタップします。テスト時はテスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。リダイレクトされた後、支払いは自動的に承認されます。 #### デスクトップ版ウェブアプリのテスト 実装をテストするには、モバイルデバイスの QR コードスキャンアプリケーションを使用して QR コードを読み取ります。テスト時は、QR コードのペイロードに URL が含まれ、テスト決済ページにリダイレクトされます。ここでテスト決済を承認または拒否できます。 本番環境では、QR コードをスキャンすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。QR コードをスキャンすると、支払いは自動的に承認されます。 ## 失敗した支払い Cash App Pay は複数のデータポイントを使用して、取引を拒否する状況を判断します (たとえば、AI モデルが取引において消費者の高い不正利用リスクを検出した場合や、Cash App で請求する許可を消費者が取り消した場合など)。 このケースでは、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) は切り離され、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 支払いが拒否された場合を除き、Cash App Pay の [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) が `requires_action` ステータスである場合、顧客は Cash App にリダイレクトされてから 10 分以内に支払いを完了する必要があります。10 分経過してもアクションが行われない場合、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) の関連付けが解除され、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 これが発生すると、Payment Element はエラーメッセージを表示し、顧客に別の支払い方法で再試行するように求めます。 ## エラーコード 次の表は、一般的なエラーコードと推奨アクションの詳細を示しています。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `payment_intent_invalid_currency` | 適切な通貨を入力します。Cash App Pay は `usd` にのみ対応しています。 | | `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_redirect_confirmation_without_return_url` | Cash App Pay で PaymentIntent を確定する際は、`return_url` を指定します。 | # 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/cash-app-pay/accept-a-payment?payment-ui=mobile&platform=ios. 埋め込み可能な決済フォーム、[Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios) を使用して、Cash App Pay やその他の決済手段を最小限の作業で貴社の連携機能に追加できます。 このガイドでは、自社で構築済みのカスタムの決済フォームを使用して、ネイティブのモバイルアプリケーションから Cash App Pay を受け付ける方法について説明します。 ネイティブのモバイルアプリケーションから Cash App Pay を受け付けている場合、顧客は Cash App Pay モバイルアプリケーションにリダイレクトされ、そこで認証を行います。購入が Cash App Pay モバイルアプリケーションで完了すると、顧客はネイティブのモバイルアプリケーションにリダイレクトされます。 ## 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) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 サーバーで `PaymentIntent` を作成して確定するには、以下の手順に従います。 - 回収する金額と通貨を指定します。 - `PaymentIntent` の[支払い方法のタイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに `cashapp` を追加します。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で Cash App Pay が有効になっていることを確認してください。 - `payment_method_data[type]` を `cashapp` に設定して、*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) を作成し、この PaymentIntent ですぐに使用します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` 返される 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)) が含まれ、これは PaymentIntent の*確定* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects)に使用されます。次のステップで使用できるように、クライアントに 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)) を保存します。 #### 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 に支払いを送信する [クライアント側] 顧客が支払いのために Cash App Pay をタップしたら、`PaymentIntent` を確定して支払いを完了します。`PaymentIntent` の [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を使用して `STPPaymentIntentParams` オブジェクトを設定します。 client secret は、Stripe API リクエストを認証する API キーとは異なります。これは支払いを完了できるため、慎重に扱う必要があります。記録したり、URL に埋め込んだり、当該の顧客以外に漏洩したりすることがないようにしてください。 ### 戻り先 URL を設定する iOS SDK では、Cash App Pay による決済を完了するための WebView がアプリに表示されます。認証が終了すると、顧客が閉じなくても、自動的に 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` にリダイレクトします。 ### Cash App Pay での決済を確定する `STPPaymentHandler confirmPayment` を呼び出して支払いを完了します。これにより WebView が表示され、顧客はここで Cash App Pay での決済を完了できます。完了後、支払いの結果とともに、完了ブロックが呼び出されます。 #### Swift ```swift let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) // Cash App Pay doesn't require additional parameters so we only need to pass the initialized // STPPaymentMethodCashAppParams instance to STPPaymentMethodParams let cashApp = STPPaymentMethodCashAppParams() let paymentMethodParams = STPPaymentMethodParams(cashApp: cashApp, 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: オーソリとキャプチャーを分離する 支払いをすぐ作成して、売上は後でキャプチャーするように、オーソリとキャプチャーを分離できます。7 日の期間内に支払いがキャプチャーされない場合、Stripe は PaymentIntent をキャンセルし、[payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) イベントを送信します。 支払いをキャプチャーできないことが分かっている場合は、7 日間経過するのを待つのではなく、[PaymentIntent をキャンセル](https://docs.stripe.com/refunds.md#cancel-payment)することをお勧めします。 ### オーソリのみを行うよう Stripe に指示する オーソリとキャプチャーの分離を指定するには、PaymentIntent の作成時に [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) を `manual` に設定します。このパラメーターは、顧客の Cash App Pay アカウントの金額のみをオーソリするように Stripe に指示します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 売上をキャプチャーする オーソリが成功すると、PaymentIntent の[ステータス](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status)は `requires_capture` に移行します。オーソリされた売上をキャプチャーするには、PaymentIntent の[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)リクエストを作成します。 ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` デフォルトでは、オーソリされた合計金額がキャプチャーされます。`amount_to_capture` を指定して、合計金額以下の金額を指定することもできます。 ### (任意)オーソリをキャンセルする オーソリをキャンセルする必要がある場合は、[PaymentIntent をキャンセル](https://docs.stripe.com/api/payment_intents/cancel.md)してください。 ## 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 を構築する** [カスタム 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)などの一般的なビジネスイベントを処理します。 ## 導入をテストする テスト API キーを使用して Cash App Pay の導入をテストするには、リダイレクトページを表示します。リダイレクトページで支払いを認証することにより、支払い成功のケースをテストできます。[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) は `requires_action` から `succeeded` に変化します。 ユーザーが認証に失敗するケースをテストするには、テスト API キーを使用してリダイレクトページを表示します。リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) が、`requires_action` から `requires_payment_method` に変化します。 テスト環境で PaymentIntents を手動でキャプチャする場合、キャプチャされていない [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) は、認証が成功してから 7 日後に自動的に期限切れになります。 本番環境では、**支払う**をタップすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内で支払いを承認または拒否するオプションはありません。リダイレクトされた後、支払いは自動的に承認されます。 ## 失敗した支払い Cash App Pay は複数のデータポイントを使用して、取引を拒否する状況を判断します (たとえば、AI モデルが取引において消費者の高い不正利用リスクを検出した場合や、Cash App で請求する許可を消費者が取り消した場合など)。 このケースでは、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) は切り離され、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 支払いが拒否された場合を除き、Cash App Pay の [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) が `requires_action` ステータスである場合、顧客は Cash App にリダイレクトされてから 10 分以内に支払いを完了する必要があります。10 分経過してもアクションが行われない場合、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) の関連付けが解除され、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 これが発生すると、Payment Element はエラーメッセージを表示し、顧客に別の支払い方法で再試行するように求めます。 ## エラーコード 次の表は、一般的なエラーコードと推奨アクションの詳細を示しています。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `payment_intent_invalid_currency` | 適切な通貨を入力します。Cash App Pay は `usd` にのみ対応しています。 | | `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_redirect_confirmation_without_return_url` | Cash App Pay で PaymentIntent を確定する際は、`return_url` を指定します。 | # 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/cash-app-pay/accept-a-payment?payment-ui=mobile&platform=android. 埋め込み可能な決済フォーム、[Mobile Payment Element](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android) を使用して、Cash App Pay やその他の決済手段を最小限の作業で貴社の連携機能に追加できます。 このガイドでは、自社で構築済みのカスタムの決済フォームを使用して、ネイティブのモバイルアプリケーションから Cash App Pay を受け付ける方法について説明します。 ネイティブのモバイルアプリケーションから Cash App Pay を受け付けている場合、顧客は Cash App Pay モバイルアプリケーションにリダイレクトされ、そこで認証を行います。購入が Cash App Pay モバイルアプリケーションで完了すると、顧客はネイティブのモバイルアプリケーションにリダイレクトされます。 ## 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.9.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.9.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) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 サーバーで `PaymentIntent` を作成して確定するには、以下の手順に従います。 - 回収する金額と通貨を指定します。 - `PaymentIntent` の[支払い方法のタイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに `cashapp` を追加します。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で Cash App Pay が有効になっていることを確認してください。 - `payment_method_data[type]` を `cashapp` に設定して、*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) を作成し、この PaymentIntent ですぐに使用します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` 返される 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)) が含まれ、これは PaymentIntent の*確定* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects)に使用されます。次のステップで使用できるように、クライアントに 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)) を保存します。 #### 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 に支払いを送信する [クライアント側] 顧客が支払いのために Cash App Pay をタップしたら、`PaymentIntent` を確定して支払いを完了します。`PaymentIntent` の [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を使用して `ConfirmPaymentIntentParams` オブジェクトを設定します。 client secret は、Stripe API リクエストを認証する API キーとは異なります。これは支払いを完了できるため、慎重に扱う必要があります。記録したり、URL に埋め込んだり、当該の顧客以外に漏洩したりすることがないようにしてください。 ### Cash App Pay での決済を確定する [PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/confirm.html) を呼び出して、支払いを完了します。これにより、WebView が表示され、顧客はここで Cash App Pay での決済を完了できます。完了すると、支払い結果とともに、指定された `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 cashAppPayParams = PaymentMethodCreateParams.createCashAppPay() val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = cashAppPayParams, clientSecret = paymentIntentClientSecret, // Add a mandate ID or MandateDataParams if you // want to set this up for future use… ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { // Handle the payment result… } } ``` ## Optional: オーソリとキャプチャーを分離する 支払いをすぐ作成して、売上は後でキャプチャーするように、オーソリとキャプチャーを分離できます。7 日の期間内に支払いがキャプチャーされない場合、Stripe は PaymentIntent をキャンセルし、[payment_intent.canceled](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.canceled) イベントを送信します。 支払いをキャプチャーできないことが分かっている場合は、7 日間経過するのを待つのではなく、[PaymentIntent をキャンセル](https://docs.stripe.com/refunds.md#cancel-payment)することをお勧めします。 ### オーソリのみを行うよう Stripe に指示する オーソリとキャプチャーの分離を指定するには、PaymentIntent の作成時に [capture_method](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) を `manual` に設定します。このパラメーターは、顧客の Cash App Pay アカウントの金額のみをオーソリするように Stripe に指示します。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d confirm=true \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ -d "payment_method_data[type]=cashapp" \ -d capture_method=manual \ --data-urlencode "return_url=https://www.example.com/checkout/done" ``` ### 売上をキャプチャーする オーソリが成功すると、PaymentIntent の[ステータス](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-status)は `requires_capture` に移行します。オーソリされた売上をキャプチャーするには、PaymentIntent の[キャプチャー](https://docs.stripe.com/api/payment_intents/capture.md)リクエストを作成します。 ```curl curl -X POST https://api.stripe.com/v1/payment_intents/{PAYMENT_INTENT_ID}/capture \ -u "<>:" ``` デフォルトでは、オーソリされた合計金額がキャプチャーされます。`amount_to_capture` を指定して、合計金額以下の金額を指定することもできます。 ### (任意)オーソリをキャンセルする オーソリをキャンセルする必要がある場合は、[PaymentIntent をキャンセル](https://docs.stripe.com/api/payment_intents/cancel.md)してください。 ## 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 を構築する** [カスタム 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)などの一般的なビジネスイベントを処理します。 ## 導入をテストする テスト API キーを使用して Cash App Pay の導入をテストするには、リダイレクトページを表示します。リダイレクトページで支払いを認証することにより、支払い成功のケースをテストできます。[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) は `requires_action` から `succeeded` に変化します。 ユーザーが認証に失敗するケースをテストするには、テスト API キーを使用してリダイレクトページを表示します。リダイレクトページで **Fail test payment (テスト支払い失敗)** をクリックします。[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) が、`requires_action` から `requires_payment_method` に変化します。 テスト環境で PaymentIntents を手動でキャプチャする場合、キャプチャされていない [PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) は、認証が成功してから 7 日後に自動的に期限切れになります。 *サンドボックス* (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)と本番環境の決済の仕組みにはいくつかの違いがあります。たとえば、本番環境で**支払う**をタップすると、Cash App モバイルアプリケーションにリダイレクトされます。Cash App 内では、Cash App 内で支払いを承認または拒否するオプションはありません。リダイレクト後、支払いは自動的に承認されます。 ## 失敗した支払い Cash App Pay は複数のデータポイントを使用して、取引を拒否する状況を判断します (たとえば、AI モデルが取引において消費者の高い不正利用リスクを検出した場合や、Cash App で請求する許可を消費者が取り消した場合など)。 このケースでは、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) は切り離され、[PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 支払いが拒否された場合を除き、Cash App Pay の [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents/object.md) が `requires_action` ステータスである場合、顧客は Cash App にリダイレクトされてから 10 分以内に支払いを完了する必要があります。10 分経過してもアクションが行われない場合、[PaymentMethod (支払い方法)](https://docs.stripe.com/api/payment_methods/object.md) の関連付けが解除され、[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) オブジェクトのステータスは自動的に `requires_payment_method` に移行します。 これが発生すると、Payment Element はエラーメッセージを表示し、顧客に別の支払い方法で再試行するように求めます。 ## エラーコード 次の表は、一般的なエラーコードと推奨アクションの詳細を示しています。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `payment_intent_invalid_currency` | 適切な通貨を入力します。Cash App Pay は `usd` にのみ対応しています。 | | `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_redirect_confirmation_without_return_url` | Cash App Pay で PaymentIntent を確定する際は、`return_url` を指定します。 | # React Native > This is a React Native for when payment-ui is mobile and platform is react-native. View the full page at https://docs.stripe.com/payments/cash-app-pay/accept-a-payment?payment-ui=mobile&platform=react-native. Cash App Pay は、すべての Cash App の顧客が 1 回限りの使用およびビジネスへの継続支払いに使用できる支払い方法です。Cash App Pay は、顧客の保存された残高または関連付けられたデビットカードを使用して、支払いを実行します。顧客は、以下の 2 通りの方法のいずれかで支払いを確定できます。 - モバイルデバイスからの決済時に、サイトで顧客は Cash App モバイルアプリケーションにリダイレクトされ、そこで認証を行います。支払いはリダイレクト時に認証されます。Cash App モバイルアプリケーションでは購入を完了するために、それ以上のアクションを実行する必要はありません。その後、顧客はサイトにリダイレクトされて戻ります。 - デスクトップ版ウェブアプリケーションからの決済時に、顧客はモバイルデバイスで QR コードをスキャンして、取引を認証します。 顧客は、将来のオンファイル決済に Cash App Pay を使用することもオーソリできます。 ## 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' ``` ### クライアント側 [React Native SDK](https://github.com/stripe/stripe-react-native) はオープンソースであり、詳細なドキュメントが提供されています。内部では、[ネイティブの iOS](https://github.com/stripe/stripe-ios) および [Android](https://github.com/stripe/stripe-android) の SDK を使用します。Stripe の React Native SDK をインストールするには、プロジェクトのディレクトリーで (使用するパッケージマネージャーによって異なる) 次のいずれかのコマンドを実行します。 #### yarn ```bash yarn add @stripe/stripe-react-native ``` #### npm ```bash npm install @stripe/stripe-react-native ``` 次に、その他の必要な依存関係をインストールします。 - iOS の場合は、**ios** ディレクトリに移動して `pod install` を実行し、必要なネイティブ依存関係もインストールします。 - Android の場合は、依存関係をインストールする必要はありません。 > [公式の TypeScript ガイド](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project)に従って TypeScript のサポートを追加することをお勧めします。 ### Stripe の初期化 React Native アプリで Stripe を初期化するには、決済画面を `StripeProvider` コンポーネントでラップするか、`initStripe` 初期化メソッドを使用します。`publishableKey` の API [公開可能キー](https://docs.stripe.com/keys.md#obtain-api-keys)のみが必要です。次の例は、`StripeProvider` コンポーネントを使用して Stripe を初期化する方法を示しています。 ```jsx import { useState, useEffect } from 'react'; import { StripeProvider } from '@stripe/stripe-react-native'; function App() { const [publishableKey, setPublishableKey] = useState(''); const fetchPublishableKey = async () => { const key = await fetchKey(); // fetch key from your server here setPublishableKey(key); }; useEffect(() => { fetchPublishableKey(); }, []); return ( {/* Your app code here */} ); } ``` > テストおよび開発時には API の[テストキー](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) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 サーバーで `PaymentIntent` を作成して確定するには、以下の手順に従います。 - 回収する金額と通貨を指定します。 - `PaymentIntent` の[支払い方法のタイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに `cashapp` を追加します。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)で Cash App Pay が有効になっていることを確認してください。 ```curl curl https://api.stripe.com/v1/payment_intents \ -u "<>:" \ -d amount=6000 \ -d currency=usd \ -d "payment_method_types[]=cashapp" \ --data-urlencode "return_url=payments-example://stripe-redirect" ``` 返される 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)) が含まれ、これは PaymentIntent の*確定* (Confirming an intent indicates that the customer intends to use the current or provided payment method. Upon confirmation, the intent attempts to initiate the portions of the flow that have real-world side effects)に使用されます。次のステップで使用できるように、クライアントに 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)) を保存します。 ```javascript function PaymentScreen() { const fetchPaymentIntentClientSecret = async () => { const response = await fetch(`${API_URL}/create-payment-intent`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ currency: 'usd', }), }); const {clientSecret} = await response.json(); return clientSecret; }; const handlePayPress = async () => { // See below }; return (