# OXXO での支払いを受け付ける メキシコで一般的な支払い方法である OXXO を受け付ける方法をご紹介します。 # Checkout > This is a Checkout for when payment-ui is checkout. View the full page at https://docs.stripe.com/payments/oxxo/accept-a-payment?payment-ui=checkout. > 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)を使用するチェックアウトの統合機能を構築します。 - 動的な決済手段を使用しない場合は、チェックアウトの導入で、決済方法を手動で設定するために以下のステップに従ってください。 OXXO は [1 回限りの使用](https://docs.stripe.com/payments/payment-methods.md#usage)の支払い方法であり、顧客が支払いを完了するには、[追加の手順を実行](https://docs.stripe.com/payments/payment-methods.md#customer-actions)する必要があります。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は、OXXO コンビニエンスストアで、生成された番号が記載された OXXO の支払いコードを提示し、現金で支払います。 ## 互換性を判断する **サポート対象のビジネスの所在地**: MX **対応可能な通貨**: `mxn` **取引通貨**: `mxn` **支払いモード**: Yes **セットアップモード**: No **サブスクリプションモード**: No OXXO での支払いに対応するには、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)が、同じ通貨である必要があります。異なる通貨のラインアイテムが存在する場合は、通貨ごとに別の Checkout セッションを作成します。 - 使用できるのは単一の項目だけです (継続的な*サブスクリプション* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)プランには対応していません)。 ## 決済を受け付ける > このガイドを使用する前に、まず Checkout で[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md?integration=checkout)ための実装を構築します。 このガイドでは、OXXO を有効にする方法について手順を追って説明し、動的な支払い方法を使用して決済を受け付ける場合と支払い方法を手動で設定する場合の違いを示します。 ### 支払い方法として OXXO を有効にする 新しい [Checkout Session (セッション)](https://docs.stripe.com/api/checkout/sessions.md) を作成する際は、以下を行う必要があります。 1. `oxxo` を `payment_method_types` のリストに追加します。 1. すべての `line_items` が `mxn` 通貨を使用していることを確認します。 #### Stripe がオンラインで提供するページ ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=mxn" \ -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]=oxxo" \ --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]=mxn" \ -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]=oxxo" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### 支払い方法のその他のオプション `Session` の[支払い方法オプション](https://docs.stripe.com/api/checkout/sessions/create.md#create_checkout_session-payment_method_options-oxxo-expires_after_days)でオプションの `expires_after_days` パラメーターを指定すると、OXXO 支払いの有効期限が切れるまでの日数を設定できます。たとえば、月曜日に OXXO の取引の詳細を作成し、`expires_after_days` を 2 に設定した場合、OXXO の支払いは、America/Mexico_City (UTC-6) 時間で水曜日の 23:59 に有効期限が切れます。`expires_after_days` パラメーターは 1 日から 7 日までの範囲で設定できます。デフォルトは 3 日です。 #### Stripe がオンラインで提供するページ ```curl curl https://api.stripe.com/v1/checkout/sessions \ -u "<>:" \ -d "line_items[0][price_data][currency]=mxn" \ -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_options[oxxo][expires_after_days]=2" \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=oxxo" \ --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]=mxn" \ -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_options[oxxo][expires_after_days]=2" \ -d "payment_method_types[0]=card" \ -d "payment_method_types[1]=oxxo" \ --data-urlencode "return_url=https://example.com/return" \ -d ui_mode=embedded_page ``` ### Stripe がオンラインで提供する取引の詳細ページにリダイレクトする Checkout フォームの送信に成功すると、顧客は `hosted_voucher_url` にリダイレクトされます。顧客はオンラインで提供される取引の詳細ページからバーコードを見つけたり、OXXO を印刷したりできます。`hosted_voucher_url` は[payment_intent.next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-hosted_voucher_url) にあります。 Stripe では、[ブランディング設定](https://dashboard.stripe.com/account/branding) ページで顧客に表示される UI をカスタマイズすることができます。取引の詳細には、以下のブランド設定を適用できます。 - **アイコン**: ブランド画像と公開ビジネス名 - **アクセント**: 印刷ボタンの色として使用されます - **ブランドカラー**: 背景色として使用されます ### 注文のフルフィルメントを実行する OXXO は通知遅延型の支払い方法であるため、*Webhook* (A webhook is a real-time push notification sent to your application as a JSON payload through HTTPS requests) などの方法を使用して支払いステータスを監視し、注文の*フルフィルメント* (Fulfillment is the process of providing the goods or services purchased by a customer, typically after payment is collected)を履行する必要があります。[Webhook の設定と注文のフルフィルメントの履行](https://docs.stripe.com/checkout/fulfillment.md)で詳細をご覧ください。 支払いステータスに変化があると、以下のイベントが送信されます。 | イベント名 | 説明 | 次のステップ | | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | | [checkout.session.completed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.completed) | 顧客が Checkout フォームの送信を完了しました。Stripe は OXXO 支払い向けに取引の詳細を作成しました。 顧客が OXXO の支払いコードを失くした場合、顧客に `hosted_voucher_url` をメールで送信することもできます。 | 顧客が OXXO で支払うのを待ちます。 | | [checkout.session.async_payment_succeeded](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_succeeded) | 顧客は OXXO の支払いを完了しました。`PaymentIntent` は `succeeded` に変わります。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | [checkout.session.async_payment_failed](https://docs.stripe.com/api/events/types.md#event_types-checkout.session.async_payment_failed) | OXXO の支払いコードの有効期限が切れたか、その他の理由で支払いが失敗しました。`PaymentIntent` のステータスは `requires_payment_method` に戻ります。 | 顧客にメールで連絡して、新たに注文を行うようリクエストします。 | ## 導入をテストする Checkout の組み込みをテストする際は、支払い方法として OXXO を選択して、**支払う**ボタンをクリックします。 | メールアドレス | 説明 | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `{any_prefix}@{any_domain}` | 顧客が 3 分後に支払い、約 3 分後に `payment_intent.succeeded` Webhook を受信する OXXO 支払いをシミュレーションします。本番環境では、この Webhook は 1 営業日後に受信します。 例: fulano@test.com | | `{any_prefix}succeed_immediately@{any_domain}` | 顧客が即座に支払う OXXO をシミュレーションし、`payment_intent.succeeded` Webhook を数秒以内に受信します。本番環境では、この Webhook は 1 営業日後に受信します。 例: succeed_immediately@test.com | | `{any_prefix}expire_immediately@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を数秒以内に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドには、現在時刻が設定されます。 例: expire_immediately@test.com | | `{any_prefix}expire_with_delay@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を約 3 分後に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドが 3 分後に設定されます。 例: expire_with_delay@test.com | | `{any_prefix}fill_never@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を 1 営業日と 2 日後に受信する OXXO をシミュレーションします。本番環境では、この Webhook をテスト環境と同じタイミングで受信します。 例: fill_never@test.com | ## Optional: 決済手順メールを送信する ダッシュボードの[メール設定](https://dashboard.stripe.com/settings/emails)ページで OXXO 決済の手順メールを有効にできます。有効にすると、Stripe は、PaymentIntent の確定時に決済手順メールを送信します。メールには、OXXO 番号と Stripe の店舗支払いページへのリンクが含まれます。 > テスト環境では、手順メールは Stripe アカウントに関連付けられたメールアドレスにのみ送信されます。 ## See also - [Checkout のフルフィルメント](https://docs.stripe.com/checkout/fulfillment.md) - [Checkout のカスタマイズ](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/oxxo/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)に関する導入ガイドをご覧ください。 ## 互換性を判断する **サポート対象のビジネスの所在地**: MX **対応可能な通貨**: `mxn` **取引通貨**: `mxn` **支払いモード**: Yes **セットアップモード**: No **サブスクリプションモード**: No OXXO での支払いに対応するには、Checkout セッションが次の条件をすべて満たしている必要があります。 - すべてのラインアイテムの価格が、同じ通貨である必要があります。異なる通貨のラインアイテムが存在する場合は、通貨ごとに別の Checkout セッションを作成します。 - 使用できるのは 1 回限りの項目のみです (継続的なサブスクリプションプランには対応していません)。 ## サーバーを設定する [サーバー側] アプリケーションから 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: 'mxn', 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: 'mxn', product_data: { name: 'T-shirt', }, unit_amount: 1099, }, quantity: 1, }, ], mode: 'payment', ui_mode: 'elements', payment_method_types: ['oxxo'], 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; ``` ## 導入をテストする 実装内容をテストするには、決済手段を選択して**支払う**をタップします。*サンドボックス* (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)では、テスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、oxxo のウェブサイトにリダイレクトされます。oxxo で支払いを承認または拒否するオプションはありません。 # 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/oxxo/accept-a-payment?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: 'mxn', // 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: 'mxn', paymentMethodTypes: ['oxxo'], // 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: 'mxn', // 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: 'mxn', paymentMethodTypes: ['oxxo'], // 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: 'mxn', }) {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: 'mxn', }) {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: 'mxn', payment_method_types: ['oxxo'], }) {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: 'mxn', payment_method_types: ['oxxo'], }) {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: 支払い後のイベントを処理する 支払いが完了すると、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)などの一般的なビジネスイベントを処理します。 ## 導入をテストする 実装内容をテストするには、決済手段を選択して**支払う**をタップします。*サンドボックス* (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)では、テスト決済ページにリダイレクトされ、そこで決済を承認または拒否できます。 本番環境では、**支払う**をタップすると、oxxo のウェブサイトにリダイレクトされます。oxxo で支払いを承認または拒否するオプションはありません。 ## エラーコード 次の表に、一般的なエラーコードと推奨される対応の詳細を示します。 | エラーコード | 推奨される対応 | | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `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` を指定します。 | # 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/oxxo/accept-a-payment?payment-ui=mobile&platform=ios. > サーバー側での手動確定を使用する必要がある場合、またはお使いの実装で決済手段を別途表示する必要がある場合を除き、[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md)ガイドに従うことをお勧めします。すでに Elements との連携が完了している場合は、[Payment Element 移行ガイド](https://docs.stripe.com/payments/payment-element/migration.md)をご覧ください。 アプリで OXXO を受け付けるには、Webview で OXXO の取引の詳細を表示します。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は、OXXO コンビニエンスストアで、生成された番号が記載された取引の詳細を提示し、現金で支払います。支払いが完了すると、Stripe からお客様に通知が送られます。 ## 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) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 ### サーバー側 サーバーで金額と`mxn`通貨を使用して PaymentIntent を作成します (OXXO は他の通貨をサポートしていません)。すでに[Payment Intents API](https://docs.stripe.com/payments/payment-intents.md)を使用した統合がある場合は、`PaymentIntent`の[決済手段タイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに`oxxo`を追加します。 #### curl ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -d "amount"=1099 \ -d "currency"="mxn" \ -d "payment_method_types[]"="oxxo" ``` ### その他の支払い方法オプション `PaymentIntent` の[支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)でオプションの `expires_after_days` パラメーターを指定して、OXXO の支払い票の有効期限が切れるまでの日数を設定できます。たとえば、月曜日に OXXO の支払い票を作成し、`expires_after_days` を 2 に設定した場合、OXXO の支払い票は、America/Mexico_City (UTC-6) 時間で水曜日の 23:59 に有効期限が切れます。`expires_after_days` パラメーターは 1 日から 7 日まで設定できます。デフォルトは 3 日です。 ### クライアント側 クライアント側で、サーバーの PaymentIntent をリクエストし、その client secret を保存します。 #### Swift ```swift class CheckoutViewController: UIViewController { var paymentIntentClientSecret: String? func startCheckout() { // Request a PaymentIntent from your server and store its client secret } } ``` ## 支払い方法の詳細を収集する [クライアント側] アプリでは、以下の必要な請求先情報を顧客から収集します。請求先情報を使用して [STPPaymentIntentParams](https://stripe.dev/stripe-ios/stripe-payments/Classes/STPPaymentIntentParams.html) を作成します。 | フィールド | 値 | | ------- | -------------------------------- | | `name` | 顧客の氏名。姓と名はそれぞれ 2 文字以上である必要があります。 | | `email` | 顧客のメールアドレス。 | #### Swift ```swift let billingDetails = STPPaymentMethodBillingDetails() billingDetails.name = "Jane Doe" billingDetails.email = "test@example.com" EOF ) ``` ## Stripe に支払いを送信する [クライアント側] ステップ 2 で作成した PaymentIntent から client secret を取得し、[STPPaymentHandler confirmPayment](https://stripe.dev/stripe-ios/stripe-payments/Classes/STPPaymentHandler.html#/c:@M@StripePayments@objc\(cs\)STPPaymentHandler\(im\)confirmPayment:withAuthenticationContext:completion:) を呼び出します。これにより、OXXO の取引の詳細を表示する WebView が表示されます。完了後、支払いの結果とともに、完了ブロックが呼び出されます。 #### Swift ```swift let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret) let oxxoParams = STPPaymentMethodOXXOParams(); paymentIntentParams.paymentMethodParams = STPPaymentMethodParams( oxxo: oxxoParams, billingDetails: billingDetails, metadata: nil ) STPPaymentHandler.shared().confirmPayment(paymentIntentParams, with: self) { (handlerStatus, paymentIntent, error) in switch handlerStatus { case .succeeded: // The OXXO voucher was displayed successfully. The customer can now pay the OXXO voucher at the OXXO convenience store. case .canceled: // Payment was canceled case .failed: // Payment failed @unknown default: fatalError() } } ``` ### オプション: 顧客に取引の詳細へのリンクをメールで送信する Stripe は、OXXO の取引の詳細が正常に作成されると、[payment_intent.requires_action](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.requires_action) イベントを送信します。顧客に取引の詳細のリンクをメールで送信する必要がある場合は、イベントの受信時に [PaymentIntent (支払いインテント) を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)することで、リンクを取得できます。[payment_intent.next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-hosted_voucher_url) の `hosted_voucher_url` フィールドには、取引の詳細へのリンクが含まれています。 ### オプション: 取引の詳細をカスタマイズする Stripe では、[ブランディング設定](https://dashboard.stripe.com/account/branding)ページで、顧客に表示される UI をカスタマイズできます。 取引の詳細には、以下のブランド設定を適用できます。 - **アイコン**: ブランド画像と公開ビジネス名 - **アクセント**—番号コピーボタンの色として使用されます - **ブランドカラー**: 背景色として使用されます ## 支払い後のイベントを処理する [サーバー側] OXXO は[通知遅延型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の決済手段であるため、売上はすぐには利用可能になりません。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は決済直後に OXXO コンビニエンスストアで OXXO 店舗支払いの決済を行わない場合があります。 Stripe は、支払われた OXXO の支払いごとに、翌営業日 (メキシコの祝日を除く月曜日から金曜日) に [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) ハンドラーを構築して、これらのイベントを受信し、アクション (顧客への注文確認メールの送信、データベースへの売上の記録、配送ワークフローの開始など) を実行します。 有効期限日を過ぎると、PaymentIntent のステータスは `processing` に移行し、顧客は期限切れの OXXO 店舗支払いに対して支払いを行うことができなくなります。OXXO 店舗支払いが有効期限日の 23:59 America/Mexico_City (UTC-6) より前に支払われなかった場合、Stripe は有効期限日から 10 日以内に [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) イベントを送信します (ほとんどの場合、このイベントは 7 日以内に送信されます)。たとえば、OXXO 店舗支払いが 9 月 1 日に有効期限が切れる場合、このイベントは遅くとも 9 月 10 日までに送信されます。 | イベント | 説明 | 次のステップ | | -------------------------------- | -------------------------------------- | ------------------------------------ | | `payment_intent.requires_action` | OXXO の支払い票が正常に作成されました。 | 顧客が OXXO で支払うのを待ちます。 | | `payment_intent.processing` | 顧客は OXXO の支払いができなくなりました。 | 支払いの成功、または失敗を待ちます。 | | `payment_intent.succeeded` | 顧客は有効期限が切れる前に OXXO の支払い票に対する支払いを行いました。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | `payment_intent.payment_failed` | 顧客が有効期限までに OXXO 店舗支払いに対する支払いを行いませんでした。 | 顧客にメールまたはプッシュ通知で連絡し、別の決済手段をリクエストします。 | ### イベントを受信し、ビジネスアクションを実行する #### 手動 Stripe ダッシュボードを使用して、Stripe のすべての支払いの確認、メール領収書の送信、入金処理、失敗した支払いの再試行を実行します。 - [ダッシュボードでテスト支払いを確認する](https://dashboard.stripe.com/test/payments) #### カスタムコード Webhook ハンドラを構築してイベントをリッスンし、非同期型のカスタムの決済フローを作成します。Stripe CLI を使用して、ローカルで Webhook の組み込みのテストとデバッグを行います。 - [カスタム webhook を構築](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) ## 構築したシステムをテストする *サンドボックス* (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)では、[STPPaymentHandler confirmPayment] (https://stripe.dev/stripe-ios/stripe-payments/Classes/STPPaymentHandler.html#/c:@M@StripePayments@objc(cs)STPPaymentHandler(im)confirmPayment:withAuthenticationContext:completion:) を呼び出すときに [STPPaymentMethodBillingDetails email] (https://stripe.dev/stripe-ios/stripe-payments/Classes/STPPaymentMethodBillingDetails.html#/c:@M@StripePayments@objc(cs)STPPaymentMethodBillingDetails(py)email) を次の値に設定することで、さまざまなシナリオをテストできます。 | メールアドレス | 説明 | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `{any_prefix}@{any_domain}` | 顧客が 3 分後に支払い、約 3 分後に `payment_intent.succeeded` Webhook を受信する OXXO 支払いをシミュレーションします。本番環境では、この Webhook は 1 営業日後に受信します。 例: fulano@test.com | | `{any_prefix}succeed_immediately@{any_domain}` | 顧客が即座に支払う OXXO をシミュレーションし、`payment_intent.succeeded` Webhook を数秒以内に受信します。本番環境では、この Webhook は 1 営業日後に受信します。 例: succeed_immediately@test.com | | `{any_prefix}expire_immediately@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を数秒以内に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドには、現在時刻が設定されます。 例: expire_immediately@test.com | | `{any_prefix}expire_with_delay@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を約 3 分後に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドが 3 分後に設定されます。 例: expire_with_delay@test.com | | `{any_prefix}fill_never@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を 1 営業日と 2 日後に受信する OXXO をシミュレーションします。本番環境では、この Webhook をテスト環境と同じタイミングで受信します。 例: fill_never@test.com | ## 有効期限とキャンセル OXXO バウチャーは `expires_after` UNIX タイムスタンプを過ぎると期限切れになり、顧客は有効期限が切れた OXXO バウチャーの支払いはできません。有効期限前に OXXO バウチャーをキャンセルすることはできません。 OXXO 支払い票の有効期限が切れると、PaymentIntent のステータスは `requires_payment_method` に変わります。この時点では、別の支払い方法を指定して PaymentIntent を確定するか、キャンセルすることができます。 # 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/oxxo/accept-a-payment?payment-ui=mobile&platform=android. > サーバー側での手動確定を使用する必要がある場合、またはお使いの実装で決済手段を別途表示する必要がある場合を除き、[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md)ガイドに従うことをお勧めします。すでに Elements との連携が完了している場合は、[Payment Element 移行ガイド](https://docs.stripe.com/payments/payment-element/migration.md)をご覧ください。 アプリで OXXO を受け付けるには、Webview で OXXO の取引の詳細を表示します。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は、OXXO コンビニエンスストアで、生成された番号が記載された取引の詳細を提示し、現金で支払います。支払いが完了すると、Stripe からお客様に通知が送られます。 ## 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.8.0") // Include the financial connections SDK to support US bank account as a payment method implementation("com.stripe:financial-connections:23.8.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) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 ### サーバー側 サーバーで金額と`mxn`通貨を使用して PaymentIntent を作成します (OXXO は他の通貨をサポートしていません)。すでに[Payment Intents API](https://docs.stripe.com/payments/payment-intents.md)を使用した統合がある場合は、`PaymentIntent`の[決済手段タイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに`oxxo`を追加します。 #### curl ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -d "amount"=1099 \ -d "currency"="mxn" \ -d "payment_method_types[]"="oxxo" ``` ### その他の支払い方法オプション `PaymentIntent` の[支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)でオプションの `expires_after_days` パラメーターを指定して、OXXO の支払い票の有効期限が切れるまでの日数を設定できます。たとえば、月曜日に OXXO の支払い票を作成し、`expires_after_days` を 2 に設定した場合、OXXO の支払い票は、America/Mexico_City (UTC-6) 時間で水曜日の 23:59 に有効期限が切れます。`expires_after_days` パラメーターは 1 日から 7 日まで設定できます。デフォルトは 3 日です。 ### クライアント側 クライアント側で、サーバーの PaymentIntent をリクエストし、その client secret を保存します。 #### Kotlin ```kotlin class OXXOActivity: AppCompatActivity() { private lateinit var paymentIntentClientSecret: String private fun startCheckout() { // Request a PaymentIntent from your server and store its client secret } } ``` ## 支払い方法の詳細を収集する [クライアント側] アプリで、必要とされる次の請求詳細を顧客から収集し、その請求詳細を使用して [PaymentMethodCreateParams](https://stripe.dev/stripe-android/payments-core/com.stripe.android.model/-payment-method-create-params/index.html) を作成します。 | フィールド | 値 | | ------- | -------------------------------- | | `name` | 顧客の氏名。姓と名はそれぞれ 2 文字以上である必要があります。 | | `email` | 顧客のメールアドレス。 | #### Kotlin ```kotlin val billingDetails = PaymentMethod.BillingDetails(email = "email@email.com", name = "Jenny Rosen") val paymentMethodCreateParams = PaymentMethodCreateParams.createOxxo(billingDetails) ``` ## Stripe に支払いを送信する [クライアント側] ステップ 2 で作成した PaymentIntent から client secret を取得し、[PaymentLauncher confirm](https://stripe.dev/stripe-android/payments-core/com.stripe.android.payments.paymentlauncher/-payment-launcher/index.html#74063765%2FFunctions%2F-1622557690) を呼び出します。これにより、OXXO の支払いコードを表示する Webview が示されます。その後、支払い結果とともに、`onPaymentResult` が呼び出されます。 #### Kotlin ```kotlin class OXXOActivity : AppCompatActivity() { // ... private lateinit var paymentIntentClientSecret: String private val paymentLauncher: PaymentLauncher by lazy { val paymentConfiguration = PaymentConfiguration.getInstance(applicationContext) PaymentLauncher.Companion.create( this, paymentConfiguration.publishableKey, paymentConfiguration.stripeAccountId, ::onPaymentResult ) } private fun startCheckout() { // ... val confirmParams = ConfirmPaymentIntentParams .createWithPaymentMethodCreateParams( paymentMethodCreateParams = paymentMethodCreateParams, clientSecret = paymentIntentClientSecret ) paymentLauncher.confirm(confirmParams) } private fun onPaymentResult(paymentResult: PaymentResult) { when (paymentResult) { is PaymentResult.Completed -> { // The OXXO voucher was displayed successfully. // The customer can now pay the OXXO voucher at the OXXO convenience store. } is PaymentResult.Canceled -> { // handle cancel flow } is PaymentResult.Failed -> { // handle failures // (for example, the customer may need to choose a new payment // method) } } } } ``` ### オプション: 顧客に取引の詳細へのリンクをメールで送信する Stripe は、OXXO の取引の詳細が正常に作成されると、[payment_intent.requires_action](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.requires_action) イベントを送信します。顧客に取引の詳細のリンクをメールで送信する必要がある場合は、イベントの受信時に [PaymentIntent (支払いインテント) を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)することで、リンクを取得できます。[payment_intent.next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-hosted_voucher_url) の `hosted_voucher_url` フィールドには、取引の詳細へのリンクが含まれています。 ### オプション: 取引の詳細をカスタマイズする Stripe では、[ブランディング設定](https://dashboard.stripe.com/account/branding)ページで、顧客に表示される UI をカスタマイズできます。 取引の詳細には、以下のブランド設定を適用できます。 - **アイコン**: ブランド画像と公開ビジネス名 - **アクセント**—番号コピーボタンの色として使用されます - **ブランドカラー**: 背景色として使用されます ## 支払い後のイベントを処理する [サーバー側] OXXO は[通知遅延型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の決済手段であるため、売上はすぐには利用可能になりません。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は決済直後に OXXO コンビニエンスストアで OXXO 店舗支払いの決済を行わない場合があります。 Stripe は、支払われた OXXO の支払いごとに、翌営業日 (メキシコの祝日を除く月曜日から金曜日) に [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) ハンドラーを構築して、これらのイベントを受信し、アクション (顧客への注文確認メールの送信、データベースへの売上の記録、配送ワークフローの開始など) を実行します。 有効期限日を過ぎると、PaymentIntent のステータスは `processing` に移行し、顧客は期限切れの OXXO 店舗支払いに対して支払いを行うことができなくなります。OXXO 店舗支払いが有効期限日の 23:59 America/Mexico_City (UTC-6) より前に支払われなかった場合、Stripe は有効期限日から 10 日以内に [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) イベントを送信します (ほとんどの場合、このイベントは 7 日以内に送信されます)。たとえば、OXXO 店舗支払いが 9 月 1 日に有効期限が切れる場合、このイベントは遅くとも 9 月 10 日までに送信されます。 | イベント | 説明 | 次のステップ | | -------------------------------- | -------------------------------------- | ------------------------------------ | | `payment_intent.requires_action` | OXXO の支払い票が正常に作成されました。 | 顧客が OXXO で支払うのを待ちます。 | | `payment_intent.processing` | 顧客は OXXO の支払いができなくなりました。 | 支払いの成功、または失敗を待ちます。 | | `payment_intent.succeeded` | 顧客は有効期限が切れる前に OXXO の支払い票に対する支払いを行いました。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | `payment_intent.payment_failed` | 顧客が有効期限までに OXXO 店舗支払いに対する支払いを行いませんでした。 | 顧客にメールまたはプッシュ通知で連絡し、別の決済手段をリクエストします。 | ### イベントを受信し、ビジネスアクションを実行する #### 手動 Stripe ダッシュボードを使用して、Stripe のすべての支払いの確認、メール領収書の送信、入金処理、失敗した支払いの再試行を実行します。 - [ダッシュボードでテスト支払いを確認する](https://dashboard.stripe.com/test/payments) #### カスタムコード Webhook ハンドラを構築してイベントをリッスンし、非同期型のカスタムの決済フローを作成します。Stripe CLI を使用して、ローカルで Webhook の組み込みのテストとデバッグを行います。 - [カスタム webhook を構築](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) ## 構築したシステムをテストする サンドボックスでは、[Stripe\# confirmPayment()](https://stripe.dev/stripe-android/payments-core/com.stripe.android/-stripe/confirm-payment.html) を呼び出すときに [PaymentMethod.BillingDetails#email](https://stripe.dev/stripe-android/payments-core/com.stripe.android.model/-payment-method/-billing-details/index.html) を次の値に設定することで、さまざまなシナリオをテストできます。 | メールアドレス | 説明 | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `{any_prefix}@{any_domain}` | 顧客が 3 分後に支払い、約 3 分後に `payment_intent.succeeded` Webhook を受信する OXXO 支払いをシミュレーションします。本番環境では、この Webhook は 1 営業日後に受信します。 例: fulano@test.com | | `{any_prefix}succeed_immediately@{any_domain}` | 顧客が即座に支払う OXXO をシミュレーションし、`payment_intent.succeeded` Webhook を数秒以内に受信します。本番環境では、この Webhook は 1 営業日後に受信します。 例: succeed_immediately@test.com | | `{any_prefix}expire_immediately@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を数秒以内に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドには、現在時刻が設定されます。 例: expire_immediately@test.com | | `{any_prefix}expire_with_delay@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を約 3 分後に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドが 3 分後に設定されます。 例: expire_with_delay@test.com | | `{any_prefix}fill_never@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を 1 営業日と 2 日後に受信する OXXO をシミュレーションします。本番環境では、この Webhook をテスト環境と同じタイミングで受信します。 例: fill_never@test.com | ## 有効期限とキャンセル OXXO バウチャーは `expires_after` UNIX タイムスタンプを過ぎると期限切れになり、顧客は有効期限が切れた OXXO バウチャーの支払いはできません。有効期限前に OXXO バウチャーをキャンセルすることはできません。 OXXO 支払い票の有効期限が切れると、PaymentIntent のステータスは `requires_payment_method` に変わります。この時点では、別の支払い方法を指定して PaymentIntent を確定するか、キャンセルすることができます。 # 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/oxxo/accept-a-payment?payment-ui=mobile&platform=react-native. > サーバー側での手動確定を使用する必要がある場合、またはお使いの実装で決済手段を別途表示する必要がある場合を除き、[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md)ガイドに従うことをお勧めします。すでに Elements との連携が完了している場合は、[Payment Element 移行ガイド](https://docs.stripe.com/payments/payment-element/migration.md)をご覧ください。 アプリで OXXO を受け付けるには、Webview で OXXO の取引の詳細を表示します。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は、OXXO コンビニエンスストアで、生成された番号が記載された取引の詳細を提示し、現金で支払います。支払いが完了すると、Stripe からお客様に通知が送られます。 ## Stripe を設定する [サーバ側] [クライアント側] ### サーバ側 この組み込みには、Stripe API と通信するエンドポイントがサーバ上に必要です。Stripe の公式ライブラリを使用して、サーバから 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' ``` ### クライアント側 [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) は、顧客から支払いを回収する意図を表すオブジェクトで、決済プロセスのライフサイクルの各段階を追跡します。 ### サーバー側 サーバーで金額と`mxn`通貨を使用して PaymentIntent を作成します (OXXO は他の通貨をサポートしていません)。すでに[Payment Intents API](https://docs.stripe.com/payments/payment-intents.md)を使用した統合がある場合は、`PaymentIntent`の[決済手段タイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに`oxxo`を追加します。 #### curl ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -d "amount"=1099 \ -d "currency"="mxn" \ -d "payment_method_types[]"="oxxo" ``` ### その他の支払い方法オプション `PaymentIntent` の[支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)でオプションの `expires_after_days` パラメーターを指定して、OXXO の支払い票の有効期限が切れるまでの日数を設定できます。たとえば、月曜日に OXXO の支払い票を作成し、`expires_after_days` を 2 に設定した場合、OXXO の支払い票は、America/Mexico_City (UTC-6) 時間で水曜日の 23:59 に有効期限が切れます。`expires_after_days` パラメーターは 1 日から 7 日まで設定できます。デフォルトは 3 日です。 ### クライアント側 クライアント側で、サーバーの 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 const fetchPaymentIntentClientSecret = async () => { const response = await fetch(`${API_URL}/create-payment-intent`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email, currency: 'mxn', payment_method_types: ['oxxo'], }), }); const {clientSecret, error} = await response.json(); return {clientSecret, error}; }; ``` ## 支払い方法の詳細を収集する [クライアント側] アプリで顧客の氏名とメールアドレスを収集します。 ```javascript export default function OxxoPaymentScreen() { const [name, setName] = useState(); const [email, setEmail] = useState(); const handlePayPress = async () => { // ... }; return ( setName(value.nativeEvent.text)} /> setEmail(value.nativeEvent.text)} /> ); } ``` ## Stripe に支払いを送信する [クライアント側] 作成した PaymentIntent から client secret を取得し、`confirmPayment` を呼び出します。これにより、Webview で OXXO 支払い向けに取引の詳細が表示されます。 ```javascript export default function OxxoPaymentScreen() { const [name, setName] = useState(); const [email, setEmail] = useState(); const handlePayPress = async () => { const billingDetails: PaymentMethodCreateParams.BillingDetails = { name, email, }; const { error, paymentIntent } = await confirmPayment(clientSecret, { paymentMethodType: 'Oxxo', paymentMethodData: { billingDetails, } }); if (error) { Alert.alert(`Error code: ${error.code}`, error.message); console.log('Payment confirmation error', error.message); } else if (paymentIntent) { if (paymentIntent.status === PaymentIntents.Status.RequiresAction) { Alert.alert( 'Success', `The OXXO voucher was created successfully. Awaiting payment from customer.` ); } else { Alert.alert('Payment intent status:', paymentIntent.status); } } }; return ( setName(value.nativeEvent.text)} /> setEmail(value.nativeEvent.text)} /> ); } ``` ### オプション: 顧客に取引の詳細へのリンクをメールで送信する Stripe は、OXXO の取引の詳細が正常に作成されると、[payment_intent.requires_action](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.requires_action) イベントを送信します。顧客に取引の詳細のリンクをメールで送信する必要がある場合は、イベントの受信時に [PaymentIntent (支払いインテント) を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)することで、リンクを取得できます。[payment_intent.next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-hosted_voucher_url) の `hosted_voucher_url` フィールドには、取引の詳細へのリンクが含まれています。 ### オプション: 取引の詳細をカスタマイズする Stripe では、[ブランディング設定](https://dashboard.stripe.com/account/branding)ページで、顧客に表示される UI をカスタマイズできます。 取引の詳細には、以下のブランド設定を適用できます。 - **アイコン**: ブランド画像と公開ビジネス名 - **アクセント**—番号コピーボタンの色として使用されます - **ブランドカラー**: 背景色として使用されます ## 支払い後のイベントを処理する [サーバー側] OXXO は[通知遅延型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の決済手段であるため、売上はすぐには利用可能になりません。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は決済直後に OXXO コンビニエンスストアで OXXO 店舗支払いの決済を行わない場合があります。 Stripe は、支払われた OXXO の支払いごとに、翌営業日 (メキシコの祝日を除く月曜日から金曜日) に [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) ハンドラーを構築して、これらのイベントを受信し、アクション (顧客への注文確認メールの送信、データベースへの売上の記録、配送ワークフローの開始など) を実行します。 有効期限日を過ぎると、PaymentIntent のステータスは `processing` に移行し、顧客は期限切れの OXXO 店舗支払いに対して支払いを行うことができなくなります。OXXO 店舗支払いが有効期限日の 23:59 America/Mexico_City (UTC-6) より前に支払われなかった場合、Stripe は有効期限日から 10 日以内に [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) イベントを送信します (ほとんどの場合、このイベントは 7 日以内に送信されます)。たとえば、OXXO 店舗支払いが 9 月 1 日に有効期限が切れる場合、このイベントは遅くとも 9 月 10 日までに送信されます。 | イベント | 説明 | 次のステップ | | -------------------------------- | -------------------------------------- | ------------------------------------ | | `payment_intent.requires_action` | OXXO の支払い票が正常に作成されました。 | 顧客が OXXO で支払うのを待ちます。 | | `payment_intent.processing` | 顧客は OXXO の支払いができなくなりました。 | 支払いの成功、または失敗を待ちます。 | | `payment_intent.succeeded` | 顧客は有効期限が切れる前に OXXO の支払い票に対する支払いを行いました。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | `payment_intent.payment_failed` | 顧客が有効期限までに OXXO 店舗支払いに対する支払いを行いませんでした。 | 顧客にメールまたはプッシュ通知で連絡し、別の決済手段をリクエストします。 | ### イベントを受信し、ビジネスアクションを実行する #### 手動 Stripe ダッシュボードを使用して、Stripe のすべての支払いの確認、メール領収書の送信、入金処理、失敗した支払いの再試行を実行します。 - [ダッシュボードでテスト支払いを確認する](https://dashboard.stripe.com/test/payments) #### カスタムコード Webhook ハンドラを構築してイベントをリッスンし、非同期型のカスタムの決済フローを作成します。Stripe CLI を使用して、ローカルで Webhook の組み込みのテストとデバッグを行います。 - [カスタム webhook を構築](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) ## 構築したシステムをテストする サンドボックスでは、`confirmPayment` を呼び出してさまざまなシナリオをテストするときに、次のメールアドレスを使用します。 | メールアドレス | 説明 | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `{any_prefix}@{any_domain}` | 顧客が 3 分後に支払い、約 3 分後に `payment_intent.succeeded` Webhook を受信する OXXO 支払いをシミュレーションします。本番環境では、この Webhook は 1 営業日後に受信します。 例: fulano@test.com | | `{any_prefix}succeed_immediately@{any_domain}` | 顧客が即座に支払う OXXO をシミュレーションし、`payment_intent.succeeded` Webhook を数秒以内に受信します。本番環境では、この Webhook は 1 営業日後に受信します。 例: succeed_immediately@test.com | | `{any_prefix}expire_immediately@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を数秒以内に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドには、現在時刻が設定されます。 例: expire_immediately@test.com | | `{any_prefix}expire_with_delay@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を約 3 分後に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドが 3 分後に設定されます。 例: expire_with_delay@test.com | | `{any_prefix}fill_never@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を 1 営業日と 2 日後に受信する OXXO をシミュレーションします。本番環境では、この Webhook をテスト環境と同じタイミングで受信します。 例: fill_never@test.com | ## 有効期限とキャンセル OXXO バウチャーは `expires_after` UNIX タイムスタンプを過ぎると期限切れになり、顧客は有効期限が切れた OXXO バウチャーの支払いはできません。有効期限前に OXXO バウチャーをキャンセルすることはできません。 OXXO 支払い票の有効期限が切れると、PaymentIntent のステータスは `requires_payment_method` に変わります。この時点では、別の支払い方法を指定して PaymentIntent を確定するか、キャンセルすることができます。 # ダイレクト API > This is a ダイレクト API for when payment-ui is direct-api. View the full page at https://docs.stripe.com/payments/oxxo/accept-a-payment?payment-ui=direct-api. > このセクションには*レガシー* (Technology that's no longer recommended)プロダクトについてのコンテンツが含まれています。最新の導入パスについては、代わりに[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md)のガイドを使用する必要があります。Stripe はこのプロダクトを引き続きサポートしていますが、プロダクトが非推奨になった場合にはサポートが終了する可能性があります。 メキシコの Stripe ユーザーは、Payment Intents API および Payment Methods API を使用して、メキシコの顧客から OXXO での支払いを受け付けることができます。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は OXXO コンビニエンスストアで、生成された番号が記載された OXXO の取引の詳細を提供し、現金で支払います。支払いが完了すると、Stripe からお客様に通知が送られます。 ## Stripe を設定する [サーバー側] まず、Stripe アカウントが必要です。[今すぐ登録](https://dashboard.stripe.com/test/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) オブジェクトを使用して、顧客から支払いを回収するお客様の意図を示し、OXXO の支払い票の作成から支払いの完了までの状態の変化を追跡します。 サーバーで金額と`mxn`通貨を使用して PaymentIntent を作成します (OXXO は他の通貨をサポートしていません)。すでに[Payment Intents API](https://docs.stripe.com/payments/payment-intents.md)を使用した統合がある場合は、`PaymentIntent`の[決済手段タイプ](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_types)のリストに`oxxo`を追加します。 #### curl ```bash curl https://api.stripe.com/v1/payment_intents \ -u <>: \ -d "amount"=1099 \ -d "currency"="mxn" \ -d "payment_method_types[]"="oxxo" ``` ### 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 ``` ### その他の支払い方法オプション `PaymentIntent` の[支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)でオプションの `expires_after_days` パラメーターを指定して、OXXO の支払い票の有効期限が切れるまでの日数を設定できます。たとえば、月曜日に OXXO の支払い票を作成し、`expires_after_days` を 2 に設定した場合、OXXO の支払い票は、America/Mexico_City (UTC-6) 時間で水曜日の 23:59 に有効期限が切れます。`expires_after_days` パラメーターは 1 日から 7 日まで設定できます。デフォルトは 3 日です。 ## 支払い方法の詳細を収集する [クライアント側] クライアントで決済フォームを作成し、必要な請求先情報を顧客から収集します。 | フィールド | 値 | | ------- | -------------------------------- | | `name` | 顧客の氏名。姓と名はそれぞれ 2 文字以上である必要があります。 | | `email` | 顧客のメールアドレス。 | ```html
``` ## Stripe に支払いを送信する [クライアント側] 顧客が OXXO での支払いをクリックしたら、Stripe.js を使用してその支払いを Stripe に送信します。[Stripe.js](https://docs.stripe.com/payments/elements.md) は、決済フローを構築するための Stripe の基本的な JavaScript ライブラリです。 Stripe.js スクリプトを決済ページに含めるには、このスクリプトを HTML ファイルの `head` に追加します。 ```html Checkout ``` 決済ページで以下の JavaScript を使用して、Stripe.js のインスタンスを作成します。 ```javascript // Set your publishable key. Remember to switch to your live publishable key in production! // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('<>'); ``` [stripe.confirmOxxoPayment](https://docs.stripe.com/js/payment_intents/confirm_oxxo_payment) と、ステップ 2 で作成した `PaymentIntent` オブジェクトの [client secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を使用して、顧客の請求先情報を送信します。 確定されると、Stripe はモーダルを自動的に開き、顧客に OXXO の支払い票を表示します。 ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const result = await stripe.confirmOxxoPayment( '{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { billing_details: { name: document.getElementById('name').value, email: document.getElementById('email').value, }, }, }); // Stripe.js will open a modal to display the OXXO voucher to your customer // This async function finishes when the customer closes the modal if (result.error) { // Display error to your customer const errorMsg = document.getElementById('error-message'); errorMsg.innerText = result.error.message; } }); ``` > `stripe.confirmOxxoPayment` の完了には数秒かかる場合があります。この間、フォームが再送信されないように無効化し、スピナーのような待機中のインジケータを表示します。エラーが発生した場合は、それを顧客に表示し、フォームを再度有効化し、待機中のインジケータを非表示にします。 OXXO バウチャーが正常に作成されると、返された PaymentIntent の`status`プロパティの値は `requires_action` になります。[ダッシュボード](https://dashboard.stripe.com/test/payments)で、またはオブジェクトの status プロパティを調べて、PaymentIntent のステータスを確認します。OXXO バウチャーが正常に作成されなかった場合は、返された `error` を調べて原因を特定します (たとえば、無効なメールアドレスの形式など)。 ### オプション: 顧客に取引の詳細へのリンクをメールで送信する Stripe は、OXXO の取引の詳細が正常に作成されると、[payment_intent.requires_action](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.requires_action) イベントを送信します。顧客に取引の詳細のリンクをメールで送信する必要がある場合は、イベントの受信時に [PaymentIntent (支払いインテント) を取得](https://docs.stripe.com/api/payment_intents/retrieve.md)することで、リンクを取得できます。[payment_intent.next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-hosted_voucher_url) の `hosted_voucher_url` フィールドには、取引の詳細へのリンクが含まれています。 ### オプション: 取引の詳細をカスタマイズする Stripe では、[ブランディング設定](https://dashboard.stripe.com/account/branding)ページで、顧客に表示される UI をカスタマイズできます。 取引の詳細には、以下のブランド設定を適用できます。 - **アイコン**: ブランド画像と公開ビジネス名 - **アクセント**—番号コピーボタンの色として使用されます - **ブランドカラー**: 背景色として使用されます ## 支払い後のイベントを処理する [サーバー側] OXXO は[通知遅延型](https://docs.stripe.com/payments/payment-methods.md#payment-notification)の決済手段であるため、売上はすぐには利用可能になりません。*顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は決済直後に OXXO コンビニエンスストアで OXXO 店舗支払いの決済を行わない場合があります。 Stripe は、支払われた OXXO の支払いごとに、翌営業日 (メキシコの祝日を除く月曜日から金曜日) に [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) ハンドラーを構築して、これらのイベントを受信し、アクション (顧客への注文確認メールの送信、データベースへの売上の記録、配送ワークフローの開始など) を実行します。 有効期限日を過ぎると、PaymentIntent のステータスは `processing` に移行し、顧客は期限切れの OXXO 店舗支払いに対して支払いを行うことができなくなります。OXXO 店舗支払いが有効期限日の 23:59 America/Mexico_City (UTC-6) より前に支払われなかった場合、Stripe は有効期限日から 10 日以内に [payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md#event_types-payment_intent.payment_failed) イベントを送信します (ほとんどの場合、このイベントは 7 日以内に送信されます)。たとえば、OXXO 店舗支払いが 9 月 1 日に有効期限が切れる場合、このイベントは遅くとも 9 月 10 日までに送信されます。 | イベント | 説明 | 次のステップ | | -------------------------------- | -------------------------------------- | ------------------------------------ | | `payment_intent.requires_action` | OXXO の支払い票が正常に作成されました。 | 顧客が OXXO で支払うのを待ちます。 | | `payment_intent.processing` | 顧客は OXXO の支払いができなくなりました。 | 支払いの成功、または失敗を待ちます。 | | `payment_intent.succeeded` | 顧客は有効期限が切れる前に OXXO の支払い票に対する支払いを行いました。 | 顧客が購入した商品またはサービスのフルフィルメントを行います。 | | `payment_intent.payment_failed` | 顧客が有効期限までに OXXO 店舗支払いに対する支払いを行いませんでした。 | 顧客にメールまたはプッシュ通知で連絡し、別の決済手段をリクエストします。 | ### イベントを受信し、ビジネスアクションを実行する #### 手動 Stripe ダッシュボードを使用して、Stripe のすべての支払いの確認、メール領収書の送信、入金処理、失敗した支払いの再試行を実行します。 - [ダッシュボードでテスト支払いを確認する](https://dashboard.stripe.com/test/payments) #### カスタムコード Webhook ハンドラを構築してイベントをリッスンし、非同期型のカスタムの決済フローを作成します。Stripe CLI を使用して、ローカルで Webhook の組み込みのテストとデバッグを行います。 - [カスタム webhook を構築](https://docs.stripe.com/webhooks/handling-payment-events.md#build-your-own-webhook) ## 構築したシステムをテストする サンドボックスでは、[stripe.confirmOxxoPayment](https://docs.stripe.com/js/payment_intents/confirm_oxxo_payment) を呼び出すときに `payment_method.billing_details.email` を次の値に設定することで、さまざまなシナリオをテストできます。 | メールアドレス | 説明 | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `{any_prefix}@{any_domain}` | 顧客が 3 分後に支払い、約 3 分後に `payment_intent.succeeded` Webhook を受信する OXXO 支払いをシミュレーションします。本番環境では、この Webhook は 1 営業日後に受信します。 例: fulano@test.com | | `{any_prefix}succeed_immediately@{any_domain}` | 顧客が即座に支払う OXXO をシミュレーションし、`payment_intent.succeeded` Webhook を数秒以内に受信します。本番環境では、この Webhook は 1 営業日後に受信します。 例: succeed_immediately@test.com | | `{any_prefix}expire_immediately@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を数秒以内に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドには、現在時刻が設定されます。 例: expire_immediately@test.com | | `{any_prefix}expire_with_delay@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を約 3 分後に受信する OXXO をシミュレーションします。 [支払い方法オプション](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-payment_method_options-oxxo-expires_after_days)で `expires_after_days` パラメーターに設定された値に関係なく、[next_action.oxxo_display_details](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `expires_after` フィールドが 3 分後に設定されます。 例: expire_with_delay@test.com | | `{any_prefix}fill_never@{any_domain}` | 顧客が支払う前に期限切れになり、`payment_intent.payment_failed` Webhook を 1 営業日と 2 日後に受信する OXXO をシミュレーションします。本番環境では、この Webhook をテスト環境と同じタイミングで受信します。 例: fill_never@test.com | ## Optional: 顧客に OXXO 詳細を表示する [クライアント側] `confirmOxxoPayment` で OXXO の取引詳細の表示を処理するには、Stripe.js を利用することをお勧めします。ただし、顧客に手動で取引詳細を表示することもできます。 ステップ 4 で `stripe.confirmOxxoPayment` をコールする際に `handleActions: false` を指定して、顧客に OXXO の詳細を表示する次のアクションを処理するように指定できます。 ```javascript const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); const result = await stripe.confirmOxxoPayment( '{{PAYMENT_INTENT_CLIENT_SECRET}}', { payment_method: { billing_details: { name: document.getElementById('name').value, email: document.getElementById('email').value, }, }, }, {handleActions: false}, ); if (result.error) { // Display error to your customer const errorMsg = document.getElementById('error-message'); errorMsg.innerText = result.error.message; } else { // An OXXO voucher was successfully created const amount = result.paymentIntent.amount; const currency = result.paymentIntent.currency; const details = result.paymentIntent.next_action.oxxo_display_details; const number = details.number; const expires_after = details.expires_after; // Handle the next action by displaying the OXXO details to your customer // You can also use the generated hosted voucher const hosted_voucher_url = result.paymentIntent.next_action.oxxo_display_details.hosted_voucher_url; } }); ``` 少なくとも、以下を含めてください。 | 詳細 | 説明 | | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | OXXO ロゴ | OXXO ロゴを[ダウンロード](https://stripe.com/img/docs/payments/oxxo.png)してバウチャーに表示します。 oxxo | | 番号 | [next_action.oxxo_display_details.number](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-number) にある `PaymentIntent` オブジェクトの番号を見つけます。 | | 有効期限 | [next_action.oxxo_display_details.expires_after](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-next_action-oxxo_display_details-expires_after) の `PaymentIntent` で OXXO の支払い票が期限切れになる UNIX タイムスタンプを見つけます。 | | 金額 | 回収する金額。 | | 通貨 | OXXO では常にメキシコのペソが使用されます。 | | バーコード | [Code 128](https://en.wikipedia.org/wiki/Code_128) を使用して、番号からバーコードを生成します。印刷時のバーコードの幅は約 7.5 cm である必要があります。モバイルディスプレイの場合は、バーコードを拡大できることを確認してください。これにより、OXXO コンビニエンスストアのレジでバーコードをスキャンできます。[JSBarcode](https://lindell.me/JsBarcode/) などの外部ライブラリを使用できます。 | | 支払い手順 | 顧客向けの支払い手順。以下の日本語とスペイン語の翻訳をご覧ください。 | ### OXXO での支払い手順 #### 英語 OXXO での支払い手順は以下のとおりです。 1. レジ係に支払い票を渡して、バーコードを読み取ってもらう。 1. レジで現金で支払う。 1. 支払いが完了したら、記録のために支払いの領収書を保管する。 1. ご不明な点や説明については、事業者にお問い合わせください。 #### HTML ```html
MX
Expires
Instructions to pay your OXXO:
  1. Give the voucher to the cashier to scan the barcode.

  2. Provide cash payment to the cashier.

  3. After the payment is complete, keep the receipt of your payment for your records.

  4. For any questions or clarification, please contact the merchant.

``` #### スペイン語 Instrucciones de pago en OXXO: 1. Entregue el código al cajero en cualquier OXXO para que lo escanee. 1. Proporcione el pago en efectivo al cajero. 1. Una vez completado el pago, guarde el recibo de su pago para sus archivos. 1. Para cualquier duda o aclaración, por favor contacte al comerciante. #### HTML ```html
MX
Expira el
Instrucciones de pago en OXXO:
  1. Entregue el código al cajero en cualquier OXXO para que lo escanee.

  2. Proporcione el pago en efectivo al cajero.

  3. Una vez completado el pago, guarde el recibo de su pago para sus archivos.

  4. Para cualquier duda o aclaración, por favor contacte al comerciante.

``` *顧客* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments)は通常、OXXO の支払い票を印刷して OXXO コンビニエンスストアに持参します。お客様は分かりやすい印刷ボタンを提供したり、OXXO 支払い票を顧客にメールで送信したりできます。OXXO 支払い票を自身で印刷して、バーコードのサイズ (幅は約 7.5 cm の必要があります) を確認してください。 ## Optional: 決済手順メールを送信する ダッシュボードの[メール設定](https://dashboard.stripe.com/settings/emails)ページで OXXO 決済の手順メールを有効にできます。有効にすると、Stripe は、PaymentIntent の確定時に決済手順メールを送信します。メールには、OXXO 番号と Stripe の店舗支払いページへのリンクが含まれます。 > テスト環境では、手順メールは Stripe アカウントに関連付けられたメールアドレスにのみ送信されます。 ## 有効期限とキャンセル OXXO バウチャーは `expires_after` UNIX タイムスタンプを過ぎると期限切れになり、顧客は有効期限が切れた OXXO バウチャーの支払いはできません。有効期限前に OXXO バウチャーをキャンセルすることはできません。 OXXO 支払い票の有効期限が切れると、PaymentIntent のステータスは `requires_payment_method` に変わります。この時点では、別の支払い方法を指定して PaymentIntent を確定するか、キャンセルすることができます。