When I run my function to make a stripe purchase the browser throws this error:
Access to fetch at ‘https://us-central1-smallgistics-cd63d.cloudfunctions.net/createStripeSubscription’ from origin ‘https://smallgistics.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
Any ideas?
Server-side code:
<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors');
const stripe = require('stripe')('sk_test_51NdbMmEls8dLhARfYdtPdL3o7oSszlYaZJE7GMYhvPtpjgGXjGYXLPlEwhD5n4sXZFR0NtaAar1qQQzG6PKEnI9M000ccfgqwX');
var serviceAccount = require('./smallgistics-cd63d-firebase-adminsdk-dev8o-b099ac3121.json');
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://smallgistics-cd63d.firebaseio.com'
exports.createStripeSubscription = functions.https.onRequest((request, response) => {
const corsHandler = cors({origin: true});
corsHandler(request, response, async () => {
const userId = request.body.userId; // The ID of the user in your Firebase auth
const productId = 'prod_Pw1OIYAqg3JuG8'; // The ID of the product in Stripe
// Retrieve the Stripe customer ID from Firestore
const doc = await admin.firestore().collection('users').doc(userId).get();
const customer = doc.data().stripeCustomerId;
// Create the subscription
const subscription = await stripe.subscriptions.create({
items: [{ product: productId }],
response.send({ subscriptionId: subscription.id });
response.status(500).send(error);
<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors');
const stripe = require('stripe')('sk_test_51NdbMmEls8dLhARfYdtPdL3o7oSszlYaZJE7GMYhvPtpjgGXjGYXLPlEwhD5n4sXZFR0NtaAar1qQQzG6PKEnI9M000ccfgqwX');
var serviceAccount = require('./smallgistics-cd63d-firebase-adminsdk-dev8o-b099ac3121.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://smallgistics-cd63d.firebaseio.com'
});
exports.createStripeSubscription = functions.https.onRequest((request, response) => {
const corsHandler = cors({origin: true});
corsHandler(request, response, async () => {
const userId = request.body.userId; // The ID of the user in your Firebase auth
const productId = 'prod_Pw1OIYAqg3JuG8'; // The ID of the product in Stripe
try {
// Retrieve the Stripe customer ID from Firestore
const doc = await admin.firestore().collection('users').doc(userId).get();
const customer = doc.data().stripeCustomerId;
// Create the subscription
const subscription = await stripe.subscriptions.create({
customer: customer,
items: [{ product: productId }],
});
response.send({ subscriptionId: subscription.id });
} catch (error) {
console.error(error);
response.status(500).send(error);
}
});
});
</code>
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors');
const stripe = require('stripe')('sk_test_51NdbMmEls8dLhARfYdtPdL3o7oSszlYaZJE7GMYhvPtpjgGXjGYXLPlEwhD5n4sXZFR0NtaAar1qQQzG6PKEnI9M000ccfgqwX');
var serviceAccount = require('./smallgistics-cd63d-firebase-adminsdk-dev8o-b099ac3121.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://smallgistics-cd63d.firebaseio.com'
});
exports.createStripeSubscription = functions.https.onRequest((request, response) => {
const corsHandler = cors({origin: true});
corsHandler(request, response, async () => {
const userId = request.body.userId; // The ID of the user in your Firebase auth
const productId = 'prod_Pw1OIYAqg3JuG8'; // The ID of the product in Stripe
try {
// Retrieve the Stripe customer ID from Firestore
const doc = await admin.firestore().collection('users').doc(userId).get();
const customer = doc.data().stripeCustomerId;
// Create the subscription
const subscription = await stripe.subscriptions.create({
customer: customer,
items: [{ product: productId }],
});
response.send({ subscriptionId: subscription.id });
} catch (error) {
console.error(error);
response.status(500).send(error);
}
});
});
Client-side code:
// Your web app's Firebase configuration
apiKey: "AIzaSyBmLNOykJH7eAaSxQZsD5P7IlQhUQtBm5k",
authDomain: "smallgistics-cd63d.firebaseapp.com",
projectId: "smallgistics-cd63d",
storageBucket: "smallgistics-cd63d.appspot.com",
messagingSenderId: "641898304430",
appId: "1:641898304430:web:9a7aecf59ea12dc0822e3f",
measurementId: "G-WR83XXQHC0"
firebase.initializeApp(firebaseConfig);
window.onload = function() {
// Set up an auth state changed listener
firebase.auth().onAuthStateChanged(user => {
// User is signed in, set up the button click handler
const subscribeButton = document.getElementById('subscribeButton');
subscribeButton.addEventListener('click', () => {
// Determine the URL to use based on the environment
const functionURL = location.hostname === 'localhost' || location.hostname === '127.0.0.1'
? 'http://127.0.0.1:5002/smallgistics-cd63d/us-central1/createStripeSubscription'
: 'https://us-central1-smallgistics-cd63d.cloudfunctions.net/createStripeSubscription';
// Call the Firebase function
body: JSON.stringify({ userId: user.uid }),
headers: { 'Content-Type': 'application/json' }
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
console.error('The element with ID subscribeButton does not exist.');
console.log('No user is signed in.');
<code> <script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyBmLNOykJH7eAaSxQZsD5P7IlQhUQtBm5k",
authDomain: "smallgistics-cd63d.firebaseapp.com",
projectId: "smallgistics-cd63d",
storageBucket: "smallgistics-cd63d.appspot.com",
messagingSenderId: "641898304430",
appId: "1:641898304430:web:9a7aecf59ea12dc0822e3f",
measurementId: "G-WR83XXQHC0"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
window.onload = function() {
// Set up an auth state changed listener
firebase.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in, set up the button click handler
const subscribeButton = document.getElementById('subscribeButton');
if (subscribeButton) {
subscribeButton.addEventListener('click', () => {
// Determine the URL to use based on the environment
const functionURL = location.hostname === 'localhost' || location.hostname === '127.0.0.1'
? 'http://127.0.0.1:5002/smallgistics-cd63d/us-central1/createStripeSubscription'
: 'https://us-central1-smallgistics-cd63d.cloudfunctions.net/createStripeSubscription';
// Call the Firebase function
fetch(functionURL, {
method: 'POST',
body: JSON.stringify({ userId: user.uid }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
});
} else {
console.error('The element with ID subscribeButton does not exist.');
}
} else {
// User is signed out
console.log('No user is signed in.');
}
});
};
</script>
</code>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyBmLNOykJH7eAaSxQZsD5P7IlQhUQtBm5k",
authDomain: "smallgistics-cd63d.firebaseapp.com",
projectId: "smallgistics-cd63d",
storageBucket: "smallgistics-cd63d.appspot.com",
messagingSenderId: "641898304430",
appId: "1:641898304430:web:9a7aecf59ea12dc0822e3f",
measurementId: "G-WR83XXQHC0"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
window.onload = function() {
// Set up an auth state changed listener
firebase.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in, set up the button click handler
const subscribeButton = document.getElementById('subscribeButton');
if (subscribeButton) {
subscribeButton.addEventListener('click', () => {
// Determine the URL to use based on the environment
const functionURL = location.hostname === 'localhost' || location.hostname === '127.0.0.1'
? 'http://127.0.0.1:5002/smallgistics-cd63d/us-central1/createStripeSubscription'
: 'https://us-central1-smallgistics-cd63d.cloudfunctions.net/createStripeSubscription';
// Call the Firebase function
fetch(functionURL, {
method: 'POST',
body: JSON.stringify({ userId: user.uid }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
});
} else {
console.error('The element with ID subscribeButton does not exist.');
}
} else {
// User is signed out
console.log('No user is signed in.');
}
});
};
</script>
Any ideas?
Made extensive changes to both client and server side code. Use tutorials and Co-pilot in VS Code. Nothing works