WooCommerce Webhooks JSON parse using PHP Object - Array - php

I create a PHP script that receive an hooks from WooCommerce, makes PDF with received data and send an e-mail, but I have a problem parsing the JSON data...
This is the JSON:
{"id":128705,"parent_id":0,"number":"128705","order_key":"wc_order_5ae3648deddcd","created_via":"checkout","version":"3.3.5","status":"on-hold","currency":"EUR","date_created":"2018-04-27T19:57:33","date_created_gmt":"2018-04-27T17:57:33","date_modified":"2018-04-27T19:57:34","date_modified_gmt":"2018-04-27T17:57:34","discount_total":"0","discount_tax":"0","shipping_total":"0","shipping_tax":"0","cart_tax":"0","total":"50","total_tax":"0","prices_include_tax":false,"customer_id":7,"customer_ip_address":"79.43.191.213","customer_user_agent":"mozilla\/5.0 (x11; linux x86_64) applewebkit\/537.36 (khtml, like gecko) chrome\/62.0.3202.89 safari\/537.36","customer_note":"","billing":{"first_name":"Nicola","last_name":"Giada","company":"","address_1":"V","address_2":"","city":"CANIC","state":"RA","postcode":"48018","country":"IT","email":"ggggggg#gmail.com","phone":"30002222"},"shipping":{"first_name":"","last_name":"","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":""},"payment_method":"bacs","payment_method_title":"Bonifico bancario","transaction_id":"","date_paid":null,"date_paid_gmt":null,"date_completed":null,"date_completed_gmt":null,"cart_hash":"dba69b53a4a39c58c83b3e557e818bb7","meta_data":[{"id":1383502,"key":"_billing_data","value":"00\/00\/1990"},{"id":1383503,"key":"_billing_codice_fiscale","value":"GDDLLLL333232"},{"id":1383504,"key":"_billing_socio","value":"Sono gi\u00e0 Socio"},{"id":1383505,"key":"_billing_dati","value":"Acconsento"},{"id":1383506,"key":"billing_data","value":"00\/00\/1990"},{"id":1383507,"key":"billing_codice_fiscale","value":"GDDLLLL333232"},{"id":1383508,"key":"billing_socio","value":"Sono gi\u00e0 Socio"},{"id":1383509,"key":"billing_dati","value":"Acconsento"}],"line_items":[{"id":94,"name":"Object buyed XXXX 2018","product_id":128683,"variation_id":128684,"quantity":1,"tax_class":"","subtotal":"40","subtotal_tax":"0","total":"40","total_tax":"0","taxes":[],"meta_data":[{"id":883,"key":"corso","value":"Object NUED"}],"sku":"","price":40},{"id":95,"name":"SECOND OBJECT","product_id":126454,"variation_id":0,"quantity":1,"tax_class":"","subtotal":"10","subtotal_tax":"0","total":"10","total_tax":"0","taxes":[],"meta_data":[],"sku":"","price":10}],"tax_lines":[],"shipping_lines":[],"fee_lines":[],"coupon_lines":[],"refunds":[]}
And this is the piece of my PHP where I retrieve information from the JSON:
/* Gestione dei dati via JSON */
$year = date('Y'); //Anno validità associativa
$secret = 'xxxxx'; //La chiave per il Webhook generata da Woocommerce
$JSON = file_get_contents('php://input');
$data = json_decode($JSON);
$sig = base64_encode(hash_hmac('sha256', $data, $secret, true));
if ($sig != $header_sig) print 'Firma invalida'; //Controllo la firma di sicurezza. Mettere die invece di print.
$nome = $data->billing->first_name;
$cognome = $data->billing->last_name;
$nato_luogo = '';
$prov = $data->billing->state;
$cap = $data->billing->postcode;
$indirizzo = $data->billing->address_1;
//$indirizzo .= $data->billing->address_2;
$tel = $data->billing->phone;
$email = $data->billing->email;
$data = date('d/m/Y'); //Data sottoscrizione scheda
$residenza = $data->billing->city;
//Valori dentro i meta_data personalizzati
foreach ($data->meta_data as $datum) {
if ($datum->key == "_billing_data") $nato_data = $datum->value;
if ($datum->key == "_billing_codice_fiscale") $CF = $datum->value;
if ($datum->key == "_billing_socio") $checksocio = $datum->value;
}
if($check_socio == 'S\u00ec') print 'Giá socio';
My problem is getting values inside "meta_data", the: foreach isn't working at all.
Thanks.

The error was in naming the variable $data ... TYPO error. Thanks.

Related

Not get info of coingecko API

