如何在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没有任何内容。删除该标头。(

您可以更改为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,
},

并部署您的功能。之后,在makepayment功能中,将您的URL更改为

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

通过这种方式,您可以通过更改URL中$amount变量的值,每次传递不同的金额。

相关内容

  • 没有找到相关文章

最新更新