#jodas.

1 messages · Page 1 of 1 (latest)

turbid streamBOT
last shuttle
#

Ill send the code

rain bridge
#

Hello, can you tell me more about the issues that you are seeing here?

last shuttle
#

I created a checkout session in the payment creation and want to reconstrcut the payment session in my webhook. But I only have access to the payment intent...

rain bridge
#

Can you tell me more about what you mean by "reconstruct the payment session"? Are you looking for the items in the Checkout Session? Or something else?

last shuttle
#

Okay I changed some stuff, I start over again:
So this is my webhook function right here. I try to retreive the checkout session in the beginning at this line:

#
const session = await stripe.checkout.sessions.retrieve(event.data.object.id);```
But  the session in the next line doesnt get logged at ALL. Literally nothing happens... 

```js
const receiveStripeWebhook = async (req: any, res: any) => {
  const sig = req.headers['stripe-signature'];

  let event;

  try {
    event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
    console.log(event.type);
    if (event.type === 'checkout.session.completed') {
      console.log(event.data.object.id);
      const session = await stripe.checkout.sessions.retrieve(event.data.object.id);
      console.log(session);
      const user = await UserModel.findOne({ email: session.customer_email });
      if (!user) {
        throw new Error('User not found');
      }
      const payment = user.payments.find((payment: any) => payment.paymentId === session.id);
      if (!payment) {
        throw new Error('Payment not found');
      }
      payment.status = 'paid';
      user.credits += payment.credits;

      if (user.referredBy) {
        const referrer = await UserModel.findOne({ referralId: user.referredBy });
        if (!referrer) {
          user.referredBy = undefined;
        } else {
          referrer.referredAccounts.push(user.email);
          user.referredBy = undefined;
          await referrer.save();
        }
      }

      if (session.metadata.coupon) {
        const coupon = await CouponModel.findOne({ code: session.metadata.coupon });
        if (coupon) {
          coupon.usedBy!.push(user._id.toString());
          coupon.paymentIds!.push(payment.paymentId);
          await coupon.save();
        }
      }

      await user.save();
      sendPaymentReceivedMail(user, payment.paymentId, payment.price);
    }
    res.status(200).send('Webhook received succesfully');
  } catch (err) {
    res.status(400).send(`Webhook Error: ${err}`);
    return;
  }
};
#

Once again how I create the session:

router.post('/create', async (req, res) => {
  const { userId, amount, coupon, redirect } = req.body;
  const user = await UserModel.findOne({ _id: userId });

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  const checkedCoupon = coupon ? await checkCoupon(userId, coupon) : false;
  const isReferred = user.referredBy ? true : false;

  const scanCreditPrice = Number(process.env.SCAN_CREDIT_PRICE);
  const referralDiscount = isReferred ? scanCreditPrice * amount * 0.5 : 0;
  const couponDiscount = checkedCoupon
    ? (amount * scanCreditPrice - (isReferred ? referralDiscount : 0)) * checkedCoupon.discount
    : 0;

  const price = amount * scanCreditPrice - referralDiscount - couponDiscount;

  const session = await stripe.checkout.sessions.create({
    customer_email: user.email,
    submit_type: 'pay',
    line_items: [
      {
        price: isReferred ? referredPrice : normalPrice,
        quantity: amount,
      },
    ],
    mode: 'payment',
    discounts: checkedCoupon
      ? [
          {
            coupon: checkedCoupon.code,
          },
        ]
      : [],
    metadata: checkedCoupon ? { coupon: checkedCoupon.code } : {},
    success_url: redirect
      ? `${process.env.NEXT_PUBLIC_WEBSITE_DOMAIN}/audit/results?projectID=${redirect}&success=true`
      : `${process.env.NEXT_PUBLIC_WEBSITE_DOMAIN}/settings?success=true`,
    cancel_url: redirect
      ? `${process.env.NEXT_PUBLIC_WEBSITE_DOMAIN}/audit/results?projectID=${redirect}&success=false`
      : `${process.env.NEXT_PUBLIC_WEBSITE_DOMAIN}/settings?success=false`,
  });

  const payment = {
    paymentId: session.id,
    credits: amount,
    price: price,
    date: new Date(),
    status: 'created',
    method: 'stripe',
  };

  user.payments.push(payment);
  await user.save();

  res.status(200).json(session.url);
});
turbid streamBOT
last shuttle
#

Uuuuhm, yeah I´m sorry. I thought I double checked it but the key in my env was wrong 😅