目次
前提
本記事は以下の記事の続きです。
まだ、ご覧になっていない方は、以下の記事からご確認をお願いいたします。
Node.jsでStripeのカスタマー(顧客)の支払い方法の設定方法(クライアントシークレット取得) stripe.setupIntents.create【1/2】
公開可能キーを取得
以下のURLにアクセスし、「公開可能キー」を取得する。
https://dashboard.stripe.com/test/apikeys
HTML/JavaScriptのプロジェクト構成
project ┗ sample ┣ index.html ┣ index.js ┗ finish ┗ index.html
ソースコードの用意
project/sample/index.html
ソースコードの全量は以下です。
重要なのは以下のポイントです。
- StripeのCDNを読み込む必要がある。
「<script src="https://js.stripe.com/v3/"></script>
」 - jQueryのCDNを読み込む必要がある。(ajaxを使用する用途ですが、必須ではありません)
「<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
」 - 「form」の中にhtmlが追加されていくため、idなどはJavaScriptと紐づいている必要がある。
※書き換える場合は、注意してください。 - 「
index.js
」の読み込みは「body
」の閉じタグの直前である必要があります。
※headなどではダメです。(カード入力フォームが読み込まれません)
<html lang="ja"> <head> <meta charset="UTF-8" /> <script src="https://js.stripe.com/v3/"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <form id="payment-form"> <div id="payment-element"></div> <div id="error-message"></div> <button id="submit">登録する</button> </form> <script src="./index.js"></script> </body> </html>
project/sample/index.js
ソースコードの全量は以下です。
重要なのは以下のポイントです。
- 以下のAPI呼び出しは、前の記事の、クライアントシークレット取得のAPIを実行してください。
https://example.com/xxxxx/yyyyy
- 「
pk_test_XXXXXXXXXX
」は「公開可能キーを取得
」で取得した内容に置き換えてください。
$.ajax({ type: "GET", url: "https://example.com/xxxxx/yyyyy", data: {}, dataType: "json", }).done((data) => { // APIから取得したクライアントシークレット const client_secret = data.client_secret; const stripe = Stripe("pk_test_XXXXXXXXXX"); const elements = stripe.elements({ clientSecret: client_secret, appearance: { theme: "stripe", }, }); const paymentElement = elements.create("payment"); paymentElement.mount("#payment-element"); const form = document.getElementById("payment-form"); form.addEventListener("submit", async (event) => { event.preventDefault(); const { error } = await stripe.confirmSetup({ elements, confirmParams: { return_url: `${location.protocol}//${location.host}/sample/finish/`, }, }); if (error) { const messageContainer = document.querySelector("#error-message"); messageContainer.textContent = error.message; } }); });
project/sample/finish/index.html
ソースコードの全量は以下です。
特に注意する必要はありません。
適当なhtmlを用意してください。
<html lang="ja"> <head> <meta charset="UTF-8" /> </head> <body> クレジットカード登録完了 </body> </html>
アクセス確認
VSCodeなどでローカルサーバーを起動して、「http://localhost:3000/sample/
」にアクセスします。
画面にて、以下の操作を行います。
- カード番号に「4242424242424242」を入力します。
- 有効期限には有効な日付(12/34)を入力します。
- CVCには適当な数字を入力します。
- 登録ボタンを押下します。
画面遷移後、URLバーに以下のようなURLが入っています。
「redirect_status
」の部分が「succeeded
」なら、登録成功です。
http://localhost:3000/sample/finish/index.html?setup_intent=seti_XXXX&setup_intent_client_secret=seti_XXXX_secret_YYYY&redirect_status=succeeded
カード登録情報確認
以下のサイトにて、カード登録したカスタマーを選択すると、「支払い方法」にカード情報の登録が確認できます。
https://dashboard.stripe.com/test/customers
テストカード
Stripeで使用できるテストカードは以下に一覧が用意されています。
状況に合わせてテストカードを登録してください。