[英]I need to get the json STRIPE API data converted into php
I need help converting some json data into a php array.我需要帮助将一些 json 数据转换为 php 数组。 I am using the STRIPE API.
我正在使用 STRIPE API。 It is first inputted into a javascript array
它首先被输入到一个 javascript 数组中
// The items the customer wants to buy
var purchase = {
items: [{ id: 2235 }]
};
Then ajaxed like so然后像这样 ajaxed
fetch("create.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(purchase)
})
on the server side (php)在服务器端(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()]);
}
Where I get into trouble is the calculateOrderAmount function.我遇到麻烦的是calculateOrderAmount function。 The function looks like so (the return is just hard coded for now but I will replace with an amount)
function 看起来像这样(返回现在只是硬编码,但我会用一个数量替换)
function calculateOrderAmount(array $items): int {
// I need to loop through the array and break out the
// product ids
return 1400;
}
For the life of me I cannot figure out how to loop through the array and get the id value.对于我的一生,我无法弄清楚如何遍历数组并获取 id 值。 I intend on looping through the array id, getting the values from my mySQL database and returning it.
我打算循环遍历数组 id,从我的 mySQL 数据库中获取值并返回它。 Can anyone give me an idea of what to do?
谁能告诉我该怎么做?
I recommend changing your json_decode() call to include the second argument, which specifies if the JSON will be decoded to a PHP object ( false
) or an associative array ( true
), like so:我建议更改您的json_decode()调用以包含第二个参数,该参数指定 JSON 是否将被解码为 PHP
true
( false
,so:an associative array)
$json_obj = json_decode($json_str, false);
This way you're not depending on the JSON_OBJECT_AS_ARRAY
flag setting to determine if you get an object or an array when decoding JSON.这样,在解码 JSON 时,您就不必依赖
JSON_OBJECT_AS_ARRAY
标志设置来确定您获得的是 object 还是数组。
Next, inside calculateOrderAmount()
, you can do something like this:接下来,在
calculateOrderAmount()
中,您可以执行以下操作:
foreach($items as $item) {
// Do something with $item->id
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.