#fabulousray_code

1 messages ยท Page 1 of 1 (latest)

jagged kilnBOT
#

๐Ÿ‘‹ Welcome to your new thread!

โฒ๏ธ We'll be here soon! Typically we respond in a few minutes, but sometimes we might take a bit longer if the server is busy or if you have a particularly tricky question.

โฑ๏ธ We close idle threads, which makes them read-only. Once a thread is closed it won't be reopened, but you can always start a new thread if you have another question.

๐Ÿ”— This thread will always be available, even after it's closed. You can find it again using Discord's search, or you can save this link: https://discord.com/channels/841573134531821608/1276497600563908659

๐Ÿ“ Have more to share? Add more details, code, screenshots, videos, etc. below.

shut kettleBOT
#

Below are links to other discussions we've had with you in the past week in case you want to review that information. If your question is related to one of these previous discussions, please provide a comprehensive summary of the current state and what you need help with now. We help many users simultaneously, so a summary allows us to resolve your issue as soon as possible.

vagrant mica
#

hello!

#

const express = require('express');
const { createCheckoutSession } = require('../services/stripeService');
const requireJwtAuth = require('~/server/middleware/requireJwtAuth');
const router = express.Router();

router.use(requireJwtAuth);

// Define the route at the root of the router
router.post('/', async (req, res) => {
try {
const session = await createCheckoutSession(req.body);
res.status(200).json({ sessionId: session.url });
} catch (error) {
console.error('Error creating checkout session:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

module.exports = router;
checkroutes.js

#

stripeservice.js
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

async function createCheckoutSession({ isAnnual, stripeCustomerId }) {
// Use the stripeCustomerId and isAnnual to create a Stripe checkout session
const session = await stripe.checkout.sessions.create({
customer: stripeCustomerId,
payment_method_types: ['card'],
line_items: [{
price: isAnnual ? 'price_annual_id' : 'price_monthly_id',
quantity: 1,
}],
mode: 'subscription',
success_url: ${process.env.DOMAIN_CLIENT}/success?session_id={CHECKOUT_SESSION_ID},
cancel_url: ${process.env.DOMAIN_CLIENT}/cancel,
});

return session;
}
module.exports = { createCheckoutSession };

#

const checkoutRoutes = require('./routes/checkoutRoutes');

app.use('/create-checkout-session', checkoutRoutes);
index.js app*

sage tree
#

Hi, let me help you with this.

#

This doesn't seem like an issue related to Stripe.

vagrant mica
#

it isnt?

sage tree
#

Your own server gives you a 404.

vagrant mica
#

oooh

#

sorry i dont have much experience with code

#

im trying to use the low code integration to provide my customers subscriptions

#

based on their customer ids

#

is there any other way for my users to pay to their respective customer ids referenced to their email that stripe provides?

sage tree
#

It's a good approach, you just need to fix your app routing.

sage tree
vagrant mica
#

hhm

#

ill try and see if that works

#

um sorry directly as in the server?

sage tree
#

Oh, I see the issue.

vagrant mica
#

i put it directly in the server.js

#

async function createCheckoutSession({ isAnnual, stripeCustomerId }) {
// Use the stripeCustomerId and isAnnual to create a Stripe checkout session
const session = await stripe.checkout.sessions.create({
customer: stripeCustomerId,
payment_method_types: ['card'],
line_items: [{
price: isAnnual ? 'price_annual_id' : 'price_monthly_id',
quantity: 1,
}],
mode: 'subscription',
success_url: ${process.env.DOMAIN_CLIENT}/success?session_id={CHECKOUT_SESSION_ID},
cancel_url: ${process.env.DOMAIN_CLIENT}/cancel,
});

return session;

}
app.post('/create-checkout-session', async (req, res) => {
try {
const session = await createCheckoutSession(req.body);
res.status(200).json({ url: session.url });
} catch (error) {
console.log('Error creating checkout session:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

sage tree
#

This should work too

sage tree
vagrant mica
vagrant mica
#

wait but my code snippet in the server should use the router right?
const checkoutRoutes = require('./routes/checkoutRoutes');

app.use('/create-checkout-session', checkoutRoutes);
index.js app*

sage tree
#

Ok, it's not that. But my initial suspicion still holds. I don't think react nests the router URLs.

vagrant mica
#

i dont understand still

sage tree
#

Are you able to hit /api/create-portal-session?

vagrant mica
#

i go on network tab

#

this shows up

vagrant mica
#

my stripe webhook works though in this server

sage tree
#

I am investigating the issue by trying to understand if only this endpoint is problematic

vagrant mica
#

okay

sage tree
#

Maybe it's because it's missing the /api/ prefix

vagrant mica
#

okay ill try that

sage tree
vagrant mica
#

okay i see

#

it still doesn't work with /api/prefix

sage tree
#

Can you reach /api/create-portal-session?

vagrant mica
#

$headers = @{"Content-Type" = "application/json"}

$body = '{"customerId": "cus_ABC123"}'
Invoke-WebRequest -Uri http://localhost:3080/api/create-portal-session -Method POST -Headers $headers -Body $body

c

StatusCode : 200
yup just tried

#

200 OK

sage tree
#

Are you sure you're running the updated code?

vagrant mica
#

yup rebuilt backend still doesnt work

sage tree
#

For a test, could you create the checkout session in the /api/create-portal-session endpoint?

#

And see if you get the Checkout Session response on the frontend.

jagged kilnBOT
sage tree
#

Also, when you fix that, I would recommend redirecting the customer to the session.url immediately, instead of returning it to the frontend.

vagrant mica
#

okay lemme try that

#

okay its getting somewhere

#

it reloads the page...

#

app.post('/api/create-checkout-session', async (req, res) => {
try {
const { isAnnual, stripeCustomerId } = req.body;
// Create a Stripe Checkout session
const session = await stripe.checkout.sessions.create({
customer: stripeCustomerId,
payment_method_types: ['card'],
line_items: [{
price: isAnnual ? 'price_annual_id' : 'price_monthly_id', // Replace with your actual price IDs
quantity: 1,
}],
mode: 'subscription',
success_url: ${process.env.DOMAIN_CLIENT}/success?session_id={CHECKOUT_SESSION_ID},
cancel_url: ${process.env.DOMAIN_CLIENT}/cancel,
});
res.status(200).json({ url: session.url });
} catch (error) {
console.error('Error creating Stripe checkout session:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
code snippet changed in index.js (server)

#

try {
const response = await axios.post('/api/create-checkout-session', {
isAnnual,
stripeCustomerId: user.stripeCustomerId, // Pass the user stripeCustomerId to the backend
});
window.location.href = response.data.url; // Redirect to the Stripe
code snipper changed in upgrade.tsx(client)

#

clicking on my button reloads the page as well

#

i think now there is a undefined 404

polar tendon
#

hi! I'm taking over this thread.

vagrant mica
#

oh hello!

polar tendon
#

i think now there is a undefined 404
where's the 404 exactly? when you try to call the /api/create-checkout-session url?

vagrant mica
#

before your collegaue told me to do some tests it actually had 404s when i called create-checkout-session

polar tendon
#

so is this issue fixed, or you still have that 404?

vagrant mica
#

nope now it reloads the page and nothing happens

polar tendon
#

and do you get some logs on your backend server to check if /api/create-checkout-session was run?

vagrant mica
#

uhh no i dont

#

i put someconsole.log('Request received at /api/create-checkout-session');
console.log('Request body:', req.body);

#

and no logs come out

polar tendon
#

next steps would be adding many logs on both the frontend and te backend, to understand which part of your code are executed or not

vagrant mica
#

okay

#

um

#

it seems like console.log is not outputting anything

#

wait i got something

#

upgrade.tsx:49

   POST http://localhost:3090/api/create-checkout-session 500 (Internal Server Error i got this
polar tendon
#

it means your backend code running on /api/create-checkout-session is returning an error. so check your backend logs to see what the error is.

vagrant mica
#

okay let me see

#

now i get this

#

index.js
app.post('/api/create-checkout-session', async (req, res) => {
try {
console.log('Request received at /api/create-checkout-session');
const { isAnnual, stripeCustomerId } = req.body;
// Create a Stripe Checkout session
const session = await stripe.checkout.sessions.create({
customer: stripeCustomerId,
payment_method_types: ['card'],
line_items: [{
price: isAnnual ? 'annual' : 'monthly', // Replace with your actual price IDs
quantity: 1,
}],
mode: 'subscription',
success_url: ${process.env.DOMAIN_CLIENT}/success?session_id={CHECKOUT_SESSION_ID},
cancel_url: ${process.env.DOMAIN_CLIENT}/cancel,
});
res.redirect(303, session.url);
} catch (error) {
console.error('Error creating Stripe checkout session:', error);
res.status(500).json({ error: 'Internal server error' });
}
});

polar tendon
#

you cannot send a post request and a res.redirect() at the same time, that's the issue.

#

you should either:

  • Return the checkout.url from your backend, and then on the frontend update the window.location
  • Or do a <form action="xxx" method="POST"> on the frontend and the backend can do a redirect
vagrant mica
#

okay ill one of them

#

it should work but would my frontend be of best practice?
try {
const response = await axios.post('/api/create-checkout-session', {
isAnnual,
stripeCustomerId: user.stripeCustomerId, // Pass the user stripeCustomerId to the backend

  });
  window.location.href = response.data.url; // Redirect to the S

...
<form action={formActionUrl} method="POST">
<input type="hidden" name="isAnnual" value={isAnnual.toString()} />
<input type="hidden" name="stripeCustomerId" value={user.stripeCustomerId} />
<button
type="submit"
className="mt-6 block w-full rounded-lg bg-yellow-500 py-2 text-center text-black"
>
Start using Pro
</button>

#

it seems like there is no webhook event sent is that suppose to be a problem?

polar tendon
#

it should work but would my frontend be of best practice?
first: does it work or not?

#

it seems like there is no webhook event sent is that suppose to be a problem?
when the payment is completed, you should receive a checkout.session.completed event, assuming you setup a webhook endpoint listening to that event.

vagrant mica
#

yes it does work

#

does payment not trigger invoice.paid?

#

i have a webhook endpoint listening to invoice.paid

polar tendon
#

does payment not trigger invoice.paid?
it depends. for example if you are creating a Subscription with your Checkout Session, then an Invoice will be created and paid, so yes you will receive invoice.paid. but for one time payments, there would be no invoice created.

#

in general for Checkout Session we recommend listening to checkout.session.completed

vagrant mica
#

okay i see