Stripe支付后如何查询所使用的优惠码?
如何获取Stripe支付中使用的优惠码
嘿,我刚好碰到过类似的问题,给你几个可行的方案:
方案1:从Checkout Session的line_items中提取
你之前调用Session::retrieve的时候,默认不会返回line_items的完整折扣信息,需要显式展开这个字段才行。修改你的代码如下:
$session = \Stripe\Checkout\Session::retrieve([ 'id' => '[SESSION_ID]', 'expand' => ['line_items'] ]);
拿到$session后,遍历line_items里的每一项,查看discounts数组,里面会包含关联的优惠券(Coupon)信息:
foreach ($session->line_items->data as $item) { if (!empty($item->discounts)) { foreach ($item->discounts as $discount) { $coupon = $discount->coupon; // 这里可以获取优惠码的ID、名称、规则等 echo "使用的优惠码:" . $coupon->name . "(ID:" . $coupon->id . ")"; } } }
方案2:通过PaymentIntent关联的Charge对象查询
PaymentIntent本身不会直接存储优惠码,但它关联的Charge对象里会有折扣信息。你可以先从PaymentIntent拿到Charge的ID,再查询Charge并展开discount字段:
// 先获取PaymentIntent $paymentIntent = \Stripe\PaymentIntent::retrieve('[PAYMENT_INTENT]'); // 取第一个关联的Charge(一般支付成功后只有一个) $chargeId = $paymentIntent->charges->data[0]->id; // 查询Charge并展开discount $charge = \Stripe\Charge::retrieve([ 'id' => $chargeId, 'expand' => ['discount'] ]); // 如果有使用优惠码,就能拿到对应的Coupon if (!empty($charge->discount)) { $coupon = $charge->discount->coupon; echo "使用的优惠码:" . $coupon->name; }
补充说明
- 如果你是把优惠码绑定到Customer对象上(比如订阅场景),还可以通过
Customer::retrieve并展开discount字段来获取优惠信息。 - 注意:Stripe的API默认不会返回嵌套的深层数据,必须通过
expand参数指定要展开的字段,否则你看不到折扣和优惠券的详细内容。
内容的提问来源于stack exchange,提问作者Martin Muehl




