Getting cors error when trying to code subscription purchase through stripe and firebase

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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

New contributor

psimonson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật