【发布时间】:2021-03-22 10:28:04
【问题描述】:
我需要帮助将一些 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 calculateOrderAmount(array $items): int {
// I need to loop through the array and break out the
// product ids
return 1400;
}
对于我的一生,我无法弄清楚如何遍历数组并获取 id 值。我打算循环遍历数组 id,从我的 mySQL 数据库中获取值并返回它。 谁能告诉我该怎么做?
【问题讨论】:
标签: javascript php jquery arrays stripe-payments