首页 > 解决方案 > JSON解码不接收数据

问题描述

我正在尝试使用 Stripe API 创建付款表单,如下所述: https ://stripe.com/docs/payments/integration-builder

我想从前端发送金额(向用户收费),因此尝试将其添加到获取请求中,如下所示:

var purchase = {
  //items: [{ id: "xl-tshirt", price: 400 }]
  amount: 2000
};

// Disable the button until we have Stripe set up on the page
document.querySelector("button").disabled = true;
fetch("/create.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(purchase)
});

但是,该值(当前硬编码为 2000)没有成功传递到 POST 正文,并且支付意图失败。下面是我正在使用的代码:

try {
  // retrieve JSON from POST body
  $json_str = file_get_contents('php://input');
  $json_obj = json_decode($json_str, false);
  $paymentIntent = \Stripe\PaymentIntent::create([
    //'amount' => calculateOrderAmount($json_obj->items),
    'amount' => $json_obj['amount'],
    'currency' => 'usd',
  ]);
  $output = [
    'clientSecret' => $paymentIntent->client_secret,
  ];
  echo json_encode($output);
} catch (Error $e) {
  http_response_code(500);
  echo json_encode(['error' => $e->getMessage()]);
}

非常感谢任何建议。

标签: javascriptphpjsonstripe-payments

解决方案


你在false这里发送,将其转换为object

$json_obj = json_decode($json_str, false);

然后您尝试将其用作array此处

'amount' => $json_obj['amount'],

尝试使用

'amount' => $json_obj->amount,

或者

$json_obj = json_decode($json_str, true);

不改变任何其他东西。


推荐阅读