查询 firestore 以检查集合和文档

时间:2021-04-22 19:45:27

标签: javascript node.js reactjs firebase google-cloud-firestore

我对 firebase / firestore 有点陌生。我正在使用条带 API。

一旦用户在预构建的条带结帐页面上点击 start trial,它就会转到 firestore 并创建一个名为 subscriptions 的新集合,其中包含所有用户信息。它似乎正在这样做,但是,我创建了一个名为 successPage 的页面,它基本上会检查以确保它创建了它。

请找到以下代码:

 const successPage = props => { 

firebase.auth().onAuthStateChanged((user) => {
    if(user) {
      console.log("calling success page : " + user.uid)


//checking if user is paying for subscription
firestore.collection('customers').doc(user.uid).collection('subscriptions')
.where('status', 'in', ['trialing', 'active']).get()
.then(activeSubscriptions => {
  // if this is true, the user has no active subscription.
  if (activeSubscriptions.empty === true) {
    console.log(user.uid)
    firestore.collection('customers').doc(user.uid)
    .get().then(
    doc => {
      if (doc.exists) {
        firestore.collection('customers').doc(user.uid).collection('subscriptions').get().
          then(sub => {
            if (sub.docs.length > 0) {
              var activityStatus = "canceled"
              createCheckoutSession(activityStatus)
              console.log('subcollection exists');
            } else {
              alert("Your account has been created, but your payment details we're not successfully created. You will now be redirected to the checkout page")
                createCheckoutSession()
                console.log(user.uid)
                console.log("does not exist!")
            }
          });
      }
    });
  } else if (activeSubscriptions.size > 1){
    alert("you have more then one active subscription. please manage your subscriptions and cancel one of your subscriptions to access the application")
  } else {
    firestore.collection("profiledata").doc(user.uid).update({
      accountStatus: "active"
    }).then (() => {
      
      
      firestore
      .collection("roger@x.ca")
      .add({
        to: user.email,
        message: {
          
        },
      })
      .then(() => console.log("email out for delivery!"));

    props.history.push('/clients')
    
    })
    
  }
});
}

  })

  return (

     <input type="hidden"></input>
  )
}

它检查订阅集合,其中 status = 为试用或活动,然后检查订阅中的所有内容以查看发生了什么,但由于某种原因,它一直重定向到条带页面 (createCheckoutSession),即使订阅集合已创建。这是时间问题吗?

1 个答案:

答案 0 :(得分:0)

当创建新订阅时,Stripe 会触发到您的服务器/云功能的 Webhook,然后在 Firestore 中创建文档。此过程可能需要一些时间,同时您的用户可能已被重定向到成功页面。如果文档尚未创建,则您将无法显示交易状态。

您可以采取以下解决方法:

  1. 在您的服务器上创建 Stripe Checkout 会话时,您实际上可以创建订阅文档,但将名为“stripe_response”的字段设置为 false,并在 stripe success_url 中添加新订阅文档 ID 作为查询参数。所以你的网址可能看起来像:https://domain.ext/paymentSuccess?id=<that_document_id>,
  2. 现在,当用户在成功页面上时,查找具有查询参数中提到的 ID 的特定订阅文档。如果“stripe_response”仍然是假的,那么可能 webhook 还没有完成它的工作。只需在 5 秒后重试请求,然后向用户显示状态。确保在 webhook 中将 stripe_response 设置为 true。

对于简单的第 2 步,您只需在文档上附加一个 realtime listener,这样当状态更新时您会尽快得到响应,而无需依赖轮询。

来到“保持重定向”部分,您能否具体说明重定向的确切情况?它在哪里重定向以及所有这些?

这绝对是一种竞争条件,但如果您按照上述步骤进行操作,它应该会解决它。如果您需要更多帮助来解决此问题,请告诉我。