Shopify API getting order by name or order_number - api

Im using a plugin for CakePHP to make the calls to obtain certain orders. I can call all orders with certain fields, but I was wondering how would I have to make the call to get the orders with a certain name or order_number? Here is the source for the call to Shopify. Its already authenticated and everything:
public function call($method, $path, $params=array())
{
if (!$this->isAuthorized())
return;
$password = $this->is_private_app ? $this->secret : md5($this->secret.$this->ShopifyAuth->token);
$baseurl = "https://{$this->api_key}:$password#{$this->ShopifyAuth->shop_domain}/";
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? stripslashes(json_encode($params)) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
$request_headers[] = 'X-Shopify-Access-Token: ' . $this->ShopifyAuth->token;
list($response_body, $response_headers) = $this->Curl->HttpRequest($method, $url, $query, $payload, $request_headers);
$this->last_response_headers = $response_headers;
$response = json_decode($response_body, true);
if (isset($response['errors']) or ($this->last_response_headers['http_status_code'] >= 400))
throw new ShopifyApiException($method, $path, $params, $this->last_response_headers, $response);
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
}
private function shopApiCallLimitParam($index)
{
if ($this->last_response_headers == null)
{
return 0;
}
$params = explode('/', $this->last_response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
...and the code that makes the GET call:
// I only want the id and title of the collections
$fields = "fields=name,id,status,financial_status,fulfillment_status,billing_address,customer";
// get list of collections
$custom_collections = $this->ShopifyAPI->call('GET', "/admin/orders.json", $fields);
$this->set('collections', $custom_collections);
I think I'm missing the place where I can put the conditions for the call to get certain orders. I've already read the API documentation but can't seem to get the answer.
I've tried putting the ?name=%231001 on the url after .json to try and get the order #1001, but it brings back a empty array.
Then I tried ?order_number=1001 but it brings me every order with as well 1001 D: This is really confusing, Could anyone help me?
Thanks in advance.

Well I found out that you can actually get the order using the name or order_number. Its another property that is not listed on the documentation for some reason. But in the URL, if your using another language, all you have to add in the GET is admin/order.json?name=%2310001&status=any this is to get the order 10001 so just add the order_number after the %23. I saw this on a forum in Shopify university, I was just implementing this wrong on my code. If your using the CakePhp shopify plugin like me all I did was add on the $field the ?name=%23". number ."&status=any";
Ill leave the code here:
$this->layout = 'main';
$order_number = "18253";
$fields = "name=%23". $order_number ."&status=any";
$order = $this->ShopifyAPI->call('GET', "/admin/orders.json", $fields);
if (!empty($order)) {
$this->set('order', $order);
} else {
$this->Session->setFlash('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> No existe el numero de orden ingresado.','default',array('class' => 'alert alert-danger alert-dismissible', 'type' => 'alert'));
}
Hope this helps someone :P

Related

PHP Magento API catalog_product.info not working when running through a list

I am trying to create a magento API to get the pricing of each item. I have a table with all the SKU's i need to get info for. i ran the following for one item and it worked
$client = new SoapClient('http://www.mysite.com/api/soap/?wsdl');
$session = $client->login('user', 'pass');
$productId = 'ABC';
$att = array("visibility","sku","special_price", "price");
$arguments = array( $productId, NULL, $att);
$result = $client->call($session, 'catalog_product.info', $arguments);
echo $result['visibility'].",".$result['sku'].",".$result['special_price'].",".$result['price'];
the above code worked fine.
then i tested another code to make sure that my code to query the database and loop through each sku works
$getskus = "SELECT sku FROM items;";
$skus = mysqli_query($con, $getskus);
while($row = mysqli_fetch_array($skus))
{
$productId = $row['sku'];
echo $productId."<br>";
}
The above code works fine. My issue is when i combine the 2 i get a blank screen.
$client = new SoapClient('http://www.mysite.com/api/soap/?wsdl');
$session = $client->login('user', 'pass');
$getskus = "SELECT sku FROM items;";
$skus = mysqli_query($con, $getskus);
while($row = mysqli_fetch_array($skus))
{
$productId = $row['sku'];
$att = array("visibility","sku","special_price", "price");
$arguments = array( $productId, NULL, $att);
$result = $client->call($session, 'catalog_product.info', $arguments);
echo $result['visibility'].",".$result['sku'].",".$result['special_price'].",".$result['price'];
}
i get nothing. Any ideas?
update: if $row['sku'] = '9005' will magento think its a product id instead of a SKU?
This line:
$result = $client->call($session, 'catalog_product.info', $arguments);
This can't accept $arguments as the third param. Instead:
$result = $client->call($session, 'catalog_product.info', $row['sku'], null, $att, 'sku');
NB: not sure if 'null' (4th param) is a valid argument for store view. To be safe, replace with the correct store view (default, in most cases).
RTM: http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalog_product.info.html

Magento resource: custom selects with OR in where (select orders by status)

I'm building a custom module and i'm trying get all orders with specific status:
$canceledQuery = Mage::getSingleton('core/resource')->getConnection('core_read')->select()
->from('mage_sales_flat_order', 'entity_id')
->where('status = ?', 'canceled');
This works very well. But now i'm trying use OR in where, without success.
I have been try this:
$whereCanceled = array();
foreach ($_status as $statusCode => $value) {
$whereCanceled[] = sprintf('%s=:%s', 'status', $statusCode);
}
$ordersQuery = Mage::getSingleton('core/resource')->getConnection('core_read')->select()
->from('mage_sales_flat_order', 'entity_id')
->where(implode(' OR ', $whereCanceled));
So, I don't know how use OR right in this case. I found no use for this with OR. Any idea?
instead of implode use join. magento use join itself.
->where(join(' OR ', $orWhere));//$orWhere array of condition
you can see in below function magento use join for OR condition in where clause
public function getSystemConfigByPathsAndTemplateId($paths, $templateId)
{
$orWhere = array();
$pathesCounter = 1;
$bind = array();
foreach ($paths as $path) {
$pathAlias = 'path_' . $pathesCounter;
$orWhere[] = 'path = :' . $pathAlias;
$bind[$pathAlias] = $path;
$pathesCounter++;
}
$bind['template_id'] = $templateId;
$select = $this->_getReadAdapter()->select()
->from($this->getTable('core/config_data'), array('scope', 'scope_id', 'path'))
->where('value LIKE :template_id')
->where(join(' OR ', $orWhere));
return $this->_getReadAdapter()->fetchAll($select, $bind);
}
for more reference open file located at [magento]/app/code/core/Mage/Core/Model/Resource/Email/Template.php
Hope this help you

Cloadflare Return 'rec_id' For 1 'A' Record in a Zone : PHP

I have a PHP script that adds a new 'A' record to a Cloudflare zone, however, by default these new 'A' records are set as non-active by Cloudflare and now days you can not set them as active when creating them.
So, to edit the new record to set it as active, you need the 'A' records 'rec_id'. In this case action 'rec_load_all' can't be used as there are too many zone 'A' records and I don't think you can filter the request (could be wrong & would be good to be wrong). The zone needs to be filtered.
I have tried the following 'dns_get_rec_one' but it just returns 'NULL' with no error message:
function returnId(){
$request = array();
$request['a'] = 'dns_get_rec_one';
$request['tkn'] = $this->tkn;
$request['email'] = $this->apiEmail;
$request['z'] = 'domain.com';
$request['name'] = 'sub.domain.com';
$response = #json_decode(file_get_contents('https://www.cloudflare.com/api_json.html?' . http_build_query($request)), true);
}
Any ideas as I have little experience with API interactions?
Thanks
Ok, I have worked this out with some help.
When you make the CURL 'rec_new' call to Cloudflare the response includes the 'rec_id' for the new "A" record. This can then be used as the 'id' in the next CURL 'rec_edit' call to edit the record as being active.
The guys at Cloudflare support answer within 24hrs as well and are helpful.
Snippets from class bellow:
private function newSub(){
$fields = array(
'a' => 'rec_new',
'tkn' => $this->tkn,
'email' => $this->apiEmail,
'z' => $this->domain,
'type' => 'A',
'name' => $this->subName,
'content' => $this->content,
'ttl' => 1
);
//url-ify the data for the POST
foreach($fields as $key=>$value){
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, 'https://www.cloudflare.com/api_json.html');
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$response = curl_exec($ch);
//close connection
curl_close($ch);
$response = json_decode($response,true);
if(!$response || $response['result'] != 'success'){
$responseError = $response['msg'];
// ERROR Handling
}else{
// Set rec_id for from the nw A record
$this->rec_id = $response['response']['rec']['obj']['rec_id'];
// Activate
$this->makeActive();
}
}
private function makeActive(){
$request['a'] = 'rec_edit';
$request['tkn'] = $this->tkn;
$request['email'] = $this->apiEmail;
$request['z'] = $this->domain;
$request['id'] = $this->rec_id;
$request['type'] = 'A';
$request['name'] = $this->subName;
$request['content'] = $this->content;
$request['service_mode'] = '1';// Make active
$request['ttl'] = '1';
$response = #json_decode(file_get_contents('https://www.cloudflare.com/api_json.html?' . http_build_query($request)), true);
//var_dump($response); die;
if(!$response || $response['result'] != 'success'){
$responseError = $response['msg'];
// ERROR Handling
}
}
Hope that this helps someone.

How to get all products of a Shopify shop?

In my theme development, I don't find the way to get all the products of my shop.
Although, I can retrieve all the collections with the variable collections (exemple: {% for c in collections %}).
Check this url: https://help.shopify.com/en/themes/customization/collections/change-catalog-page
Like magic... all your products...
Get all products at once or to run a query(API Request) for all products in shopify store :
using this app is more managed -> https://github.com/phpish/shopify_private_app-skeleton so, my solution below is based on this app or you can relate the solution with your solution as well
<?php
session_start();
require __DIR__.'/vendor/autoload.php';
use phpish\shopify;
require __DIR__.'/conf.php';
$shopify = shopify\client(SHOPIFY_SHOP, SHOPIFY_APP_API_KEY, SHOPIFY_APP_PASSWORD, true);
try
{
$products = $shopify('GET /admin/products/count.json', array('published_status'=>'published'));
$totalproducts = $shopify('GET /admin/products/count.json', array('published_status'=>'published'));
$limit = 50;
$totalpage = ceil($totalproducts/$limit);
for($i=1; $i<=$totalpage; $i++){
$products = $shopify('GET /admin/products.json?'.$limit.'=50&page='.$i, array('published_status'=>'published'));
foreach($products as $product){
//do anything at once for all the products in store
}
}
}
catch (shopify\ApiException $e)
{
//
}
Summary : The idea is to retrieve with page=x as parameter. after calculating the number of pages we will have with specified limit i.e 50 at one time fetch.

Issue with retrieving Magento Frontend Session

I am trying to retrieve the customer's login status from Flex application using AMF call to the Magento Customer API :
Mage::app('default');
$session = Mage::getSingleton('customer/session', array('name'=>'frontend') );
$sessId= $session->getSessionId();
if($session->isLoggedIn()) {
$name = "Hi ". Mage::getModel('customer/session')->getCustomer()->getName();
return 'true' . $name;
}
else{
return 'false ' . $sessId;
}
Only the PHP session ID is returned:
PHPSESSID=i5s1gcemc6r8uquadc4rsk9ou5
But the user is logged into the below ID
frontend=3qdcimcdp7nq4bi8jlovqmnq61
Let me know if I am missing something here.
Use the following code to get the customer ID
Mage::getSingleton('core/session', array('name' => 'frontend'));
$customer = Mage::getSingleton('customer/session',array('name' => 'frontend'));
echo $customerId = $customer->getCustomer()->getId();