Retrieve an array of invoices instead of an object PHP

173 Views Asked by At

I'm trying to retrieve a list of invoices per customer. So far I'm only retrieving the first object of the list. But how do I retrieve the whole list? I'm a beginner in PHP so I really can't figure this out and the docs of Chargebee aren't clarifying anything for me.

Here are the docs: https://apidocs.eu.chargebee.com/docs/api/invoices?prod_cat_ver=2&lang=php#list_invoices

And this is what I tried so far:

$customerID = $_POST['customerID']; 

require_once(dirname(__FILE__) . '/chargebee-php-2.8.3/lib/ChargeBee.php');

ChargeBee_Environment::configure("xxxx","xxxx");

$result = ChargeBee_Invoice::all(array(
  "limit" => 13,
  "sortBy[desc]" => "date",
  "customerId[is]" => (string)$customerID
  ));
  
foreach($result as $entry){
  $invoice = $entry->invoice();
}

$array = (array) $invoice;

echo json_encode($array);

Unfortunately I'm only retrieving the first item of the list. How do I get the whole list in an array, but encoded to a json string?

2

There are 2 best solutions below

3
geertjanknapen On BEST ANSWER

You keep overwriting your $invoice variable.

Creating and empty array and pushing every invoice onto that should yield the result you want. So try this:

$customerID = $_POST['customerID']; 

require_once(dirname(__FILE__) . '/chargebee-php-2.8.3/lib/ChargeBee.php');

ChargeBee_Environment::configure("xxxx","xxxx");

$result = ChargeBee_Invoice::all(array(
  "limit" => 13,
  "sortBy[desc]" => "date",
  "customerId[is]" => (string)$customerID
  ));

$invoicesArr = [] // create empty array
  
foreach($result as $entry){
  array_push($invoicesArr, $entry->invoice()); // foreach invoice, push it to array
}

echo json_encode($invoicesArr);
0
Mohd Farhan Rizwan On

You can use the getValues() function given by chargebee. Here is the example.

$result = ChargeBee_Invoice::all(array(
 "limit" => 13,
 "sortBy[desc]" => "date",
 "customerId[is]" => (string)$customerID
));

if (count($result) > 0) {

   $invoices = [];

   foreach ($result as $value) {

       $invoices[] = $value->invoice()->getValues();

   }

   echo json_encode($invoices);

} else {

   echo "Invoices not found";

}