📑

StripeのInvoice支払いの導入の流れ

に公開

StripeのInvoice支払いの導入

流れ

  • 開発環境

    • Stripe dashboard: Test modeに設定する
    • Publishable_keySecret_keyを設定、取得する
  • 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: '',
                  };
              }
          }
          
  • Invoiceの作成

    • クラインエントのリクエストよりInvoiceを作成して、Invoiceのpayment_intentからclientSecretを取得する
      finalizedInvoice.payment_intent?.client_secret
  • 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.confirmPaymentresultから、支払いの結果を知る。完了の場合は、サーバに通知を送って、サーバがStripeのwebhookからの支払い完了の情報を確認する後、次の処理に進みます。
Bizlink Developers Blog

Discussion