This is our class that is called
<?php
class Nest
{
public $debug;
private $username;
private $password;
private $cookieFile;
public function __construct($username, $password, $debug = false)
{
// Set the properties
$this->debug = $debug;
$this->username = $username;
$this->password = $password;
$this->useragent = 'Nest/1.1.0.10 CFNetwork/548.0.4';
$this->cookieFile = tempnam('/tmp', 'nest-cookie');
// Login
$response = $this->curlPost('https://home.nest.com/user/login', 'username=' . urlencode($username) . '&password=' . urlencode($password));
if (($json = json_decode($response)) === false)
throw new Exception('Unable to connect to Nest');
// Stash information needed to make subsequence requests
$this->access_token = $json->access_token;
$this->user_id = $json->userid;
$this->transport_url = $json->urls->transport_url;
}
public function house_state_set($state)
{
switch ($state)
{
case 'away':
$away = true;
break;
case 'home':
$away = false;
break;
default:
throw new Exception('Invalid state given: "' . $state . '"');
}
$status = $this->status_get();
$structure_id = $status->user->{$this->user_id}->structures[0];
$payload = json_encode(array('away_timestamp' => time(), 'away' => $away, 'away_setter' => 0));
return $this->curlPost($this->transport_url . '/v2/put/' . $structure_id, $payload);
}
public function house_state_get()
{
$status = $this->status_get();
$structure = $status->user->{$this->user_id}->structures[0];
list (,$structure_id) = explode('.', $structure);
return ($status->structure->{$structure_id}->away ? 'away' : 'home');
}
public function temperature_set(&$temp)
{
$status = $this->status_get();
$structure = $status->user->{$this->user_id}->structures[0];
list (,$structure_id) = explode('.', $structure);
$device = $status->structure->{$structure_id}->devices[0];
list (,$device_serial) = explode('.', $device);
$temperature_scale = $status->device->{$device_serial}->temperature_scale;
if ($temperature_scale == "F")
{
$target_temp_celsius = (($temp - 32) / 1.8);
}
else
{
$target_temp_celsius = $temp;
}
$payload = json_encode(array('target_change_pending' => true, 'target_temperature' => $target_temp_celsius));
return $this->curlPost($this->transport_url . '/v2/put/shared.' . $device_serial, $payload);
}
public function status_get()
{
$response = $this->curlGet($this->transport_url . '/v2/mobile/user.' . $this->user_id);
if (($json = json_decode($response)) === false)
throw new Exception('Unable to gather the status from Nest');
return $json;
}
private function curlGet($url, $referer = null, $headers = null)
{
$headers[] = 'Authorization: Basic ' . $this->access_token;
$headers[] = 'X-nl-user-id:' . $this->user_id;
$headers[] = 'X-nl-protocol-version: 1';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
if(!is_null($referer)) curl_setopt($ch, CURLOPT_REFERER, $referer);
if(!is_null($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($ch, CURLOPT_VERBOSE, true);
$html = curl_exec($ch);
if(curl_errno($ch) != 0)
{
throw new Exception("Error during GET of '$url': " . curl_error($ch));
}
$this->lastURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$this->lastStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $html;
}
private function curlPost($url, $post_vars = '', $referer = null)
{
if (isset($this->access_token)) $headers[] = 'Authorization: Basic ' . $this->access_token;
if (isset($this->user_id)) $headers[] = 'X-nl-user-id:' . $this->user_id;
$headers[] = 'X-nl-protocol-version: 1';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vars);
if(!is_null($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($ch, CURLOPT_VERBOSE, true);
$html = curl_exec($ch);
$this->lastURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$this->lastStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $html;
}
}
and is called with:
<?php
$new = $_GET['t'];
include_once('nest.php');
$nest = new Nest('usr', 'pwd');
$nest->temperature_set($new);
?>
If I replace $new with a number and then call the function it works but not in it current form. I have tried using the class to call outside variables, tried to just call but cant figure where and why its not working.
I suspect it is not working because your device is configured to use Celsius.
PHP is a dynamically typed language, as is JavaScript, but sometimes people forget that both will change types based on context (and sometimes the type conversion will have unexpected results).
All $_REQUEST variables are strings. Try changing:
$target_temp_celsius = $temp;
To
$target_temp_celsius = $temp + 0;
(JSON is strongly typed)
Related
I have spend much of time on it, but did not found any working solution ...
I have tried the following code .. but always else case is running "didnt find login form1"
I have tried another coders11 inplemented api but it was also deprecated...
I found many other solutions but not in php ... I am looking for solution in php...
class googleAlerts{
public function createAlert($alert){
$USERNAME = 'XXXXXX#gmail.com';
$PASSWORD = 'YYYYYY';
$COOKIEFILE = 'cookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);
$formFields = $this->getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
if (strpos($result, '<title>') === false) {
return false;
} else {
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/create');
curl_setopt($ch, CURLOPT_POST, 0);
$result = curl_exec($ch);
//var_dump($result);
$result = $this->getFormFieldsCreate($result);
$result['q'] = $alert;
$result['t'] = '7';
$result['f'] = '1';
$result['l'] = '0';
$result['e'] = 'feed';
unset($result['PersistentCookie']);
$post_string = '';
foreach($result as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/manage');
$result = curl_exec($ch);
if (preg_match_all('%'.$alert.'(?=</a>).*?<a href=[\'"]http://www.google.com/alerts/feeds/([^\'"]+)%i', $result, $matches)) {
return ('http://www.google.com/alerts/feeds/'.$matches[1][0]);
} else {
return false;
}
}
}
private function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
private function getFormFieldsCreate($data)
{
if (preg_match('/(<form.*?name=.?.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form1');
}
}
private function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
}
$alert = new googleAlerts;
echo $alert->createAlert('YOUR ALERT');```
You can't login into google alerts with password and email anymore, you would have to pre-create cookies by login into google alerts and copying them out of the dev console and then passing them as argument when doing a curl request. Check out my google alerts api i have written in php. Maybe that helps you out https://github.com/Trivo25/google-alerts-api-php
I have created an application where my website form data will be stored into a google spreadsheet. It was working fine till yesterday i.e 26/05/2015. But from today i.e 27/05/2015 it suddenly stopped working. And no value is adding into the google spreadsheet.
I have used the below mentioned class for spreadsheet application
spreadsheet.php:
<?php
class spreadsheet {
private $token;
private $spreadsheet;
private $worksheet;
private $spreadsheetid;
private $worksheetid;
public function __construct() {
}
public function authenticate($username, $password) {
$url = "https://www.google.com/accounts/ClientLogin";
$fields = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => $username,
"Passwd" => $password,
"service" => "wise",
"source" => "pfbc"
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if($status == 200) {
if(stripos($response, "auth=") !== false) {
preg_match("/auth=([a-z0-9_\-]+)/i", $response, $matches);
$this->token = $matches[1];
}
}
}
public function setSpreadsheet($title) {
$this->spreadsheet = $title;
}
public function setWorksheet($title) {
$this->worksheet = $title;
}
public function add($data) {
if(!empty($this->token)) {
$url = $this->getPostUrl();
if(!empty($url)) {
$headers = array(
"Content-Type: application/atom+xml",
"Authorization: GoogleLogin auth=" . $this->token,
"GData-Version: 3.0"
);
$columnIDs = $this->getColumnIDs();
if($columnIDs) {
$fields = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
foreach($data as $key => $value) {
$key = $this->formatColumnID($key);
if(in_array($key, $columnIDs))
$fields .= "<gsx:$key><![CDATA[$value]]></gsx:$key>";
}
$fields .= '</entry>';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
}
}
}
}
private function getColumnIDs() {
$url = "https://spreadsheets.google.com/feeds/cells/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full?max-row=1";
$headers = array(
"Authorization: GoogleLogin auth=" . $this->token,
"GData-Version: 3.0"
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if($status == 200) {
$columnIDs = array();
$xml = simplexml_load_string($response);
if($xml->entry) {
$columnSize = sizeof($xml->entry);
for($c = 0; $c < $columnSize; ++$c)
$columnIDs[] = $this->formatColumnID($xml->entry[$c]->content);
}
return $columnIDs;
}
return "";
}
private function getPostUrl() {
$url = "https://spreadsheets.google.com/feeds/spreadsheets/private/full?title=" . urlencode($this->spreadsheet);
$headers = array(
"Authorization: GoogleLogin auth=" . $this->token,
"GData-Version: 3.0"
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status == 200) {
$spreadsheetXml = simplexml_load_string($response);
if($spreadsheetXml->entry) {
$this->spreadsheetid = basename(trim($spreadsheetXml->entry[0]->id));
$url = "https://spreadsheets.google.com/feeds/worksheets/" . $this->spreadsheetid . "/private/full";
if(!empty($this->worksheet))
$url .= "?title=" . $this->worksheet;
curl_setopt($curl, CURLOPT_URL, $url);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status == 200) {
$worksheetXml = simplexml_load_string($response);
if($worksheetXml->entry)
$this->worksheetid = basename(trim($worksheetXml->entry[0]->id));
}
}
}
curl_close($curl);
if(!empty($this->spreadsheetid) && !empty($this->worksheetid))
return "https://spreadsheets.google.com/feeds/list/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full";
return "";
}
private function formatColumnID($val) {
return preg_replace("/[^a-zA-Z0-9.-]/", "", strtolower($val));
}
}
?>
and use it in following way:
include 'spreadsheet.php';
$doc = new spreadsheet();
$doc->authenticate("example#example.com", "example");
$doc->setSpreadsheet("Tester");
$doc->setWorksheet("Sheet1");
$my_data = array("First Name" => "John", "Last Name" => "Doe");
$doc->add($my_data);
Please help me out. Thanks in advance.
The ClientLogin method, which has been deprecated for a number of years, has now been turned off. It will return a 404 when trying to authenticate. You will need to migrate to OAuth for authentication.
See https://developers.google.com/identity/protocols/AuthForInstalledApps
Here is an updated PHP library that uses OAuth - https://github.com/asimlqt/php-google-spreadsheet-client. The author also has a sample project with instructions to generate OAuth access tokens.
I am new to working with api and have been searching for the little tiny piece of code that makes the following snippit possible, but I am having trouble finding it. I have been watching tutorials on jquery, ajax, json, and php but have not found exactly what I need. If someone could show me a simple example of how the request would be constructed from the opening tag of the file to the closing tag it would be very helpful. After I get the data returned I can figure out how to parse and style it for display.
The first piece of code is the example that someone else said they use but I tried it (with my own api key) and I seem to be missing something. The second code is the "Mmjmenu.php" file that I assume needs to be in the same directory as the first php file. Following the code is the error I get.
("my api key" is replacing my actual key)
<?php
require 'API/Mmjmenu.php';
$client = new Mmjmenu('my api key');
$menuItems = $client->menuItems();
$menuItems = json_decode($menuItems, true);
foreach($menuItems['menu_items'] as $item)
{
echo $item['name'];
}
?>
This is the "Mmjmenu.php" file (can be found on git hub):
<?php
class Mmjmenu {
private $domain = 'https://mmjmenu.com/api/v1';
private $active_api_key;
private $active_domain;
private $username;
private $password;
public function __construct($api_key, $active_domain = null, $active_api_key = null) {
$this->setActiveDomain($this->domain, $api_key);
}
public function setActiveDomain($active_domain, $active_api_key) {
$this->active_domain = $active_domain;
$this->active_api_key = $active_api_key;
$this->username = $this->active_api_key;
$this->password = 'x';
}
private function sendRequest($uri, $method = 'GET', $data = '') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://mmjmenu.com/api/v1" . $uri);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
$method = strtoupper($method);
if($method == 'POST')
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
else if ($method == 'PUT')
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
else if($method != 'GET')
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = new StdClass();
$result->response = curl_exec($ch);
$result->code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result->meta = curl_getinfo($ch);
$curl_error = ($result->code > 0 ? null : curl_error($ch) . ' (' . curl_errno($ch) . ')');
curl_close($ch);
if ($curl_error) {
//print('ERROR');
}
return $result;
}
/****************************************************
********************* MENU ITEMS ********************
****************************************************/
public function menuItems() {
$base_url = '/menu_items';
$menuItems = $this->sendRequest($base_url);
return $menuItems->response;
}
public function menuItem($id) {
$base_url = "/menu_items/$id";
$menuItem = $this->sendRequest($base_url);
return $menuItem->response;
}
}
?>
This is the error I get when executing the first file:
Fatal error: Class 'Mmjmenu' not found in /home/...(my directory).../mmtest.php on line 4
I'm trying to use Spreadshirt API to create a product on their platform, but i'm stuck with this weird error:
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/anarchoi/public_html/test.php:102 Stack trace: #0 /home/anarchoi/public_html/test.php(102): SimpleXMLElement->__construct('') #1 {main} thrown in /home/anarchoi/public_html/test.php on line 102
Most of the code is just copied from their wiki so i really don't understand why it doesn't work.
I'm looking for help to understand where the error is coming from and why it is happening.
$productTypeId = "210";
$printTypeId = "17";
$printColorIds = "13,20";
$productTypeAppearanceId = "1";
$productTypePrintAreaId = "4";
$designId = "10438193";
// 1. Get shop data
$shopUrl = "http://api.spreadshirt.com/api/v1/shops/266497";
$ch = curl_init($shopUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$shop = new SimpleXMLElement($result);
$namespaces = $shop->getNamespaces(true);
// 2. Get product type data
$attributes = $shop->productTypes->attributes($namespaces['xlink']);
$productTypeUrl = $attributes->href . "/" . $productTypeId;
$ch = curl_init($productTypeUrl);
// echo "<br>$productTypeUrl<br>";
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$productType = new SimpleXMLElement($result);
// 3. Get design data
$attributes = $shop->designs->attributes($namespaces['xlink']);
$designUrl = $attributes->href . "/" . $designId;
$ch = curl_init($designUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$design = new SimpleXMLElement($result);
// 4. Prepare product
// get positioning data for selected product type
$printArea = null;
foreach ($productType->printAreas->printArea as $current) {
if ($current['id'] == $productTypePrintAreaId) {
$printArea = $current;
}
}
$product = new SimpleXMLElement(getFileData("product.xml"));
$product->productType['id'] = $productTypeId;
$product->appearance['id'] = $productTypeAppearanceId;
$configuration = $product->configurations->configuration;
$configuration->printArea['id'] = $productTypePrintAreaId;
$configuration->printType['id'] = $printTypeId;
$configuration->offset->x =
((doubleval($printArea->boundary->size->width) - doubleval($design->size->width)) / 2);
$configuration->offset->y =
((doubleval($printArea->boundary->size->height) - doubleval($design->size->height)) / 4);
$image = $product->configurations->configuration->content->svg->image;
$image['width'] = $design->size->width;
$image['height'] = $design->size->height;
$image['designId'] = $designId;
$image['printColorIds'] = $printColorIds;
// 5. Create product
$attributes = $shop->products->attributes($namespaces['xlink']);
$productsUrl = $attributes->href;
$header = array();
$header[] = createSprdAuthHeader("POST", $productsUrl);
$header[] = "Content-Type: application/xml";
$ch = curl_init("$productsUrl"."?fullData=true");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $product->asXML());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$productUrl = parseHttpHeaders($result, "Location");
$ch = curl_init($productUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$product = new SimpleXMLElement($result);
$resource = $product->resources->resource[0];
$attributes = $resource->attributes($namespaces['xlink']);
echo '<html><body>';
echo 'Product available at: ' . $productUrl . '</br>';
echo 'Product image is available at: ' . $attributes->href . '</br>';
echo '<img src="' . $attributes->href . '?width=1000"/>';
echo '</body></html>';
function createSprdAuthHeader($method, $url) {
$apiKey = "***";
$secret = "***";
$time = time()*1000;
$data = "$method $url $time";
$sig = sha1("$data $secret");
return "Authorization: SprdAuth apiKey=\"$apiKey\", data=\"$data\", sig=\"$sig\"";
}
function parseHttpHeaders( $header, $headername ) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/('.$headername.'): (.+)/m', $field, $match) ) {
return $match[2];
}
}
return $retVal;
}
function getFileData($file) {
$fp = fopen($file, "r");
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
}
product.xml = https://www.ni-dieu-ni-maitre.com/product.xml
I stumbled upon similar issue when implementing Spreadshirt, looks like their API server is sending (at least some) content gzipped regardless of any Accept-Encoding headers. You can tell that it's your case by var_dumping the string before it's passed to SimpleXMLElement (as suggested by others) – if it's gibberish, it's very possible you have the same issue as I did.
Setting the curl option of CURLOPT_ENCODING to an empty string ('') fixed that for me – it "magically" turned on ungzipping the response (see man page for curl_setopt() for more information).
Is it currently supported that I send toast push notifications to a Windows 8 store app using php server side script like on Windows Phone.
I was able to find the below php code to send push notifications to a Windows 8 store app but doesn't seem to support toast notifications.
<?php
class WPNTypesEnum{
const Toast = 'wns/toast';
const Badge = 'wns/badge';
const Tile = 'wns/tile';
const Raw = 'wns/raw';
}
class WPNResponse{
public $message = '';
public $error = false;
public $httpCode = '';
function __construct($message, $httpCode, $error = false){
$this->message = $message;
$this->httpCode = $httpCode;
$this->error = $error;
}
}
class WPN{
private $access_token = '';
private $sid = '';
private $secret = '';
function __construct($sid, $secret){
$this->sid = $sid;
$this->secret = $secret;
}
private function get_access_token(){
if($this->access_token != ''){
return;
}
$str = "grant_type=client_credentials&client_id=$this->sid&client_secret=$this->secret&scope=notify.windows.com";
$url = "https://login.live.com/accesstoken.srf";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$str");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output);
if(isset($output->error)){
throw new Exception($output->error_description);
}
$this->access_token = $output->access_token;
}
public function build_tile_xml($title, $img){
return '<?xml version="1.0" encoding="utf-16"?>'.
'<tile>'.
'<visual lang="en-US">'.
'<binding template="TileWideImageAndText01">'.
'<image id="1" src="'.$img.'"/>'.
'<text id="1">'.$title.'</text>'.
'</binding>'.
'</visual>'.
'</tile>';
}
public function post_tile($uri, $xml_data, $type = WPNTypesEnum::Tile, $tileTag = ''){
if($this->access_token == ''){
$this->get_access_token();
}
$headers = array('Content-Type: text/xml', "Content-Length: " . strlen($xml_data), "X-WNS-Type: $type", "Authorization: Bearer $this->access_token");
if($tileTag != ''){
array_push($headers, "X-WNS-Tag: $tileTag");
}
$ch = curl_init($uri);
# Tiles: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868263.aspx
# http://msdn.microsoft.com/en-us/library/windows/apps/hh465435.aspx
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$response = curl_getinfo( $ch );
curl_close($ch);
$code = $response['http_code'];
if($code == 200){
return new WPNResponse('Successfully sent message', $code);
}
else if($code == 401){
$this->access_token = '';
return $this->post_tile($uri, $xml_data, $type, $tileTag);
}
else if($code == 410 || $code == 404){
return new WPNResponse('Expired or invalid URI', $code, true);
}
else{
return new WPNResponse('Unknown error while sending message', $code, true);
}
}
}
?>