问题描述
我正在处理条带扩展,但是当我传递 uid 时,它给了我错误“firebase__WEBPACK_IMPORTED_MODULE_3___default.a.auth.onAuthStateChanged 不是一个函数”...所以有什么建议我如何解决这个错误??
这是我的代码:
import {loadStripe} from '@stripe/stripe-js';
import firebase from 'firebase';
const firestore = firebase.firestore();
firebase.auth().onAuthStateChanged((user) => {
if(user) {
console.log(user.uid) ;
}
});
export async function createCheckoutSession(uid){
firebase.auth.onAuthStateChanged((user) => {
if (user){
const checkoutSessionRef = firestore
.collection('customers')
.doc(user.uid)
.collection('checkout_sessions')
.add({
price: 'price id',success_url: window.location.origin,cancel_url: window.location.origin,});
// Wait for the CheckoutSession to get attached by the extension
checkoutSessionRef.onSnapshot((snap) => {
const { error,sessionId } = snap.data();
if (error) {
// Show an error to your customer and
// inspect your Cloud Function logs in the Firebase console.
alert(`An error occured: ${error.message}`);
}
if (sessionId) {
// We have a session,let's redirect to Checkout
// Init Stripe
const stripe = loadStripe('pk_test_1234');
stripe.redirecttocheckout({ sessionId });
}
});
}
}
)}
解决方法
onAuthStateChanged
中的 firebase
函数只能在客户端工作。根据我的理解,您正在尝试检查用户是否已登录或注销,但已在后端本身调用了 onAuthStateChanged
侦听器。
因此将逻辑或 onAuthStateChanged
逻辑移至前端代码。如果您真的想使用逻辑来检查用户是否通过后端本身登录,那么您可能不得不求助于云功能并使用 firebase adming SDK 处理它。
还应在文件顶部处理 loadStripe
承诺,以避免在每次调用时重新创建 Stripe
对象。