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

Stripe API创建优惠券成功但未返回对象,无法获取ID?

问题:Stripe API创建优惠券成功但返回空对象,无法获取优惠券ID

我尝试通过Stripe API创建优惠券,优惠券已在Stripe管理面板成功创建,但API调用返回空对象{},无法获取优惠券ID。以下是服务端PHP代码和AJAX代码:

服务端PHP代码

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/assets/core/php/include/stripe/live-env.php';

$stripe = new \Stripe\StripeClient($stripeSecretKey);

$stripe->coupons->create([
  'percent_off' => 20,
  'duration' => 'once',
]);

echo json_encode($stripe);

AJAX代码

$.ajax({
    type: "post",
    url: "/assets/core/php/ajax-calls/stripe/create-coupon.php",
    dataType: "json",
    success: function (response, textStatus, xhr) {
        console.log("success create coupon");
        console.log(response);
    },
    error: function (error) {
        console.log("error creating coupon");
        console.log(error);
    }
})

请问我哪里操作出错了?


问题原因及修复方案
  • 核心问题:你现在是把整个StripeClient实例对象用json_encode输出,这个对象包含大量无法被JSON序列化的内部属性(比如连接池、配置信息等),最终只会输出空对象{}。而且你完全没捕获coupons->create()方法返回的优惠券数据。

  • 修复步骤:

    1. 捕获创建后的优惠券对象:把coupons->create()的结果赋值给一个变量,比如$coupon。
    2. 输出优惠券对象的JSON:对$coupon而不是$stripe实例进行json_encode。

修改后的PHP代码:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/assets/core/php/include/stripe/live-env.php';

$stripe = new \Stripe\StripeClient($stripeSecretKey);

// 捕获创建成功后的优惠券对象
$coupon = $stripe->coupons->create([
  'percent_off' => 20,
  'duration' => 'once',
]);

// 输出优惠券数据的JSON格式
echo json_encode($coupon);

修改后,AJAX的response里就会包含完整的优惠券数据,包括你需要的id字段。

内容的提问来源于stack exchange,提问作者Michael Bellamy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:23:30