Iv been tryiing to get this api integration to work, when i use postman to try the http://localhost:5001/api/stripe/create-checkout-session POST i get 200k and a session ID in return as well as using curl. When i try the actual redirect on my billing page when cliclking activate subscription nothing happens and console produces a network error:
Billing-7ca61e132a5214f3.js:1 Error creating checkout session:
V
code
:
"ERR_NETWORK"
config
:
{transitional: {…}, adapter: Array(3), transformRequest: Array(1),
transformResponse: Array(1), timeout: 0, …}
message
:
"Network Error"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0,
withCredentials: false, upload: XMLHttpRequestUpload, …}
stack
:
"AxiosError: Network Errorn at m.onerror
(http://localhost:3001/_next/static/chunks/988-fcb0a835e46419aa.js:1:39051)n
at ts.request (http://localhost:3001/_next/static/chunks/988-
fcb0a835e46419aa.js:1:46641)n at async i
(http://localhost:3001/_next/static/chunks/pages/billing/Billing-
7ca61e132a5214f3.js:1:1042)"
[[Prototype]]
:
Error
i @ Billing-7ca61e132a5214f3.js:1
and issue: Ensure CORS response header values are valid
A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request.
To fix this issue, ensure the response to the CORS request and/or the associated preflight request are not missing headers and use valid header values.
Note that if an opaque response is sufficient, the request’s mode can be set to no-cors to fetch the resource with CORS disabled; that way CORS headers are not required but the response content is inaccessible (opaque).
1 request
Request Status Preflight Request (if problematic) Header Problem Invalid Value (if available)
create-checkout-session blocked
create-checkout-session Access-Control-Allow-Origin Missing Header
Learn more: Cross-Origin Resource Sharing (CORS)
iv tried multiple things and cannot get this to work. Any help or insight would be great.
my server index.js
const express = require("express");
const cors = require("cors");
require("dotenv").config();
const app = express();
const PORT = process.env.PORT || 5001;
// Middleware
app.use(cors());
app.use(express.json());
// Import routes
const stripeRoutes = require("./routes/stripe");
app.use("/api/stripe", stripeRoutes);
// Test route
app.get('/api/test', (req, res) => {
res.send('API is working!');
});
// Start server
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
my front end billing.js
import React from "react";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import { useUser } from '../../context/UserContext';
import axios from 'axios';
const stripePromise = loadStripe("your-publishable-key");
const Billing = () => {
const userContext = useUser();
const subscriptionStatus = userContext?.subscriptionStatus;
const setSubscriptionStatus = userContext?.setSubscriptionStatus;
const handleSubscriptionChange = async (priceId) => {
try {
console.log('Creating checkout session...');
const response = await axios.post('http://localhost:5001/api/stripe/create-
checkout-session', {
name: "Basic Plan",
price: 1000,
successUrl: "http://localhost:3001/success",
cancelUrl: "http://localhost:3001/cancel"
}, {
headers: {
'Content-Type': 'application/json'
}
});
const { id } = response.data;
console.log('Checkout session created:', id);
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({ sessionId: id });
if (error) {
console.error('Error redirecting to checkout:', error);
}
} catch (error) {
console.error('Error creating checkout session:', error);
console.error('Error details:', error.response ? error.response.data :
error.message);
}
};
return (
<Elements stripe={stripePromise}>
<div>
<h1>Billing</h1>
<p>Manage your billing information here.</p>
<p>Current subscription status: {subscriptionStatus}</p>
<button onClick={() =>
handleSubscriptionChange('price_1Hh1Y2I4s2eZvKYlo2L8U7c2')}>Activate
Subscription</button>
<button onClick={() =>
handleSubscriptionChange('price_1Hh1Y2I4s2eZvKYlo2L8U7c3')}>Deactivate
Subscription</button>
</div>
</Elements>
);
};
export default Billing;
stripe.js:
`
const express = require('express');
const router = express.Router();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
router.post('/create-checkout-session', async (req, res) => {
const { name, price, successUrl, cancelUrl } = req.body;
console.log('Received request to create checkout session');
console.log('Request body:', req.body);
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: name,
},
unit_amount: price,
},
quantity: 1,
},
],
mode: 'payment',
success_url: successUrl,
cancel_url: cancelUrl,
});
console.log('Checkout session created:', session.id);
res.json({ id: session.id });
} catch (error) {
console.error('Error creating checkout session:', error);
res.status(500).json({ error: error.message });
}
});
module.exports = router;
`
i tried changing cords header, making sure the api url is correct, relaunching the server i stil get the samer result