簡體   English   中英

使用條帶結帳時出現未定義的錯誤和 url

[英]Getting undefined for error and url when using stripe checkout

我有一個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;
      }
    }
  }
}

所以我對錯誤和 url 沒有定義......任何想法我做錯了什么?

如果文檔不存在並且您無法讀取 undefined 的屬性,則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;
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM