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
相关产品推荐
相关产品推荐

