Json data get from API URL (using curl) - php

The online service "eTermin" provides an API Url which outputs reviews of my service.
I tried it with this code but only got a bad request and an error:
$service_url = 'https://www.etermin.net/api/rating/';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false); // DEBUGGING set to true
$curl_response = curl_exec($curl);
echo print_r($curl_response); // test the JSON array
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response, true);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}

The eTermin FAQ did not provide all the information needed. In order to GET or POST you need to send a publickey, a salt and an encoded signature in the Header.
So this is the solution to GET the ratings of my eTermin account (the return is not formatted yet!):
$publicKey = "[publicKey]";
$secretKey = "[secretKey]";
// Generates a random string of ten digits
$salt = mt_rand();
// Computes the signature by hashing the salt with the secret key as the key
$signature = hash_hmac('sha256', $salt, $secretKey, true);
// base64 encode
$encodedSignature = base64_encode($signature);
// CURL GET REQUEST
$service_url = 'https://www.etermin.net/api/rating/';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'publickey:'.$publicKey,
'salt:'.$salt,
'signature:'.$encodedSignature
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HEADER, true);
$curl_response = curl_exec($curl);
$curl_response = json_decode($curl_response);
echo print_r($curl_response);
This is what it returns:
Array ( [0] => stdClass Object ( [ID] => 60979 [AppointmentExternalID] => XXXXXXX [CustomerFeedback] => Sehr schöner Laden, sehr privat. Wir wurden von zwei Experten gleichzeitig beraten, Preise sind angemessen. Schöne Anzüge. Wir sind zufrieden. [Rating] => 5 [CustomerInfo] => Benjamin (email#something.at, ) [RatingDate] => 2018-01-24T17:21:20.793 [CalendarID] => 46499 [CalendarName] => Kalender [ServiceID] => 60347 [Publish] => 1 ) [1] => stdClass Object ( [ID] => 61014 [AppointmentExternalID] => XXXXXXXX [CustomerFeedback] => [Rating] => 5 .....
Now all I need to do is format this somehow and get the char encoding to work.

In order to parse the JSON for eTermin ratings use this foreach loop:
//Traverse array __standard_Obj
foreach ($decoded as $key => $value) {
$c_feeback = $value["CustomerFeedback"];
$c_name = $value["CustomerInfo"];
$c_name = before ('(',$c_name);
$c_rating = $value["Rating"];
$c_date = $value["RatingDate"];
if(!empty($c_feeback)):
echo '<h2>Feedback:'.$x.'</h2>';
$x++;
echo '<div>';
if(strlen($c_name)>3):
echo $c_name;
else:
echo "Anonym";
endif;
echo ': '.$c_feeback;
//positiv stars
//$c_rating = 4; //testvalue
for($c = 0; $c < $c_rating; $c++) {
echo '<span class="fa fa-star checked"></span>';
}
//negative stars
$c_rating = 5 - $c_rating;
for($c = 0; $c < $c_rating; $c++) {
echo '<span class="fa fa-star"></span>';
}
endif;
}

Related

Error in creating record in zohocrm contacts using php 7.1

I am trying to create a record in zohocrm. i am using API version2 code.
i recieve this following error which i stated below. I tried stackoverflow for solutions but can't find relevant solution. I tried this Stackoverflow answer Zoho API V2 Update Record. It doesn't work for me. Help me with some solution. i use php version
7.1
Here's the Code i used:
public function createRecord($module, $module_fields)
{
global $HelperObj;
$WPCapture_includes_helper_Obj = new WPCapture_includes_helper_PRO();
$activateplugin = $WPCapture_includes_helper_Obj->ActivatedPlugin;
$moduleslug = $this->ModuleSlug = rtrim(strtolower($module), "s");
$zohoapi = new SmackZohoApi();
$module_field['data'] = array($module_fields);
$module_field['Owner']['id'] = $module_fields['SMOWNERID'];
$fields_to_skip = ['Digital_Interaction_s', 'Solution'];
foreach ($module_fields as $fieldname => $fieldvalue) {
if (!in_array($fieldname, $fields_to_skip)) {
continue;
}
$module_fields[$fieldname] = array();
if (is_string($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
} else if (is_array($fieldvalue)) {
array_push($module_fields[$fieldname], $fieldvalue);
}
}
//$fields = json_encode($module_fields);
$attachments = $module_fields['attachments'];
$body_json = array();
$body_json["data"] = array();
array_push($body_json["data"], $module_fields);
$record = $zohoapi->Zoho_CreateRecord($module, $body_json, $attachments);
if ($record['code'] == 'INVALID_TOKEN' || $record['code'] == 'AUTHENTICATION_FAILURE') {
$get_access_token = $zohoapi->refresh_token();
if (isset($get_access_token['error'])) {
if ($get_access_token['error'] == 'access_denied') {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "Access Denied to get the refresh token";
return $data;
}
}
$exist_config = get_option("wp_wpzohopro_settings");
$config['access_token'] = $get_access_token['access_token'];
$config['api_domain'] = $get_access_token['api_domain'];
$config['key'] = $exist_config['key'];
$config['secret'] = $exist_config['secret'];
$config['callback'] = $exist_config['callback'];
$config['refresh_token'] = $exist_config['refresh_token'];
update_option("wp_wpzohopro_settings", $config);
$this->createRecord($module, $module_fields);
} elseif ($record['data'][0]['code'] == 'SUCCESS') {
$data['result'] = "success";
$data['failure'] = 0;
} else {
$data['result'] = "failure";
$data['failure'] = 1;
$data['reason'] = "failed adding entry";
}
return $data;
}
API Call Code:
public function Zoho_CreateRecord($module = "Lead",$data_array,$extraParams) {
try{
$apiUrl = "https://www.zohoapis.com/crm/v2/$module";
$fields = json_encode($data_array);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $this->access_token),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
curl_close($ch);
$result_array = json_decode($result,true);
if($extraParams != "")
{
foreach($extraParams as $field => $path){
$this->insertattachment($result_array,$path,$module);
}
}
}catch(\Exception $exception){
// TODO - handle the error in log
}
return $result_array;
}
error i got:
Array
(
[data] => Array
(
[0] => Array
(
[code] => INVALID_DATA
[details] => Array
(
[expected_data_type] => jsonarray
[api_name] => Solution_Interest
)
[message] => invalid data
[status] => error
)
)
)
By the details which you gave ,
(1)you said you wish to create "Contacts" , but the url you are using to create contact doesn't seems to create "Contacts" either by
**converting leads to account and contact , or
**directly creating contact
(2)you mentioned module name as "Lead" , try changing it to "Leads".
(3)variables $data_array & $extraParams , doesn't seems to hold any value , they seems to be null.
(4)Here is a help doc. for you
Create Contact
If that still doesn't solve your problem ,you could ask your queries at zoho crm community , people will definitely solve your queries Ask here

Update Values in Database after getting success message using curl

i am getting below message after passing values in url with curl:
{"AddManifestDetails":[{"AuthKey":"Valid","ReturnMessage":"successful",}]
If ReturnMessage is successful , than i want to update values in database, i tried below code :
<?php
$data =
array (
'OrderNo' => $order_id,
'AirWayBillNO' => $resultc[0]['awb'],
);
$url = "http://114.143.206.69:803/StandardForwardStagingService.svc/AddManifestDetails";
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
$res=json_decode($curl_response);
foreach ($res->curl_response as $values)
{
if($values->ReturnMessage=='successful')
{
$usql="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress', where order_id='".$order_id."'";
$result=$db_handle->executeUpdate($usql);
echo "1";die;
}
else
{
echo $values->ReturnMessage;die;
}
}
Here is full code : https://pastebin.com/EvcEY0xp
Result :
Notice: Undefined property: stdClass::$curl_response
Warning: Invalid argument supplied for foreach()
$res will already contain decoded response from curl request, which will have only 1 property - AddManifestDetails.
Try following:
<?php
$data =
array (
'OrderNo' => $order_id,
'AirWayBillNO' => $resultc[0]['awb'],
);
$url = "http://114.143.206.69:803/StandardForwardStagingService.svc/AddManifestDetails";
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
$res=json_decode($curl_response);
if($res->AddManifestDetails[0]->ReturnMessage=='successful')
{
$usql="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress' where order_id='".$order_id."'";
$result=$db_handle->executeUpdate($usql);
echo "1";
die;
}
else
{
echo $res->AddManifestDetails[0]->ReturnMessage;
die;
}

404 Not Found nginx/1.12.0 Push Notification

I'm in big trouble that I have no idea what it can be.
I have an APP that has more than 100k users on the table, I happen to call the GCM service inside LOOP after about 1 minute presents this error message.
I have treated all the fields so as not to be NULL, I do not know what it can be!
Will it be timeout from ajax?
The call in GCM is as follows:
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'data' => array(
"mensagem" => $message
),
'registration_ids' => $registatoin_ids
);
if (is_array($data)) {
foreach ($data as $key => $value) {
$fields['data'][$key] = $value;
}
}
$headers = array(
'Authorization: key=' . apiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
Loop to bring the database id-------------
for ($i = 0; $i < $num / 1000; $i++)
{
$query = $con->query("SELECT gcm_regid from registration where status ='S' and LENGTH(gcm_regid) = 152 and app_id=$Id_Aplicativo LIMIT $current_num,1000");
foreach($query as $data)
{
if (!is_null($data["gcm_regid"]))
{
$row[] = is_null($data["gcm_regid"]) ? " " : $data["gcm_regid"];
$cont = $cont + 1;
}
}
// print_r($row);
$pushStatus = send_notification($con, $row, $mensagem, array(
'titulo' => is_null($titulo) ? " " : $titulo, //$titulo,
'sub_mensagem' => is_null($sub_mensagem) ? " " : $sub_mensagem, //$sub_mensagem,
'content_mensagem' => is_null($content_mensagem) ? " " : $content_mensagem, //$content_mensagem,
'content_info' => is_null($content_info) ? " " : $content_info, //$content_info,
'url_imagem' => is_null($path . $nome_imagem) ? " " : $path . $nome_imagem, //$path.$nome_imagem,// Esse Path vem do arquivo Conect.php
'url_audio' => is_null($path_audio . $filenameAudio) ? " " : $path_audio . $filenameAudio, //$path_audio.$filenameAudio, // Esse Path vem do arquivo Conect.php
'tipo_notificacao' => is_null($TipoNotificacao) ? " " : $TipoNotificacao, //$TipoNotificacao
));
$row = null;
$current_num+= 1000;
}
404 Not Found Nginx/1.12.0

Combine 2 associative arrays

I have 2 arrays that i have created from 2 different systems:
URL changed
I need to loop through the array on the left and find a match for the business, address and zip. If there is a match on the right side then I need to grab the id and add it to the array item on the left.
I am structuring the arrays so i can change them as needed.
${'URL'} = 'http://reviewsfor.biz/api/biz/';
// Initiate the cURL request
$curl = curl_init();
$data = array(
'api_key' => REVIEWS_API_KEY,
'format' => 'json',
'act' => 'active'
);
// Set the cURL options
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
curl_setopt($curl, CURLOPT_URL, ${'URL'}.'?'.http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute the cURL POST
$response = curl_exec($curl);
// Close the cURL connection
curl_close($curl);
$response = json_decode($response);
// Out the list of businesses into an array
${'Business List'} = $response->businesses;
${'Local Biz Array'} = array();
${'Query'} = mysql_query('SELECT * FROM `companies`.`subdomains`');
while(${'Sub Domain'} = mysql_fetch_assoc(${'Query'})){
${'Database'} = ${'Sub Domain'}['database'];
${'DB Query'} = mysql_query('SELECT * FROM `'.${'Database'}.'`.`users`');
while(${'User'} = mysql_fetch_assoc(${'DB Query'})){
if(${'User'}['company'] != ''){
${'Local Biz Array'}[] = array('business' => ${'User'}['company'], 'address' => ${'User'}['company_address'], 'zip' => ${'User'}['company_zip'], 'user_id' => ${'User'}['id']);
}
}
}
// Build an array
${'LBL Biz Array'} = array();
foreach(${'Business List'} as $item){
${'LBL Biz Array'}[] = array('business' => $item->business->business, 'address' => $item->business->address, 'zip' => $item->business->zip, 'id' => $item->business->id);
}
echo '<div id="leftCol" style="float:left;width:49%;height:500px;overflow:scroll;">';
echo '<pre>';
print_r(${'LBL Biz Array'});
echo '</pre></div>';
echo '<div id="rightCol" style="float:right;width:49%;height:500px;overflow:scroll;">';
echo '<pre>';
print_r(${'Local Biz Array'});
echo '</pre></div>';
function findMatch($arrayLeft, $arrayRight){
for($i=0,$j=count($arrayLeft);$i<$j;$i++){
for($k=0,$l=count($arrayRight);$k<$l; $k++){
if($arrayLeft[$i]['business'] == $arrayRight[$k]['business'] && $arrayLeft[$i]['address'] == $arrayRight[$k]['address'] && $arrayLeft[$i]['zip'] == $arrayRight[$k]['zip']){
$arrayLeft[$i]['user_id'] = $arrayRight[$k]['user_id'];
unset($arrayRight[$k]); //remove addresses already matched
break;
}
}
}
return $arrayLeft;
}

Multiple PHP cUrl posts to same page

So the gist is that I need to post XML data query to a gateway page to receive a XML response which O parse later, there can be anywhere from 3-60 queries to this web service, I unfortunately have to run a simple loop right now and do them one at a time. On the response side, I will only need 1 (or a max of 5) of the lines in the response, line 2 is the first line that I need containing image data. So I'd like the ability to select which lines I am reading in if at all possible.
I created a simple "Read in" function as I said out of a basic for loop, here's the code that I am currently using and would like to revise.
$part1 = 'XML Beginning'; $part2 = XML End';
$posts = array( 0 => 'SC-010052214', 1 => 'SC-000032972', 2 => 'SC-012535460', 3 => 'SC-011257289', 4 => 'SC-010134078' );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/index.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER => 1);
curl_setopt ($ch, CURLOPT_POST, 1);
$count = count($posts);
for($i=0;$i<$count;$i++) {
curl_setopt ($ch, CURLOPT_POSTFIELDS, "payload=$part1{$posts[$i]}$part2");
$return[] = curl_exec ($ch);
}
curl_close ($ch);
print_r($return);
Restrictions: I cannot use ?post=$data0&post=$data1&post=$data3 unfortunately, so I need a better solution. Other than that, I'd like to see what kinds of improvements can be made here.
Maybe http://php.net/manual/en/function.curl-multi-init.php helps you
Because of limits in quick response,
<?php
function m_curl($input) {
// compile queries for usable locations
foreach($input['content'] as $pos=>$item) {
$query = '<childDetailQuery><request><query-replacement>';
$query .= "<item_number>{$item}</item_number>";
$query .= (isset($input['story']) && $input['story'] != NULL)
? "<story_type>".$input['story']."</story_type>"
: '<story_type>SHORT</story_type>';
$query .= (isset($input['party']) && $input['party'] != NULL)
? "<party_number>".$input['party']."</party_number>"
: '';
$query .= "</query-replacement><latency-tolerance>NONE</latency-tolerance>";
$query .= '</request></childDetailQuery>';
$queries[] = $query;
unset($query);
}
// make sure the rolling window isn't greater than the # of urls
$limit = 10;
$limit = (sizeof($queries) < $limit) ? sizeof($queries) : $limit;
$master = curl_multi_init();
$curl_arr = array();
// add additional curl options here
$std_options = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_MAXREDIRS => 0,
);
$options = ($coptions) ? ($std_options + $coptions) : $std_options;
echo $input['location'];
// start the first batch of requests
for ($i = 0; $i < $limit; $i++) {
$ch = curl_init();
$options[CURLOPT_POSTFIELDS] = "payload=".$queries[$i];
curl_setopt_array($ch,$options);
curl_multi_add_handle($master, $ch);
}
do {
while(($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
if($execrun != CURLM_OK) {
echo 'Curl Error'; break;
}
// a request was just completed -- find out which one
while($done = curl_multi_info_read($master)) {
$info = curl_getinfo($done['handle']);
if ($info['http_code'] == 200) {
$output = curl_multi_getcontent($done['handle']);
// request successful. process output using the callback function.
parse_returns($output);
// start a new request (it's important to do this before removing the old one)
$ch = curl_init();
$options[CURLOPT_POSTFIELDS] = "payload=".$queries[$i++]; // increment i
curl_setopt_array($ch,$options);
curl_multi_add_handle($master, $ch);
// remove the curl handle that just completed
curl_multi_remove_handle($master, $done['handle']);
} else {
echo 'Failed on:'; var_dump($info);
echo 'With options:'; var_dump($options);
// request failed. add error handling.
}
}
} while ($running);
curl_multi_close($master);
return false;
}
function parse_returns($data) {
print_r($data);
}
// set query numbers
$data = array(
0 => 'SC-010052214',
1 => 'SC-000032972',
2 => 'SC-012535460',
3 => 'SC-011257289',
4 => 'SC-010134078'
);
// set options array
$options = array(
'location' => 'http://ibudev.wvus.org/websvc/actions/wvsMessageRouter.php',
'readline' => 2,
'coptions' => NULL,
'content' => $data,
'story' => 'FULL',
'party' => NULL,
);
m_curl($options);
?>

Categories