Skip to content

Instantly share code, notes, and snippets.

@suhailgupta03
Created December 20, 2023 15:24
Show Gist options
  • Save suhailgupta03/4c81b553eec57950c28fcbe751238474 to your computer and use it in GitHub Desktop.
Save suhailgupta03/4c81b553eec57950c28fcbe751238474 to your computer and use it in GitHub Desktop.
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY');
async function handlePaymentMethodRequired(paymentIntentId) {
try {
const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId);
if (paymentIntent.status === 'requires_payment_method') {
// Prompt the user to provide a new payment method
// For example, collect new payment details from the user and create a PaymentMethod
// Assuming you have a new PaymentMethod ID from the frontend
const newPaymentMethodId = 'pm_newPaymentMethodId'; // Replace with actual PaymentMethod ID
// Update the PaymentIntent with the new payment method
await stripe.paymentIntents.update(paymentIntentId, {
payment_method: newPaymentMethodId,
});
// Confirm the PaymentIntent with the new payment method
const confirmedPaymentIntent = await stripe.paymentIntents.confirm(paymentIntentId);
// Check if confirmation was successful
if (confirmedPaymentIntent.status === 'succeeded') {
// Payment was successful
return true;
} else {
// Payment confirmation failed
return false;
}
} else {
// Handle other statuses accordingly
return false;
}
} catch (error) {
// Handle error
console.error(error);
return false;
}
}
// Usage example
const paymentIntentId = 'pi_XXXXXXXXXXXX'; // Replace with your actual PaymentIntent ID
handlePaymentMethodRequired(paymentIntentId).then(isSuccessful => {
console.log('Payment successful after updating payment method:', isSuccessful);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment