简体   繁体   English

在 NodeJS 中使用 Firebase 为 Stripe 创建付款意图时出错

[英]Error creating a payment intent for Stripe with Firebase in NodeJS

I'm attempting to create a Stripe payment intent in NodeJS with Firebase.我正在尝试使用 Firebase 在 NodeJS 中创建 Stripe 支付意图。 Server function receives JSON from my iOS app, retrieves the product correctly and gets the product's price (which is confirmed by the correct values in console), but at the very last step it doesn't pass the price value correctly.服务器 function 从我的 iOS 应用程序接收 JSON ,正确检索产品并获取产品的价格(由控制台中的正确值确认的最后一步通过价格值),但没有正确。

Here's the error I receive in my Firebase console:这是我在 Firebase 控制台中收到的错误:

Error: Invalid integer: {:domain=>{:domain=>"", :_eventsCount=>"1"}}
    at Function.generate (/srv/node_modules/stripe/lib/Error.js:38:16)
    at IncomingMessage.res.once (/srv/node_modules/stripe/lib/StripeResource.js:175:33)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)

And here's the code:这是代码:

// New Stripe Payment Intent
const newPaymentIntent = express();
newPaymentIntent.use(bodyParser.urlencoded({ extended: true }));
newPaymentIntent.post('/', (req, res) => { createPaymentIntent(req, res); });
function paymentIntent(req, res) { }
exports.paymentIntent = functions.https.onRequest(newPaymentIntent);

const calculateOrderAmount = items => {
    let price = admin.database().ref('/productAds').orderByChild('code').equalTo(items['code']).once('value').then((snapshot) => {
            var productPrice = 99;

            snapshot.forEach((childSnapshot) => {
          var childData = childSnapshot.val();

                productPrice += childData.price;
                console.log(childData.price);
        });

            console.log(productPrice);
            return productPrice;
    });

    return price;
};

// Create Stripe Customer
async function createPaymentIntent(req, res) {
  const { items, currency } = req.body;

    const paymentIntent = await stripe.paymentIntents.create({
      amount: calculateOrderAmount(items),
      currency: 'aud',
    });
    const clientSecret = paymentIntent.client_secret

    // Send publishable key and PaymentIntent details to client
  res.send({
    publishableKey: 'pk_test_ikLVo1vJSDi89gcfwMiBTDDw',
    clientSecret: clientSecret
  });
}

Any suggestions on what I am doing wrong?关于我做错了什么有什么建议吗?

Your function calculateOrderAmount doesn't return a number.您的 function calculateOrderAmount不返回数字。 It returns a promise that will resolve with the value returned by the function you passed to then .它返回一个 promise ,它将使用您传递给then的 function 返回的值进行解析。

You should use another then to wait for the final value, and only then invoke the stripe API.您应该使用另一个then等待最终值,然后才调用条带 API。 Or use async.或者使用异步。 (If you have the capability of using async, you should probably also use it in your calculateOrderAmount function instead of using then , as it will be easier to read and reason about.) (如果你有能力使用异步,你可能也应该在你的calculateOrderAmount function 中使用它,而不是使用then ,因为它更容易阅读和推理。)

So Doug was correct.所以道格是对的。 I edited the code to include async functions and it works flawlessly now.我编辑了代码以包含异步函数,它现在可以完美运行。 Here's what the final code looks like:这是最终代码的样子:

 // Retrieve product code from Firebase async function getDataFromFirebase(items) { const objects = await admin.database().ref('/productAds').orderByChild('code').equalTo(items['code']) const data = await objects.once('value'); return data; } async function getPrice(items) { console.log('Executing getPrice method.'); var resultPrice = 0; // we wait for the axios.get Promise to be resolved const objects = await getDataFromFirebase(items); objects.forEach((childSnapshot) => { var childData = childSnapshot.val(); resultPrice += childData.price; }); console.log('Price is: ' + resultPrice); // we then return the data, just like we did in the callback-based version; return resultPrice, } // Create Stripe Customer async function createPaymentIntent(req, res) { const { items. currency } = req;body. const paymentIntent = await stripe.paymentIntents:create({ amount, await getPrice(items): currency, 'aud'; }). const clientSecret = paymentIntent.client_secret // Send publishable key and PaymentIntent details to client res:send({ publishableKey, 'pk_test_ikLVo1vJSDi89gcfwMiBTDDw': clientSecret; clientSecret }); }

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

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