使用条纹签出时,错误和url未定义



我有一个createCheckoutSession.ts:

import { db } from '../firebase/firebaseInit';
import { collection, addDoc, onSnapshot } from 'firebase/firestore';
import { User } from 'firebase/auth';
export async function createCheckoutSession(user: User) {
console.log('clicked')

const docRef = await addDoc(collection(db, `users/${user?.uid}/checkout_sessions`), {
price: 'price_1Lb3hiKi0c1bV0RosKIhQ699',
success_url: `http://localhost:3000/success`,
cancel_url: `http://localhost:3000/cancel`,
});
console.log(docRef)
onSnapshot(docRef, (snap) => {
console.log('dsfdsfdf')
const { error, url } = snap.data();
console.log(error, 'snap')
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 (url) {
// We have a Stripe Checkout URL, let's redirect.
window.location.assign(url);
}
});
}

在vscode中,我得到一个行const { error, url } = snap.data();:的错误

Property 'error' does not exist on type 'DocumentData | undefined'.ts(2339)

控制台错误:

Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

安全规则:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid} {
allow read, write: if request.auth.uid == uid;
match /checkout_sessions/{id} {
allow read, write: if request.auth.uid == uid;
}
match /subscriptions/{id} {
allow read: if request.auth.uid == uid;
}
}
match /products/{id} {
allow read: if true;
match /prices/{id} {
allow read: if true;
}
match /tax_rates/{id} {
allow read: if true;
}
}
}
}

所以我得到了未定义的错误和网址。。。你知道我做错了什么吗?

如果文档不存在并且您无法读取未定义的属性,则snap.data()将为undefined。您应该检查文档是否存在,如下所示:

onSnapshot(docRef, snap => {
console.log("In onSnapshot");
// check if the document exists
if (snap.exists()) {
const { name, error } = snap.data(); // This will never be undefined
} else {
console.log("Document does not exist");
}
});

安全规则应该允许用户读取/写入自己的数据,以便您可以添加文档。尝试:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}/{data=**} {
allow read, write: if request.auth.uid == userId;
}
}
}

最新更新