handle-stripe-payment-action.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { FetchError, postJSON } from '@/infrastructure/fetch-json'
  2. import { loadStripe } from '@stripe/stripe-js/pure'
  3. export default async function handleStripePaymentAction(
  4. error: FetchError
  5. ): Promise<{ handled: boolean }> {
  6. const clientSecret = error?.data?.clientSecret
  7. const publicKey = error?.data?.publicKey
  8. if (clientSecret && publicKey) {
  9. const stripe = await loadStripe(publicKey)
  10. if (stripe) {
  11. const manualConfirmationFlow =
  12. await stripe.confirmCardPayment(clientSecret)
  13. if (manualConfirmationFlow.error) {
  14. const paymentIntentId = manualConfirmationFlow.error.payment_intent?.id
  15. try {
  16. await postJSON(
  17. `/user/subscription/void-change?payment_intent_id=${paymentIntentId}`
  18. )
  19. } catch (error) {
  20. // do nothing
  21. }
  22. return { handled: false }
  23. } else {
  24. try {
  25. await postJSON(`/user/subscription/sync`)
  26. } catch (error) {
  27. // if the sync fails, there may be stale data until the webhook is
  28. // processed but we can't do any special handling for that in here
  29. }
  30. return { handled: true }
  31. }
  32. }
  33. }
  34. return { handled: false }
  35. }