📑
StripeのInvoice支払いの導入の流れ
StripeのInvoice支払いの導入
流れ
-
開発環境
- Stripe dashboard:
Test mode
に設定する -
Publishable_key
とSecret_key
を設定、取得する
- Stripe dashboard:
-
Stripe CLI
- ローカルテスト用のWebhookを設定する
- Stripe CLIのインストール、設定-
https://docs.stripe.com/stripe-cli
brew install stripe/stripe-cli/stripe
stripe login --api-key Secret_key
- テスト環境のWebhook APIを作る、例:
localhost:8080/webhook_api
- AWS Lambda / Web Server
- テスト環境のStripe支払いのイベントをWebhookに繋がる
-
stripe listen --forward-to localhost:8080/webhook_api
- 実行する後、一つのsigned secret :
whsec_XXXXXXXXXXXXXXXXXXX
が出てくる - Webhook APIの中に、そのsigned secretを使って、Stripe側の発信のidentityを認証する
const endpointSecret = Env.ENDPOINT_SIGNING_SECRET; // check if the event is from Stripe if (endpointSecret) { try { event = stripe.webhooks.constructEvent(requestBody || '', requestSignature || '', endpointSecret); } catch (err) { console.warn(`Webhook signature verification failed.`, (err as { message?: string })?.message); return { statusCode: 400, body: '', }; } }
- 実行する後、一つのsigned secret :
-
-
https://docs.stripe.com/stripe-cli
- ローカルテスト用のWebhookを設定する
-
Invoiceの作成
- クラインエントのリクエストよりInvoiceを作成して、Invoiceのpayment_intentからclientSecretを取得する
finalizedInvoice.payment_intent?.client_secret
- クラインエントのリクエストよりInvoiceを作成して、Invoiceのpayment_intentからclientSecretを取得する
-
Stripe支払いのReact component (Payment Element)の導入
- https://docs.stripe.com/payments/payment-element
- https://docs.stripe.com/invoicing/integration?method=elements&element=payment#accept-invoice-payment (Stripe Elements)
- Payment Elementを導入して、ユーザがクレジットカードなどの情報を入力されて、入力される情報をStripe側に送って、クラインエント側が支払いの結果がstripe(clientSecretがこの前のInvoiceの作成のclientSecret、STRIPE_PUBLIC_KEYがStripe dashboardで設定されるPublishable_key)
PaymentElement
const stripePromise = loadStripe(STRIPE_PUBLIC_KEY); <Elements stripe={stripePromise} options={{ clientSecret: clientSecret }}> <PaymentForm /> <Elements>
PaymentForm
<form onSubmit={handleSubmit}> <div> Your content... </div> <PaymentElement /> <button> Submit Button </button> </form>
-
handleSubmit
の中にstripe.confirmPayment
で支払い情報を確認する
const result = await stripe.confirmPayment({ elements, redirect: "if_required", });
-
Stripe支払いのバッグエント処理
- サーバ:Stripeのwebhookから、支払い完了の情報を送られる。
- クラインエンド側が
stripe.confirmPayment
のresult
から、支払いの結果を知る。完了の場合は、サーバに通知を送って、サーバがStripeのwebhookからの支払い完了の情報を確認する後、次の処理に進みます。
Discussion