I’m trying to calculate the order amount in the function but it keeps throwing the error
Uncaught (in promise) SyntaxError: Unexpected token { in JSON at
position 220
& this is the response in the network tab
[
{
"name": "Peanut Butter & Oats",
"price": 7.99,
"quantity": 6,
"size": "N/A"
},
{
"name": "Oatmeal & Blueberry",
"price": 9.99,
"quantity": 3,
"size": "N/A"
},
{
"name": "Chicken Liver & Gizzards",
"price": 4.99,
"quantity": 1,
"size": "N/A"
}
]{
"clientSecret": "SECRET_KEY"
}
JavaScript:
async function initialize() {
const clientSecret = await fetch("create.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({items}),
}).then((r) => r.json());
elements = stripe.elements({ clientSecret });
const paymentElement = elements.create("payment", {
fields: {
billingDetails: {
name: "auto",
email: "auto",
}
}
});
paymentElement.mount("#payment-element");
}
PHP:
function calculateOrderAmount(array $items): int {
// Replace this constant with a calculation of the order's amount
// Calculate the order total on the server to prevent
// people from directly manipulating the amount on the client
echo json_encode($items);
/**$total = 0;
for ($i = 0; $i < count($items); $i++) {
$total += ($items[i].quantity) * $items[$i].price;
//$total += 100;
}**/
return 1400;
}
header('Content-Type: application/json');
try {
// retrieve JSON from POST body
$jsonStr = file_get_contents('php://input');
$jsonObj = json_decode($jsonStr);
// Create a PaymentIntent with amount and currency
$paymentIntent = StripePaymentIntent::create([
'amount' => calculateOrderAmount($jsonObj->items),
'currency' => 'USD',
'automatic_payment_methods' => [
'enabled' => true,
],
'receipt_email' => '[email protected]',
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
If I remove the echo statement the error goes away but the commented out for loop ( inside the calculateOrderAmount function) is basically what I want to do because I need to calculate the price based on that data, but it keeps giving me a json error but I followed the code from the Stripe docs.