# 韓国で Samsung Pay による支払いを受け付ける

# ダイレクト API


[Samsung Pay](https://www.samsung.com/sec/apps/samsung-wallet/) を使用すると、韓国在住の顧客はこの地域固有の決済手段を使用して支払えるようになります。

顧客は支払いを行うと、現地の提携決済代行業者にリダイレクトされ、認証と支払いの承認を求められます。顧客が支払いを承認すると、Stripe は顧客をお客様のサイトにリダイレクトします。

[Payment Intents API](https://docs.stripe.com/payments/payment-intents.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'
```

## PaymentIntent を作成する [サーバー側]

[PaymentIntent](https://docs.stripe.com/api/payment_intents/object.md) は、顧客から支払いを回収する意図を表し、支払いプロセスを追跡するオブジェクトです。サーバー上で金額と通貨を指定して `PaymentIntent` を作成します。ダッシュボードで[決済手段を有効にします](https://dashboard.stripe.com/settings/payment_methods)。[動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe により対象となる決済手段が顧客に自動的に表示されます。

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=10000 \
  -d currency=krw \
  -d "payment_method_data[type]=samsung_pay"
```

### 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
<form id="payment-form" data-secret="<%= @intent.client_secret %>">
  <button id="submit">Submit</button>
</form>
```

```ruby
get '/checkout' do
  @intent = # ... Fetch or create the PaymentIntent
  erb :checkout
end
```

## 顧客が利用規約を理解していることを確認する [クライアント側]

Stripe の決済代行業者は、顧客が代行業者の身元を認識し、その利用規約を理解していることを求めています。そのため、チェックアウトページには以下の文言とリンクを必ず含める必要があります。

> 送信すると、次の手順を完了するためにリダイレクトされます。この取引は、NICEPAY の[利用規約](https://start.nicepay.co.kr/homepage/terms/bill.do)に従って、NICEPAY を通じて処理されます。

## 現地の代行業者にリダイレクトする [クライアント側]

顧客が Samsung Pay での支払いをクリックしたときに、Stripe.js を使用してその支払いを Stripe に送信します。[Stripe.js](https://docs.stripe.com/payments/elements.md) は、決済フローを構築するための基本的な JavaScript ライブラリです。このライブラリにより、以下で説明するリダイレクトなどの複雑な処理が自動的に行われ、他の決済手段にも対応できるように実装を拡張できます。Stripe.js スクリプトを決済ページに含めるには、HTML ファイルの `head` にこのスクリプトを追加します。

```html
<head>
  <title>Checkout</title>
  <script src="https://js.stripe.com/dahlia/stripe.js"></script>
</head>
```

決済ページで以下の JavaScript を使用して、Stripe.js のインスタンスを作成します。

```javascript
// Set your publishable key. Remember to change this to your live publishable key in production!
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = Stripe('<<YOUR_PUBLISHABLE_KEY>>');
```

`PaymentIntent` の [Client Secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret) を使用して `stripe.confirmPayment` を呼び出し、地域の決済代行業者の決済フローページへのリダイレクトを処理します。このページで、顧客はカード発行会社を選択し、支払いを承認します。`return_url` を追加して、決済完了後に顧客をリダイレクトする場所を指定します。

```javascript
const form = document.getElementById('payment-form');

form.addEventListener('submit', async function(event) {
  event.preventDefault();

  // Set the clientSecret of the PaymentIntent
  const { error } = await stripe.confirmPayment({
    clientSecret: clientSecret,
    confirmParams: {
      payment_method_data: {
        type: 'samsung_pay',
      },
      // Return URL where the customer should be redirected after the authorization
      return_url: `${window.location.href}`,
    },
  });

  if (error) {
    // Inform the customer that there was an error.
    const errorElement = document.getElementById('error-message');
    errorElement.textContent = result.error.message;
  }
});
```

`return_url` は、支払いの結果を表示する、貴社のウェブサイトのページに相当します。`PaymentIntent` の[ステータスを確認](https://docs.stripe.com/payments/payment-intents/verifying-status.md#checking-status)して、何を表示するべきか判断できます。ステータスを確認するために、Stripe がリダイレクトする `return_url` には次の URL クエリパラメーターが含まれています。また、独自のクエリパラメーターを `return_url` に追加することもできます。設定したパラメーターは、リダイレクトプロセス全体にわたって保持されます。

| パラメータ                          | 説明                                                                                                                                  |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `payment_intent`               | `PaymentIntent` の一意の ID。                                                                                                            |
| `payment_intent_client_secret` | `PaymentIntent` オブジェクトの [Client Secret](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-client_secret)。 |

## Test integration with Samsung Pay

リダイレクトページを表示して、テスト API キーを使用した Samsung Pay の実装をテストします。リダイレクトページで決済を認証することで、決済の成功をテストできます。PaymentIntent は `requires_action` から `succeeded` に移行します。認証の失敗をテストするには、テスト API キーを使用してリダイレクトページを表示します。リダイレクトページで **テスト決済を失敗** をクリックします。PaymentIntent は `requires_action` から `requires_payment_method` に移行します。

## 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/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)などの一般的なビジネスイベントを処理します。