I´m forking this repo https://github.com/FundacionPesetacoin/Pesetacoin_WooCommerce-Plugin and working fine. But when change the API for catch the price in other Site, not update
I try some differents links of API and make same.
Original code get info of his private API, and I want use other public API.
With original code, API show this info:
{"status" : "success" , "message" : "null", "ptc_btc" : "0.00000083", "btc_usd" : "5070.29", "btc_eur" : "4505.46", "supply" : "138188628.56442260", "ptc_eur" : "0.00373953", "ptc_usd" : "0.00420834" , "date" : "2019-04-13 10:20:07"}
and get "ptc_eur" of API for shows in shoppping cart.
Now I want use the new API of other site https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur than shows this info:
{"reecore":{"eur":0.0046564}}
I want use only the "eur" data , same the original code use the "ptc_eur" but dont work.
Sorry for my english.
ORIGINAL CODE:
//precio en PesetaCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "http://nodos.pesetacoin.info/api/api.php";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_ptc= $pesetas['ptc_eur'];
$ptc= $euros/$valor_ptc;
$ptc= round($ptc, 2);
//precio en PesetaCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "ptc") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$ptc."</b> de Pesetacoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
NEW CODE:
//precio en ReecoreCoins
global $woocommerce;
$euros= $woocommerce->cart->total;
$xaxa= "https://api.coingecko.com/api/v3/simple/price?ids=reecore&vs_currencies=eur";
$data = file_get_contents($xaxa);
$pesetas = json_decode($data, true);
$valor_reex= $pesetas['eur'];
$reex= $euros/$valor_reex;
$reex= round($reex, 2);
//precio en ReecoreCoins
$pagos= array();
$metodo= $order->get_payment_method();
$i = -1;
foreach ( $this->account_details as $account ) {
$i++;
$pagos[$i]=
$pagos[$i]= esc_attr( wp_unslash( $account['hash_name'] ) );
}
$cont= rand(0, $i);
if($metodo == "reex") {
$description= "<span style='font-size:14px'>Para completar el pedido, debe enviar la cantidad <b>".$reex."</b> de Reecorecoin a la siguiente dirección: <b>";
$description.= $pagos[$cont];
$description.="</b><br>Una vez se reciba la transacción se enviará el pedido.</span>";
echo wpautop(wptexturize($description));
}
}
It's because the now Coingecko API return a nested JSON which is simply a JSON file with a fairly big portion of its values being other JSON objects.
Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.
Using Phrase, keys will be stored by separating levels with a dot.
The new API returns a nested JSON object, where you need two steps to access the desired value:
$valor_reex= $pesetas['reecore']['eur'];
You might want to use ready library for this. Like this one https://github.com/npabisz/coingecko-api.
Install via composer:
composer require npabisz/coingecko-api
And then get your reecore price by:
$client = new \CoinGecko\Client();
$data = $client->Simple->Price->get([
'ids' => 'reecore',
'vs_currencies' => 'eur',
]);
$reecorePrice = $data['reecore']['eur'] ?? null;

How to conect php with tally?

I want to connect php with tally and I want to store ledger in tally with php any idea?
I got reference from different site like :
1) http://www.tallysolutions.com/website/html/tallydeveloper/integration-capabilities.php
2)http://stackoverflow.com/questions/15717941/how-to-insert-data-into-tally-using-php
But it doesn't fulfill my requirement.
Thanks in advance
It's may help you
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
$envelope = $doc->appendChild($doc->createElement('ENVELOPE'));
//Header Section
$header = $envelope->appendChild($doc->createElement('HEADER'));
$version = $header->appendChild($doc->createElement('VERSION','6.3'));
$import = $header->appendChild($doc->createElement('TALLYREQUEST','Import'));
$type = $header->appendChild($doc->createElement('TYPE','Data'));
$id = $header->appendChild($doc->createElement('ID','All Masters'));
//End Header Section
//Body Section
$body = $envelope->appendChild($doc->createElement('BODY'));
$desc = $body->appendChild($doc->createElement('DESC'));
$static_var = $desc->appendChild($doc->createElement('STATICVARIABLES'));
$dup_combine = $static_var->appendChild($doc->createElement('IMPORTDUPS','##DUPCOMBINE'));
$data = $body->appendChild($doc->createElement('DATA'));
$tally_msg = $data->appendChild($doc->createElement('TALLYMESSAGE'));
//Ledger Data
foreach($contacts_data as $key => $value){
$ledger = $tally_msg->appendChild($doc->createElement('LEDGER'));
$parent=$ledger->appendChild($doc->createElement('PARENT',($value['contacts_types_id']=='1')?'Sundry Debtors':'Sundry Creditors'));
$name=$ledger->appendChild($doc->createElement('NAME',trim(str_replace( "&"," AND ",$value['name']))));
$address=$ledger->appendChild($doc->createElement('ADDRESS',trim(str_replace( "&"," AND ",$value['address']))));
$state=$ledger->appendChild($doc->createElement('STATENAME',trim(str_replace( "&"," AND ",$value['state_name']))));
$pincode=$ledger->appendChild($doc->createElement('PINCODE',$value['pincode']));
/*$ledger_contact=$ledger->appendChild($doc->createElement('LEDGERCONTACT',trim(str_replace( "&"," AND ",$value['contact_person']))));
$phone=$ledger->appendChild($doc->createElement('LEDGERPHONE',$value['phone']));
$fax=$ledger->appendChild($doc->createElement('LEDGERFAX',$value['fax']));
$mobile_no=$ledger->appendChild($doc->createElement('MOBILENO',$value['mobile_no']));
$sales_tax_no=$ledger->appendChild($doc->createElement('SALESTAXNO','23456789'));
$pan_no=$ledger->appendChild($doc->createElement('PANNO','453456789'));*/
$o['contacts_id'][]=$value['id'];
}
//End Ledger and Body Section
//Write the XML nodes
$fp = fopen(public_path()."/xml/import_tally/ledger.xml","wb");
if(fwrite($fp,$doc->saveXML())){
$o['tally_rslt']= shell_exec("curl -X POST tally_server_ip:port --data #".public_path()."/xml/import_tally/ledger.xml");
$o['modified_result']=strpos(preg_replace('/[0-9]+/', '', $o['tally_rslt']),'exists');
}
fclose($fp);
return $o;

