You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中Stripe结账完成后如何从Session获取商品元数据?

解决Stripe Session元数据获取为Null的问题

问题根源

你把元数据设置在了Product对象上,但获取时错误地从Price对象的metadata里取值;同时Stripe API默认不会返回关联对象的完整数据,必须显式指定展开字段才能拿到Product的元数据。

修复步骤

1. 修改LineItem查询逻辑,添加字段展开

调用listLineItems时,通过expand参数显式展开price.product,确保能获取到关联Product的完整数据:

private void handleCheckoutSessionCompleted(Session session) {
    try {
        // 添加expand参数,展开Price关联的Product对象
        SessionListLineItemsParams params = SessionListLineItemsParams.builder()
                .addExpand("data.price.product")
                .build();
        List<LineItem> lineItems = session.listLineItems(params).getData();

        for (LineItem item : lineItems) {
            // 从Price关联的Product中获取元数据
            Product product = item.getPrice().getProductObject();
            if (product != null) {
                String metadataValue = product.getMetadata().get("this");
                System.out.println("this is " + metadataValue);
            }
        }
    } catch (StripeException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2. 确认元数据的存储位置

你创建Session时,通过PriceData.ProductData.builder().putAllMetadata(metadata)把元数据存在了Product上,而非Price上,所以必须从Product对象的metadata中读取,不能从item.getPrice().getMetadata()获取。

额外检查项

  • 确认传入的metadataMap中确实包含键为"this"的键值对,没有拼写错误
  • 可以在创建Session后,登录Stripe后台查看对应的Product,确认元数据已正确保存

内容的提问来源于stack exchange,提问作者J.E.N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:47:12