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

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.

Related

Shopify API getting order by name or order_number

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

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

PDO row doesn't exist?

Below is my code:
<?php
$url = $_GET['url'];
$wordlist = array("Www.", "Http://", "Http://www.");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$url = preg_replace($wordlist, '', $url);
?>
<?php
$oDB = new PDO('mysql:dbname=mcnsaoia_onsafe;host=localhost;charset=utf8', 'mcnsaoia_xx', 'PASSWORD');
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt=ja");
$hStmt->execute(array('hjemmside' => $url));
if( $row = $hStmt->fetch() ){
echo "EXIST";
}else{
echo "NOT EXIST";
}
?>
My problem is that it says NOT EXIST, because I know that there is a row which should be found with the following query:
SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt=ja
So why does it say not exist? I have absolutely no idea :(
Instead of
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside
AND godkendt=ja");
try
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside
AND godkendt='ja'");
The left is most likely a column and the right side is a string? I don't speak your language, but this is the first thing coming to my mind.
You should surround with quotes your not integer variable in your query
AND godkendt='ja'
Or maybe let pdo deal with it
$hStmt=$oDB->prepare("SELECT * FROM users WHERE hjemmside = :hjemmside AND godkendt = :ja");
$hStmt->execute(array(':hjemmside' => $url, ':ja' => 'ja'));
//^ i added : for placeholder here, you missed it
I would also rather check if rows are returned
if($hStmt->$eowVount() > 0){
$row = $hStmt->fetch()
echo "EXIST";
}else{
echo "NOT EXIST";
}

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();

Piwik plugins

I'm building a plugin, and I want to have a Subtable, so that my users can click on the overview data, and display the data from there.
Following the code that I've been able to glean:
public function getCompanyList($idSite, $period, $date )
{
$dataTable = new Piwik_DataTable();
$query = Piwik_Query("SELECT cl.id, cl.company_name name, sf.id sf_id FROM sitedb.company_lookup cl INNER JOIN sitedb.storefronts sf ON cl.id = sf.company_id");
while ($row = $query->fetch()) {
$piwik_row = new Piwik_DataTable_Row;
$piwik_row->setSubTable( $this->getProductsForCompany($idSite, $period, $date, $row['id']) );
$piwik_row->setColumns( array('id' => $row['id'], 'Company Name' => $row['name']) );
$dataTable->addRow($piwik_row);
}
return $dataTable;
}
public function getProductsForCompany($idSite, $period, $date, $company_id )
{
if (!defined('PIWIK_ENABLE_DISPATCH')) define('PIWIK_ENABLE_DISPATCH', false);
if (!defined('PIWIK_ENABLE_ERROR_HANDLER')) define('PIWIK_ENABLE_ERROR_HANDLER', false);
require_once PIWIK_INCLUDE_PATH . "/index.php";
require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
Piwik_FrontController::getInstance()->init();
$request = new Piwik_API_Request('
method=Actions.getActions
&idSite=' . $idSite . '
&date=' . $date . '
&period=' . $period . '
&format=PHP
&filter_column=label
&filter_pattern=product.php
&filter_sort_column=nb_visits
&filter_sort_order=desc
&token_auth=anonymous
');
$result = $request->process();
// contains an array of visits to storefront.php
$result = unserialize($result);
$query = Piwik_Query("SELECT sp.product_id id, sp.name, sp.storefront_id sf_id, cl.company_name FROM sitedb.storefront_products sp INNER JOIN sitedb.storefronts sf ON sp.storefront_id = sf.id INNER JOIN sitedb.company_lookup cl ON sf.company_id = cl.id WHERE cl.id = {$company_id}");
$dataTable = new Piwik_DataTable();
while ($row = $query->fetch()) {
// piwik returns & escaped to & -- make sure that's what you use to search!
$this->array_search_in_level("/product.php?id=" . $row['id'] . "&sf_id=" . $row['sf_id'], $result, 'label', $storefront_array, 1);
if (is_array($storefront_array) && array_key_exists('nb_visits', $storefront_array)) {
$piwik_row = new Piwik_DataTable_Row;
$piwik_row->setColumns( array('id' => $row['id'], 'Product Name' => $row['name'], 'Page Views' => $storefront_array['nb_visits']) );
$dataTable->addRow($piwik_row);
}
}
return $dataTable;
}
However, the subTable never shows up. Am I doing something wrong?
Maybe you need to add the 'expanded=1' parameter to your API request?
http://piwik.org/docs/analytics-api/reference/#toc-optional-api-parameters
If you are looking for example code on how to use the piwik framework to plot custom data in plugins, it looks like they have a bit of doc: Piwik plugins docs