我正在开发模式下创建一个条带结帐会话,该会话成功将信息发送到我的 webhook,当我打印出会话详细信息时,它成功打印出会话中的所有信息。但奇怪的是,当我尝试访问一条单独的信息以便我可以使用 prisma 将其保存在我的后端时,当我 console.log 输出它时,它说该信息未定义。这太奇怪了,我可以看到整个事情,但看不到个别信息。我做错了什么以及如何访问 Next.js 程序中的各个行?
这是我的网络钩子代码
import Stripe from "stripe";
import { stripe } from "@/lib/stripe";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import prisma from "@/lib/db/prisma";
import { OrderItem } from "@prisma/client";
import { createCart, getCart } from "@/lib/db/cart";
import { revalidatePath } from "next/cache";
export async function POST(req: Request) {
const cart = (await getCart()) ?? (await createCart());
const body = await req.text();
const signature = headers().get("Stripe-Signature") as string;
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!,
);
} catch (error) {
return new NextResponse("Invalid signature", { status: 400 });
}
const session = event.data.object as Stripe.Checkout.Session;
if (event.type === "charge.succeeded") {
console.log("*********************************************************");
console.log(session.shipping_details?.address?.state);
console.log("*********************************************************");
const paymentIntent = event.data.object;
const userId = paymentIntent.metadata.userId;
const {
name,
address,
aptNumber,
city,
state,
zipCode,
country,
paymentMethod,
totalInCents,
taxInCents,
cartItems,
} = paymentIntent.metadata;
try {
await prisma.$transaction(async (prisma) => {
// Create the order
const order = await prisma.order.create({
data: {
userId,
name,
address,
aptNumber,
city,
state,
zipCode,
country,
paymentMethod,
totalInCents: parseInt(totalInCents),
taxInCents: parseInt(taxInCents),
},
});
// Create order items
const orderItems = JSON.parse(cartItems).map((item: OrderItem) => ({
productId: item.productId,
productName: item.productName,
price: item.price,
quantity: item.quantity,
orderId: order.id,
}));
await prisma.orderItem.createMany({
data: orderItems,
});
// Empty the user's cart
await prisma.cartItem.deleteMany({
where: {
cart: {
userId: userId,
},
},
});
await prisma.cart.update({
where: { id: cart.id },
data: {},
});
revalidatePath("/", "layout");
});
} catch (error) {
console.error("Error handling checkout session:", error);
}
}
return new NextResponse("ok", { status: 200 });
}
这是我 console.log 整个会话时打印出来的内容。
{
id: *the id is here*,
object: 'charge',
amount: 1499,
amount_captured: 1499,
amount_refunded: 0,
application: null,
application_fee: null,
application_fee_amount: null,
balance_transaction: null,
billing_details: {
address: {
city: 'Austin',
country: 'US',
line1: '3186 Brentwood Drive',
line2: null,
postal_code: '78746',
state: 'TX'
},
email: '[email protected]',
name: 'John Doe',
phone: null
},
calculated_statement_descriptor: 'JOHN DOE',
captured: true,
created: 1722718453,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_balance_transaction: null,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: {
network_status: 'approved_by_network',
reason: null,
risk_level: 'normal',
risk_score: 35,
seller_message: 'Payment complete.',
type: 'authorized'
},
paid: true,
payment_intent: 'pi_3PjoxtRu5CVeMm6U0PoyXjnC',
payment_method: 'pm_1PjoxsRu5CVeMm6UvlsVXLbb',
payment_method_details: {
card: {
amount_authorized: 1499,
authorization_code: null,
brand: 'visa',
checks: [Object],
country: 'US',
exp_month: 11,
exp_year: 2042,
extended_authorization: [Object],
fingerprint: '08eKoYQiOE8pTlLD',
funding: 'credit',
incremental_authorization: [Object],
installments: null,
last4: '4242',
mandate: null,
multicapture: [Object],
network: 'visa',
network_token: [Object],
overcapture: [Object],
three_d_secure: null,
wallet: null
},
type: 'card'
},
radar_options: {},
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/payment/CAcaFwoVYWNjdF8xUGZDT1pSdTVDVmVNbTZVKPaxurUGMgYiOLShtJk6LBZH4IQkJ4DUUBK9TzBeAOdnf8adJI3SNgJhlihMuQHs9e8IDacRGL5vePD12-',
refunded: false,
review: null,
shipping: {
address: {
city: 'AUSTIN',
country: 'US',
line1: '3186 Brentwood Drive',
line2: null,
postal_code: '78746',
state: 'TX'
},
carrier: null,
name: 'John Doe',
phone: null,
tracking_number: null
},
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
}
当我检查单个项目时,例如
console.log(session.shipping_details?.address?.state);
它只是打印出未定义,这很奇怪。
另外,您可能已经注意到,我也觉得这很奇怪,但是当我尝试访问会话中的信息并尝试执行会话时。“自动完成”以获取可供选择的可用键,它并没有只给我基本的运费。只有shipping_details,这也很奇怪。我似乎可以访问顶级键,例如 session.created,但更深层次的键值对似乎不起作用。我以前从未处理过这个问题,所以我很困惑。
我有 console.logged 记录了我能想到的所有可能的方式。我已经浏览了文档,但它主要只是向我展示了会话对象的结构,但没有任何内容可以让我理解它为什么不起作用。
你有尝试过吗?
console.log(session.shipping?.address?.state);
否则您可以先尝试记录这些。希望你能找到更多有价值的日志
console.log(session?.shipping)
console.log(session?.shipping_details)
也许 Shipping_details 有一些其他属性而不是地址