PHP [function.file-get-contents]: Failed to open stream

This is really annoying me, the php script was working and returning the weather from open weather map but literally all of a sudden the php script takes forever to execute and the following error is produced:
Warning: file_get_contents(http://api.openweathermap.org/data/2.5/weather?lat=&lon=&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070) [function.file-get-contents]: failed to open stream: Connection timed out in /xxx/xxx/public_html/fullweather.php on line 15
Any help would be appreciated. The php script can be viewed below. Only the beginning is important (first 18 lines) but I have included the full thing.
<?php
$lat = $_POST["latitude"];
$lon = $_POST["longitude"];
$url="http://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
// Make call with cURL
$session = curl_init($url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
$json=file_get_contents($url);
$data=json_decode($json,true);
class weatherdata
{
public $temp = "";
public $weather = "";
public $clouds = "";
public $area = "";
public $humidity = "";
public $humidpressure = "";
public $weatherdesc = "";
public $tempmin = "";
public $tempmax = "";
public $windspeed = "";
public $winddirec = "";
}
$data1 = $data['main']['temp'];
$data2 = $data['weather'][0]['main'];
$data3 = $data['clouds']['all'];
$data4 = $data['name'];
$data5 = $data['main']['humidity'];
$data6 = $data['main']['pressure'];
$data7 = $data['weather'][0]['description'];
$data8 = $data['main']['temp_min'];
$data9 = $data['main']['temp_max'];
$data10 = $data['wind']['speed'];
$data12 = $data['wind']['deg'];
$weatherdata = new weatherdata();
$weatherdata->temp = $data1;
$weatherdata->weather = $data2;
$weatherdata->clouds = $data3;
$weatherdata->area = $data4;
$weatherdata->humidity = $data5;
$weatherdata->humidpressure = $data6;
$weatherdata->weatherdesc = $data7;
$weatherdata->tempmin = $data8;
$weatherdata->tempmax = $data9;
$weatherdata->windspeed = $data10;
$weatherdata->winddirec = $data12;
$output[] = $weatherdata;
print(json_encode($output));
?>
I think the API was just down, cause the link is working for me right now.
Try one more time.
May be the API had change it's url by the time. Try to check the documentation for any updated information. I think that they could change it and your code couldnt find because this $url doesn't exist anymore.
i added https instead of http in url and it worked.
so maybe change http in url like this url.
$url="https://api.openweathermap.org/data/2.5/weather?lat=".$lat."&lon=".$lon."&units=metric&cnt=7&lang=en&key=f38a36af9e4965dd5192ba4282abe070";
Edit
Also you should not show your api key to anyone as some one can use it.

Using Zend_Http_Client to send json POST

I'm trying to send a json object as a POST command using the following:
$uri = "http://amore-luce.com/product_create";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://amore-luce.com/product_create');
// set some parameters
$client->setParameterPost('product', $json);
// POST request
$response = $client->request(Zend_Http_Client::POST);
When I view the $json the data is there and all looks good - however the POST is not sending the json data. I'm capturing it using a simple email form that should send me the response:
<?php
$webhookContent = "";
$ref = "";
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhookContent .= fread($webhook, 4096);
}
fclose($webhook);
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
foreach ($headers as $header => $value) {
$ref .= "$header: $value <br />\n";
}
$post = file_get_contents('php://input');
$to = "address#my-email.com"; //the address the email is being sent to
$subject = "This is the subject"; //the subject of the message
$msg = "This is the message - Webhook content: ".$webhookContent." This is url: ".$ref; //the message of the email
mail($to, $subject, $msg, 'From: PHP Scriptv2 <noreply#domain.com>'); //send the email.
echo ($_SERVER['HTTP_REFERER']."<br>".$_SERVER['REQUEST_URI']);
?>
This page works with other json POST requests I've sent to it. I'm fairly new at sending POST requests so any help would be greatly appreciated.
Try change :
$client->setParameterPost('product', $json);
to :
$client->setHeaders('Content-type','application/json');
$client->setParameterPost('product', $json);
or use:
$client->setRawData($json, 'application/json');
So Update / Answer changing how I did it to these lines of code:
$uri = "http://requestb.in/p6p4syp6";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
$client = new Zend_Http_Client($uri);
$client->setRawData($json, null)->request('POST');
Changing the SetRawData($json, null) was the bit - using SetRawDate($json, 'application/json') caused it to fail.
Thanks Voodoo417 - I'll also try your suggestion and see if that lets me set the correct type

How to retrieve xml from my webservice in php

I'm using a webservice in php here :
http://cdt33.tourinsoft.com/soft/RechercheDynamique/Syndication/controle/syndication2.asmx
You can test for example getListing with idModule = dafda774-317d-4b5f-bb8b-33e5977dc13c, and click on invoke
I'm trying to retrieve this result (XML) in php. But i have no idea how to do this.
If i use getListing like :
$client = new SoapClient("http://cdt33.tourinsoft.com/soft/RechercheDynamique/Syndication/controle/syndication2.asmx?wsdl");
echo "GET LISTING";
$getListing = $client->getListing(
array (
'idModule' => "dafda774-317d-4b5f-bb8b-33e5977dc13c"));
echo("<pre>");
print_r($getListing);
echo("</pre>");
Result is something like that :
stdClass Object
(
[getListingResult] => stdClass Object
(
[schema] =>
[any] =>
HOTAQU03301V3EZB2005-06-29T00:00:00.0000000+02:002012-06-28T14:43:44.0000000+02:0074HOTHôtellerie1e9eb500-e0c9-4a53-b6a5-0b36faa63ed4true 2 étoiles Français www.hotel-lenovel.com +33 5 57 52 26 47 7 oui En centre ville$ Au bord de la mer Ascenseur$ Salon 22 -1.164866 Au coeur d'Arcachon, à deux pas de la gare, du théâtre de l'Olympia et de l'Office du Tourisme, le Novel bénéficie d'une situation privilégiée. Les chambres sont chaleureuses et douillettes pour un séjour....... ETC
How can i retieve XML ?? Thanks you !
Here is sometihng to try out, run it and check the source code for the page, it should contain the xml file. SOAP is just a fancy way of doing a post.
<?php
function smartpost($type,$host,$port='80',$path='/',$data='') {
$d="";
$str="";
$_err = 'lib sockets::'.__FUNCTION__.'(): ';
switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port');
if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1);
$fp = fsockopen($host,$port,$errno,$errstr,$timeout=30);
if(!$fp) die($_err.$errstr.$errno); else {
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($str)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $str."\r\n\r\n");
while(!feof($fp)) $d .= fgets($fp,4096);
fclose($fp);
$result = explode("\r\n\r\n", $d, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
} return array($header, $content);
}
list($header, $content) = smartpost('http','cdt33.tourinsoft.com','80','/soft/RechercheDynamique/Syndication/controle/syndication2.asmx/getListingByIDs',array('idModule'=>'dafda774-317d-4b5f-bb8b-33e5977dc13c','ObjetTourCode' => '','IDs' => ''));
print($content);
?>
assuming you are using standard PHP SoapClient, try using
$client->__getLastRequestHeaders()
(http://www.php.net/manual/en/soapclient.getlastresponse.php)
According to maual, you should also set trace option to true on SoapClient:
$client = new SoapClient("http://cdt33.tourinsoft.com/soft/RechercheDynamique/Syndication/controle/syndication2.asmx?wsdl", array('trace' => true));
Regards, Jakub Derda
class ABRSoapClient extends SoapClient
{
$result = "";
function __doRequest($request, $location, $action, $version)
{
$result = parent::__doRequest($request, $location, $action, $version);
return $result;
}
}
Instead of creating object of SoapClient, Create object of ABRSoapClient, Here $result is your XML string from Web-Service.
You can access that variable using $client->result;

Categories