Skip to content

Instantly share code, notes, and snippets.

@2Fwebd
Created January 23, 2017 16:03
Show Gist options
  • Save 2Fwebd/d9ddfe7809a8ac648d83f6b38ee0d679 to your computer and use it in GitHub Desktop.
Save 2Fwebd/d9ddfe7809a8ac648d83f6b38ee0d679 to your computer and use it in GitHub Desktop.
<?php
/**
* Get Sales total from a REMOTE .json file
*
* @link https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6
* @author François Forest
* @version 1.0.0
*/
Class ShopifyIntern
{
/**
* API endpoint to fetch the data
*
* @var string
*/
private $api_endpoint = 'https://shopicruit.myshopify.com/admin/orders.json';
/**
* Orders array
*
* @var array
*/
private $orders = array();
/**
* Current page
*
* @var int
*/
private $page = 0;
/**
* Token for the API auth
*
* @var string
*/
private $access_token = 'c32313df0d0ef512ca64d5b336a0d7c6';
/**
* ShopifyIntern constructor.
*/
public function __construct()
{
// We get the order from all pages
do {
$paged_orders = $this->getOrders();
} while(!empty($paged_orders));
print_r($this->getTotal());
}
/**
* Build a query ready for teh API
*
* @return string
*/
private function buildQuery()
{
// We increase the page number
$this->page = $this->page + 1;
// We return the URL
return $this->api_endpoint . '?access_token='. $this->access_token .'&page='. $this->page;
}
/**
* Sum every update total price to get the turnover
*
* Important, the global $this->orders contains a sub array [0],
* could be removed easily on a second version though
*
* @return int - USD amount
*/
private function getTotal() {
$total = 0;
if(empty($this->orders))
return $total;
// We loop through all the orders
foreach ($this->orders[0] as $order) {
$total += $order->total_price;
}
return $total;
}
/**
* Retrieve the orders using CURL
*
* @return array of Shopify orders
*/
private function getOrders() {
// Initiate curl
$ch = curl_init();
// We don't want to output it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Let's grab our data
curl_setopt($ch, CURLOPT_URL,$this->buildQuery());
$results = curl_exec($ch);
// Decode the JSON
$decoded_result = json_decode($results);
if(!empty($decoded_result->orders)) {
// We add the returned orders to our global handler
array_push($this->orders, $decoded_result->orders);
// We return it so we know we can keep it going
$returned = $this->orders;
} else {
$returned = array();
}
// Close curl
curl_close($ch);
return $returned;
}
}
// Here is where the magic starts.
new ShopifyIntern();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment