我在 server.js Node 文件中的这一行出现错误 - “const determination = await stripe.tax.calculations.create({", 错误是“await 仅在异步函数中有效”。下面是我的 server.js 文件的代码
const stripe = require('stripe')('sk_test_');
const express = require('express');
const app = express();
app.use(express.json());
const calculation = await stripe.tax.calculations.create({
currency: 'usd',
line_items: [
{
amount: 1000,
reference: 'L1',
tax_code: 'txcd_99999999',
},
],
customer_details: {
address: {
line1: '920 5th Ave',
city: 'Seattle',
state: 'WA',
postal_code: '98104',
country: 'US',
},
address_source: 'shipping',
},
});
app.post('/prepare-payment-sheet', async (req, res) => {
try {
const customer = await stripe.customers.create();
const ephemeralKey = await stripe.ephemeralKeys.create({customer: customer.id},
{apiVersion: '2024-06-20; payment_intent_with_tax_api_beta=v1;'});
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: 'usd',
customer: customer.id,
automatic_payment_methods: {
enabled: true,
},
async_workflows: {
inputs: {
tax: {
calculation: '{{CALCULATION_ID}}',
},
},
},
});
console.log(req.body)
console.log(res.body)
res.json({
paymentIntentID: paymentIntent.id,
clientSecret: paymentIntent.client_secret,
ephemeralKey: ephemeralKey.secret,
customer: customer.id,
publishableKey: 'pk_test_'
});
} catch(e) {
res.status(400).json({ error: { message: e.message }});
}
});
app.post('/update-payment-sheet', async (req, res) => {
const paymentIntent = await stripe.paymentIntents.update(
req.body.paymentIntentID,
{
amount: req.body.amount,
}
);
console.log(req.body)
console.log(res.body)
res.json({});
});
app.listen(3000, () => console.log('Running now on port 3000'));
app.get('/', (req,res) => res.json('My API is running'))
以下是 Stripe 网站上无效的代码副本
// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = require('stripe')(
'sk_test_',
{apiVersion: '2024-06-20; payment_intent_with_tax_api_beta=v1;'}
);
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000,
currency: 'usd',
automatic_payment_methods: {
enabled: true,
},
async_workflows: {
inputs: {
tax: {
calculation: '{{CALCULATION_ID}}',
},
},
},
});
问题是您在代码的顶层使用了 await 关键字,但是,您只允许在异步函数内部使用 await 关键字。
经过这个小小的改变你的代码就可以工作了