简体   繁体   English

在 Cloud Function 中使用 Cloud Firestore 数据

[英]Using Cloud Firestore data in a Cloud Function

I am trying to create Cloud Functions that would fetch data from Cloud Firestore, and send a payment request to a payment gateway API using the values fetched from Cloud Firestore.我正在尝试创建从 Cloud Firestore 获取数据的 Cloud Functions,并使用从 Cloud Firestore 获取的值向支付网关 API 发送支付请求。

I can fetch the document I need from Firestore using this function:我可以使用这个 function 从 Firestore 获取我需要的文档:

exports.getData = functions.https.onRequest((req, res) => {
  const docRef = db.collection('requests').doc('vsFyJ5lisBgYNwQEzOLa');
  const getDoc = docRef.get()
    .then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
        return res.send('Not Found')
      } 
        console.log(doc.data());
        return res.send(doc.data());
    })
    .catch(err => {
      console.log('Error getting document', err);
      
    });
    
 });

However, this function only prints the document values;但是,此 function 仅打印文档值; I need to use the values in another function like the one below:我需要使用另一个 function 中的值,如下所示:

exports.pay = functions.https.onRequest((req, res) => {
  var Iyzipay = require('iyzipay');
  const doc = db.collection('requests').doc('vsFyJ5lisBgYNwQEzOLa');
  const iyzipay = new Iyzipay({
    apiKey: 'apiKey',
    secretKey: 'secretKey',
      uri: 'https://sandbox-api.iyzipay.com'
  });
  var request = {
    locale: Iyzipay.LOCALE.TR,
    conversationId: '123456789',
    price: doc.price,
    paidPrice: doc.paidPrice,
    currency: Iyzipay.CURRENCY.TRY,
    installment: '1',
    basketId: 'B67832',
    paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB,
    paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT,
    paymentCard: {
        cardHolderName: doc.cardHolderName,
        cardNumber: doc.cardNumber,
        expireMonth: doc.expireMonth,
        expireYear: doc.expireYear,
        cvc: doc.cvc,
        registerCard: '0'
    },
  };
iyzipay.payment.create(request, function (err, result) {
  console.log(err, result);
});
});

I tried to combine the functions like below:我试图结合如下功能:

exports.pay = functions.https.onRequest((req, res) => {
  var Iyzipay = require('iyzipay');
  const doc = db.collection('requests').doc('vsFyJ5lisBgYNwQEzOLa');
  const iyzipay = new Iyzipay({
    apiKey: 'sandbox-afXhZPW0MQlE4dCUUlHcEopnMBgXnAZI',
    secretKey: 'sandbox-wbwpzKIiplZxI3hh5ALI4FJyAcZKL6kq',
      uri: 'https://sandbox-api.iyzipay.com'
  });
  const docRef = db.collection('requests').doc('vsFyJ5lisBgYNwQEzOLa');
  const getDoc = docRef.get()
    .then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
        return res.send('Not Found')
      } 
        console.log(doc.data());
        return res.send(doc.data());
    })
    .catch(err => {
      console.log('Error getting document', err);
      
    });
  var request = {
    locale: Iyzipay.LOCALE.TR,
    conversationId: '123456789',
    price: '1',
    paidPrice: '1.2',
    currency: Iyzipay.CURRENCY.TRY,
    installment: '1',
    basketId: 'B67832',
    paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB,
    paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT,
    paymentCard: {
        cardHolderName: doc.cardHolderName,
        cardNumber: doc.cardNumber,
        expireMonth: doc.expireMonth,
        expireYear: doc.expireYear,
        cvc: doc.cvc,
        registerCard: '0'
    }        
  };
iyzipay.payment.create(request, function (err, result) {
  console.log(err, result);
});
});

The payment processor returned an error while the Firestore query printed on the console like before.当 Firestore 查询像以前一样打印在控制台上时,支付处理器返回错误。

I then tried was to try the call to payment processor with static values like below:然后我尝试使用 static 值尝试调用支付处理器,如下所示:

var request = {
    locale: Iyzipay.LOCALE.TR,
    conversationId: '123456789',
    price: '1',
    paidPrice: '1.2',
    currency: Iyzipay.CURRENCY.TRY,
    installment: '1',
    basketId: 'B67832',
    paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB,
    paymentGroup: Iyzipay.PAYMENT_GROUP.LISTING,
    paymentCard: {
        cardHolderName: 'John Doe',
        cardNumber: '5528790000000008',
        expireMonth: '12',
        expireYear: '2030',
        cvc: '123',
        registerCard: '0'
}
}

And the payment processor returned success, so there must be something wrong with the way I fetch or use the Firestore document values.并且支付处理器返回成功,所以我获取或使用 Firestore 文档值的方式一定有问题。

To test once more if it was indeed using Firestore values, I switched only one field to cardNumber: doc.cardNumber .为了再次测试它是否确实使用了 Firestore 值,我只将一个字段切换到cardNumber: doc.cardNumber The console returned:控制台返回:

✔  functions[pay]: http function initialized (http://localhost:5000/highmidlow1/us-central1/pay).
i  functions: Beginning execution of "pay"
⚠  External network resource requested!
   - URL: "https://sandbox-api.iyzipay.com/payment/auth"
 - Be careful, this may be a production service.
⚠  Google API requested!
   - URL: "https://oauth2.googleapis.com/token"
   - Be careful, this may be a production service.
>  null {
>    status: 'failure',
>    errorCode: '12',
>    errorMessage: 'Invalid card number',
>    locale: 'tr',
>    systemTime: 1608311421424,
>    conversationId: '123456789'
>  }
>  {
>    expireYear: '2030',
>    paidPrice: 1.2,
>    cardNumber: '5528790000000008',
>    cvc: '123',
>    price: 1,
>    expireMonth: '12',  }

So how can I fetch a document from Firestore and use its values in a Cloud Function, like price: doc.price ?那么如何从 Firestore 获取文档并在 Cloud Function 中使用其值,例如price: doc.price

I think you need to move your request logic into the .then(...) block because right now it looks like you're trying to use the document result outside of the block where it is actually returned, which might be why you're getting an "invalid card number" error.我认为您需要将您的请求逻辑移动到.then(...)块中,因为现在看起来您正试图在实际返回的块之外使用文档结果,这可能就是您的原因重新收到“无效卡号”错误。

The Firestore API uses Promises for most/all fetch operations so you'll always need to wait for the result before using it. Firestore API 将 Promises 用于大多数/所有 fetch 操作,因此您始终需要在使用它之前等待结果。

// ...
docRef.get().then(doc => {
    if (!doc.exists) {
        console.log('No such document!');
        return res.send('Not Found')
    }
    console.log(doc.data());
    res.send(doc.data());

    const request = { ... }
})

If you're using a node version that supports async/await , it might make it easier to spot these types of bugs.如果您使用的是支持async/await的节点版本,则可能更容易发现这些类型的错误。

const doc = await docRef.get()
if (!doc.exists) {
    console.log('No such document!');
    return res.send('Not Found')
}
console.log(doc.data());
res.send(doc.data());

const request = { ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM