#acffaria91-subcriptions with checkout
1 messages ยท Page 1 of 1 (latest)
๐ happy to help
could you please provide some ids so I could take a look? Checkout Session id, Subscription Ids etc.
Hi,
Here's the subscription id = sub_1KxRo9BOIcgIIZ17Gke0Nw5O
I don't have the checkout one. Is that enough?
I will take a look
thank you!
are you using webhooks by any chance?
yes, but I'm not sure I'm using them properly. I'm wuite new to stripe and somethings are now 100% clear to me
Sorry! Yes
app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = stripe.webhooks.constructEvent(req.body, req.header('stripe-signature'), endpointSecret);
} catch (err) {
console.log(err);
return res.sendStatus(400)
}
if (event.type === 'payment_intent.succeeded') {
const data = event.data.object;
const paymentMethod = event.data.object.payment_method;
// const customer = event.data.object.customer;
// attach payment to customer
const attachPaymentToCustomer = await stripe.paymentMethods.attach(
paymentMethod, // <-- your payment method ID collected via Stripe.js
{ customer: customer.id } // <-- your customer id from the request body
);
//create subscription
const subscription = await stripe.subscriptions.create({
customer: customer.id,
items: [{ plan: 'plan_DznNb3tPEEI0cj' }],
default_payment_method: paymentMethod,
expand: ['latest_invoice.payment_intent']
});
await User.updateOne(
{_id: ObjectId(userId) },
{$set: { "stripeCustomer": customer}},
);
await User.updateOne(
{_id: ObjectId(userId) },
{$set: { "stripeCustomer.subscriptions": subscription}},
);
counter++;
}
res.sendStatus(200);
});
when you're using checkout you don't need to create the subscription and attach the payment method to your customer
Checkout will do all of this for you
when I didn't have that I would always get an error "This customer has no attached payment source or default payment method."
my checkout code, so you can see
I also had to put the webhook before this because of the rawBody issues (don't know if this has any impact)
could you please give me a moment, I will try to answer you with as much details you need
of course, thank you!
could you please try to comment the code you added in the webhook and create a Checkout Session on a new customer?
if you still get an error could you please provide the id for that request?
sorry for the delay (I had to comute meanwhile). I'll do it now
you mean comment the payment method, attachment and subscription creation right?
yes, or just remove it really. You don't need it, since using the CheckoutSession already created the customer and subscription, you don't have to do it again when handling the webhook.
Ok, it worked! Now I have to retrieve the object to upload to the database right?
I would say yes; https://stripe.com/docs/payments/checkout/fulfill-orders covers the approach for handing the checkout.session.completed webhook event