CJ Broersma
CJ Broersma

Reputation: 189

I need to get the json STRIPE API data converted into php

I need help converting some json data into a php array. I am using the STRIPE API. It is first inputted into a javascript array

// The items the customer wants to buy
var purchase = {
  
  items: [{ id: 2235 }]
};

Then ajaxed like so

fetch("create.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(purchase)
})

on the server side (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. The function looks like so (the return is just hard coded for now but I will replace with an amount)

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. I intend on looping through the array id, getting the values from my mySQL database and returning it. Can anyone give me an idea of what to do?

Upvotes: 0

Views: 774

Answers (1)

Justin Michael
Justin Michael

Reputation: 6485

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_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.

Next, inside calculateOrderAmount(), you can do something like this:

foreach($items as $item) {
  // Do something with $item->id
}

Upvotes: 1

Related Questions