javascript - 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()]);
}
非常感谢任何建议。
解决方案
你在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);
不改变任何其他东西。
推荐阅读
- google-cloud-firestore - 使用 exists() 的 Cloud Firestore 规则是否算作读取?
- regex - RegEx - 排除特定标签之间的随机字符串
- vim - 如何区分快速修复和位置列表缓冲区?
- java - maven 存储库记录器冲突
- c# - 运行时TextBlock不显示整个文本
- node.js - WebRTC 服务器节点
- python - Pandas - 根据另一个列表中的索引对列表中的值求和
- scala - 如何使用基于不同字符串模式的 Spark Scala 在数据框中创建新列
- sendgrid - 使用 ARM 模板部署 SendGrid 帐户
- javascript - 从 URL 获取服务器 IP