StripeのCheckout経由の決済をキャンセルしたときのWebhookをハンドリングする
public.icon
背景
Stripeの管理画面で決済を返金対応などを行った場合、Firestore(DB)上のデータとデータがズレるので同期したいと思った
結論
Sessionとは別にPaymentIntentというものが発行され、その中のlatest_chargeの中にchargeIdが含まれている このchargeIdを決済完了時のwebhookcheckout.session.completedでdbに保存しておく
Stripeで返金を行った際charge.refundedがwebhookで飛んでくる
code:index.ts
const handlePayment = async (session: Stripe.Checkout.Session) => {
// pi_xxxxxxxxxxxxx
const sessionPaymentIntent = session.payment_intent;
if (sessionPaymentIntent) {
const paymentIntent = await stripeClient.getIntents(sessionPaymentIntent as string);
console.log({ paymentIntent });
// ch_yyyyyyyyyyyyyyy
const chargeId = paymentIntent.latest_charge as string;
}
}
code:index.ts
export const chargeRefunded = async (charge: Stripe.Charge): Promise<void> => {
// ch_yyyyyyyyyyyyyyy
const chargeId = charge.id;
// このidをdbと比較して返金したことを反映してあげる
}
参考文献
貴社で構築済みの Stripe システムが Webhook イベントを処理するように設定されていることを確認してください。また、返金処理の状況を顧客や社内チームに通知するための内部ロジックを構築する必要もあります。少なくとも、charge.refunded イベントをリッスンすることをお勧めします。