如何在颤振中将数据传递到云函数文件

How to pass data to cloud function file in flutter

我是 flutter 的新手,我刚刚创建了一个应用程序,它使用 flutter_stripe: ^2.1.0 插件接受用户的付款。云函数文件 index.js 中的金额是固定的,但我想传递动态计算的金额。这是我的代码。

Future<void> makePayment() async {
final url = Uri.parse(
    'https://us-central1-carwashapp-376b6.cloudfunctions.net/stripePayment');
final response =
    await http.get(url, headers: {"Content-Type": "application/json"});
paymentIntentData = json.decode(response.body);
await Stripe.instance.initPaymentSheet(
  paymentSheetParameters: SetupPaymentSheetParameters(
    paymentIntentClientSecret: paymentIntentData['paymentIntent'],
    applePay: true,
    googlePay: true,
    style: ThemeMode.light,
    merchantCountryCode: 'US',
    merchantDisplayName: 'Kleen My Car',
  ),
);
setState(() {});
displayPaymentSheet();
}



Future<void> displayPaymentSheet() async {
    try {
      await Stripe.instance.presentPaymentSheet(
          parameters: PresentPaymentSheetParameters(
              clientSecret: paymentIntentData['paymentIntent'],
              confirmPayment: true));
      setState(() {
        paymentIntentData = null;
      });
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Payment succeeded')));
    } catch (e) {
      print('error error error');
    }
  }

这是我的 index.js 文件的代码

    const functions = require("firebase-functions");

const stripe = require("stripe")(functions.config().stripe.testkey);

exports.stripePayment = functions.https.onRequest(async (req, res) => {
  const paymentIntent = await stripe.paymentIntents.create(
    {
      amount: 120,
      currency: "USD",
    },
    function (err, paymentIntent) {
      if (err != null) {
        console.log(err);
      } else {
        res.json({
          paymentIntent: paymentIntent.client_secret,
        });
      }
    }
  );
});

非常感谢任何形式的帮助。非常感谢!

您需要修改此行:

final response = await http.get(url, headers: {"Content-Type": "application/json"});

(首先,在 GET 上给出内容类型没有任何意义,因为 GET 没有任何内容。删除 header。)

您可以更改为 POST 并将金额添加为参数,或者将其保留为 GET 并将金额添加到 URL。

加上POST,加上(例如)body: {'amount': amount.toString()}

有了GET,将其添加到URL,如下:

final uri = Uri.https('us-central1-carwashapp-376b6.cloudfunctions.net', '/stripepayment', {'amount': amount.toString()});

在您的云函数中从 req 访问 amount。 (例如,在 GET 示例中,它将是 req.query.amount as string。)

我们还传递了其他参数,如电子邮件、唯一订单 ID(用作幂等键)等。

在 index.js 文件中更改

const paymentIntent = await stripe.paymentIntents.create(
{
  amount: 120,
  currency: "USD",
},

const paymentIntent = await stripe.paymentIntents.create(
{
  amount: req.query.amount,
  currency: req.query.currency,
},

并部署您的函数。 之后,在付款功能中,将您的 URL 更改为

https://us-central1-carwashapp-376b6.cloudfunctions.net/stripePayment?amount=$amount&currency=$currency.

这样,通过改变URL中的$amount变量的值,就可以每次传递不同的金额。