[英]I need to get the json STRIPE API data converted into php
我需要帮助将一些 json 数据转换为 php 数组。 我正在使用 STRIPE API。 它首先被输入到一个 javascript 数组中
// The items the customer wants to buy
var purchase = {
items: [{ id: 2235 }]
};
然后像这样 ajaxed
fetch("create.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(purchase)
})
在服务器端(php)
header('Content-Type: application/json');
try {
// retrieve JSON from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
//echo $json_obj;
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => calculateOrderAmount($json_obj->items),
'currency' => 'usd',
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
我遇到麻烦的是calculateOrderAmount function。 function 看起来像这样(返回现在只是硬编码,但我会用一个数量替换)
function calculateOrderAmount(array $items): int {
// I need to loop through the array and break out the
// product ids
return 1400;
}
对于我的一生,我无法弄清楚如何遍历数组并获取 id 值。 我打算循环遍历数组 id,从我的 mySQL 数据库中获取值并返回它。 谁能告诉我该怎么做?
我建议更改您的json_decode()调用以包含第二个参数,该参数指定 JSON 是否将被解码为 PHP true
( false
,so:an associative array)
$json_obj = json_decode($json_str, false);
这样,在解码 JSON 时,您就不必依赖JSON_OBJECT_AS_ARRAY
标志设置来确定您获得的是 object 还是数组。
接下来,在calculateOrderAmount()
中,您可以执行以下操作:
foreach($items as $item) {
// Do something with $item->id
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.