0

當用戶購買產品並通過分條付款時,我正在努力融合自動化工作流程。我正在使用Firestore和雲端函數。使用Firestore在Cloud功能中獲取/添加文檔

工作流程

  1. 通過條紋Checkout.js
  2. 付款用戶購買產品存儲在 '支付' 收集

    { product:<uid of the product> '...', user:<uid of the user> '..', method: 'stripe', token:< Stripe token> {..} } 
    
  3. 觸發器雲功能(onWrite對於代收貨款)

  4. TODO:Get product DocRef從「產品」(獲取產品的價格)
  5. TODO:爲「購買」集合添加文檔集合的文檔內的「用戶」

  6. 報酬支付

我實現這個工作流程,除了第4步和第5步外,因爲我不知道如何從Firestore中檢索和添加DocRef(CloudSense文檔提供了很多關於RT數據庫如何工作的示例)

個功能/ index.js

exports.stripeCharge = functions.firestore 
    .document('/payments/{payment}') 
    .onWrite(event => { 
    const paymentId = event.params.payment; 
    const payment = event.data.data(); 
    if (!payment || payment.method !== 'stripe' || payment.charge) return; 
    // 4. Get Product's Price 
    firestore.collection('products').doc(payment.product).then(product => { 
     const idempotency_key = paymentId; 
     const charge = { 
     amount: product.price, 
     currency: 'chf', 
     source: payment.token.id 
     }; 
     stripe.charges.create(charge, {idempotency_key}).then(charge => { 
     // 5. Update User Purchases 
     firestore.collection('users').doc(payment.user).collection('purchases').add({ 
      product: payment.product, 
      payment: paymentId, 
      date: new Date() 
     }); 
     // Updated Charge 
     event.data.ref.update({charge}); 
     }); 
    }); 

聯繫SDK 我想,我必須使用Admin SDK來實現這一點,但我對這個應該如何與公司的FireStore

工作

回答

1

訪問不知道來自Admin SDK的Firestore與從Admin SDK訪問任何其他Firebase產品非常相似:例如, admin.firestore()...https://firebase.google.com/docs/reference/admin/node/admin.firestore

你錯過了,當你試圖訪問該文檔的get()電話:

firestore.collection('products').doc(payment.product).get().then(product => { 
    if (!product.exists) { 
     console.log('No such product!'); 
    } else { 
     console.log('Document data:', product.data()); 
    } 

如果你還沒有從之前的JavaScript使用的FireStore雲的功能是不是開始使用的最簡單方法它。我建議您閱讀docs for JavaScript/web users,並以​​。

+0

很好,謝謝! 所以我只需要用'admin.firestore()'替換'firestore'並添加'get()'方法 –

相關問題