#fabulousray_code
1 messages ยท Page 1 of 1 (latest)
๐ 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.
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.
- fabulousray_webhooks, 20 hours ago, 34 messages
- fabulousray_code, 1 day ago, 50 messages
- fabulousray_webhooks, 3 days ago, 12 messages
hello!
upgrade.tsx
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*
it isnt?
Your own server gives you a 404.
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?
It's a good approach, you just need to fix your app routing.
I am not sure if express route config nesting works like this. Try registering the handler with router.post('/create-checkout-session', ...) directly and just listening to that router.
Oh, I see the issue.
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' });
}
});
You don't seem to use this router anywhere.
This should work too
But note this about the previous approach โ๏ธ
this still leads to 404 though
hmmm
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*
index.js (server)
Ok, it's not that. But my initial suspicion still holds. I don't think react nests the router URLs.
i dont understand still
Are you able to hit /api/create-portal-session?
sorry i dont understand why create-portal-session?
my stripe webhook works though in this server
I am investigating the issue by trying to understand if only this endpoint is problematic
okay
Maybe it's because it's missing the /api/ prefix
okay ill try that
I don't know why, just trying ideas, since you have a lot of configuration in that file. Multiple factors might be at play.
Can you reach /api/create-portal-session?
$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
Are you sure you're running the updated code?
yup rebuilt backend still doesnt work
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.
Also, when you fix that, I would recommend redirecting the customer to the session.url immediately, instead of returning it to the frontend.
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
hi! I'm taking over this thread.
oh hello!
i think now there is a undefined 404
where's the 404 exactly? when you try to call the/api/create-checkout-sessionurl?
before your collegaue told me to do some tests it actually had 404s when i called create-checkout-session
so is this issue fixed, or you still have that 404?
nope now it reloads the page and nothing happens
and do you get some logs on your backend server to check if /api/create-checkout-session was run?
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
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
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
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.
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' });
}
});
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
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?
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 acheckout.session.completedevent, assuming you setup a webhook endpoint listening to that event.
yes it does work
does payment not trigger invoice.paid?
i have a webhook endpoint listening to invoice.paid
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 receiveinvoice.paid. but for one time payments, there would be no invoice created.
in general for Checkout Session we recommend listening to checkout.session.completed
we have a guide about this: https://docs.stripe.com/checkout/fulfillment
okay i see