Json_decode throws "Trying to get property of non-object" - php

I'm trying to use the simple weather API, but somehow it doesn't recognize it as an object whatever I do. This is my code:
$url = "https://www.amdoren.com/api/weather.php?api_key=za8LEJ8F9mcHK8SvLxdM98rM9mNFjW&lat=40.7127837&lon=-74.0059413";
$curl = curl_init($url);
$curl_response = curl_exec($curl);
$jsonobj = json_decode($curl_response);
$msg = "Temperature in ".$city."will be: ". $jsonobj->forecast->max_c;
and this is the data I'm trying to reach with $jsonojb->forecast->max_c:
{
"error" : 0,
"error_message" : "-",
"forecast":[
{"date":"2016-12-02",
"avg_c":8,
"min_c":5,
"max_c":11,
"avg_f":46,
"min_f":41,
"max_f":52,
(...)
but it doesn't work. What am I doing wrong guys?

forecast is an array, so you have to use like this:
$forecast = $jsonobj->forecast;
$forecast[0]->max_c;

You can try out this code:
$url = "https://www.amdoren.com/api/weather.php?api_key=za8LEJ8F9mcHK8SvLxdM98rM9mNFjW&lat=40.7127837&lon=-74.0059413";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
$jsonobj = json_decode($curl_response);
$msg = "Temperature in ". $city . " will be: ". $jsonobj->forecast[0]->max_c;
echo $msg;
Hope it helps!

The "forecast" is an array, you have to add [0] to get the first one and then you will be able to get your "max_c".
Also, your API does not give you the city. You would have to use the Google Geocoding API to convert the lon,lat into a City Name.
$api_key = "za8LEJ8F9mcHK8SvLxdM98rM9mNFjW";
$lon = -74.0059413;
$lat = 40.7127837;
$url = "https://www.amdoren.com/api/weather.php?api_key=".$api_key."&lat=".$lat."&lon=".$lon."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$max_c = $response['forecast'][0]['max_c'];
// Your API doesn't return the city name.
$city = "City Name";
$msg = "Temperature in ".$city."will be: ". $max_c;
echo $msg;
To get your City Name, here's the function you can use. You will need to replace the API KEY.
// Geocode
function geocode($lat,$lon){
$details_url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lon."&key=YOUR_API_KEY";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
// If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
if ($response['status'] != 'OK') {
return null;
}
$formatted_address = $response['results'][0]['formatted_address'];
$geometry = $response['results'][0]['geometry'];
$longitude = $geometry['location']['lat'];
$latitude = $geometry['location']['lng'];
$array = array(
'lat' => $geometry['location']['lng'],
'lon' => $geometry['location']['lat'],
'location_type' => $geometry['location_type'],
'formatted_address' => $formatted_address
);
return $array;
}

Related

Shopify GraphQL Error "Parse error on \":\" (COLON) at [2, 35]" With PHP

Greetings I have a problem with my GraphQL I don't know how to pass data to my GraphQL without getting
Error Message: "Parse error on ":" (COLON) at [2, 35]"
here is what I'm trying to pass product variant id data and get some response here is the example of what I'm trying to do and my function for graphql
$variantId = (isset($data->variantId) && !empty($data->variantId)) ? strip_tags($data->variantId) : "";
if(empty($variantId)){
$result['error'] = "Product id not specified!";
}
$query = array("query" => '{
productVariant(id: '. ($variantId) .') {
availableForSale
}
}');
$variants = shopify_gql_call($_SESSION['access_token'], $_SESSION['shop_name'], $query);
if( isset($variants['response']) && !empty($variants['response']) ){
$result[] = $variants['response'];
}else{
$result['error'] = "Variants not found!";
}
function shopify_gql_call($token, $shop, $query = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . "/admin/api/".getenv('API_DATE')."/graphql.json";
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
// Setup headers
$request_headers[] = "";
$request_headers[] = "Content-Type: application/json";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($curl, CURLOPT_POST, true);
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part, 2);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
I strongly suggest the use of https://packagist.org/packages/shopify/shopify-api instead of implementing your own function/http requests.
Your query should be something like this
query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}
and then you submit the ID as part of another entry of the array, check the example below:
$query = [
"query" =>
'query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}',
"variables" => [
'id' => $variantId
]
];
You should never concatenate the values as part of the query string (unless you want to deal with a lot of injection issues). Check more info about variables here https://graphql.org/learn/queries/

How to use AZURE face recognition Rest API?

I am using Face API with curl in PHP. But I am having issue when matching images.
I am able to generate faceId's but when matching I get different results than expected. I have two images belonges to same person but API indicates that these images are different. But when using Microsoft demo to compare images I get right result.
Here is microsoft demo link:
https://azure.microsoft.com/en-in/services/cognitive-services/face/#demo
Here are My images url
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
Here is my code
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$headers = ["Ocp-Apim-Subscription-Key: ********* ","Content-Type:application/json" ];
/* Getting faceId */
foreach($images as $data)
{
/* First step is to detect face */
$request_url='https://nexever.cognitiveservices.azure.com/face/v1.0/detect?detectionModel=detection_03&returnFaceId=true&returnFaceLandmarks=false';
/* Image to get faceid */
$detect = array('url' => $data);
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($detect)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl);
$curlErrno = curl_errno($curl);
if ($curlErrno) { $curlError = curl_error($curl);throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl);
$strResponse = json_decode($strResponse , true);
print_r($strResponse);
array_push($faceid , $strResponse[0]['faceId']);
}
// comparing by face ID
/* Match face url */
$request_url = 'https://nexever.cognitiveservices.azure.com/face/v1.0/verify';
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($match)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl); $curlErrno = curl_errno($curl);
if ($curlErrno) {$curlError = curl_error($curl); throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($strResponse, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
I have successfully got face id but unable to match. If I try some other images of same person it matches sometimes. The problem is result is not accurate.
but on microsoft demo it is working fine.
Pls try to use specify request param: recognitionModel=recognition_04 when you detect faces as official doc recommanded:
I modified your code as below, it works for me perfectly:
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$faceAPIName = "nexever";
$apikey = "<your api key>";
$faceidAPIHost = "https://$faceAPIName.cognitiveservices.azure.com";
foreach($images as $data)
{
$detect = array('url' => $data);
$result = do_post("$faceidAPIHost/face/v1.0/detect?recognitionModel=recognition_04&detectionModel=detection_03",json_encode($detect),$apikey);
array_push($faceid , $result[0]['faceId']);
}
$request_url = "$faceidAPIHost/face/v1.0/verify";
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
return do_post($request_url,json_encode($match),$apikey);
}
function do_post($url, $params,$key) {
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\nOcp-Apim-Subscription-Key: $key",
'method' => 'POST',
'content' => $params
)
);
$result = file_get_contents($url, false, stream_context_create($options));
return json_decode($result, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
Result of your code:

PHP - Fortnite API show me "Invalid authentication credentials"?

I would like to make a small Fortnite API, but I always get an error in the JSON file.
{"message":"Invalid authentication credentials"}
My PHP Code:
$ch = curl_init();
//pc, xbl, psn
curl_setopt($ch, CURLOPT_URL, "https://api.fortnitetracker.com/v1/profile/pc/MyName");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'TRN-Api-Key: My-API-Code'
));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$fp = fopen("myStats.json", "w");
fwrite($fp, $response);
fclose($fp);
$data = json_decode(file_get_contents("myStats.json"));
$solo = $data->stats->p2;//solos data
$duos = $data->stats->p10;//duos data
$squads = $data->stats->p9;//squads data
$matches = $data->recentMatches;//match data
$sesh1 = $matches[0]->id->valueInt;
$solo_wins = $solo->top1->valueInt;
$duos_wins = $duos->top1->valueInt;
$squads_wins = $squads->top1->valueInt;
$solo_matches = $solo->matches->valueInt;
$duos_matches = $duos->matches->valueInt;
$squads_matches = $squads->matches->valueInt;
$solo_kd = $solo->kd->valueDec;
$duos_kd = $duos->kd->valueDec;
$squads_kd = $squads->kd->valueDec;
$solo_games = $solo->matches->valueInt;
$duos_games = $duos->matches->valueInt;
$squads_games = $squads->matches->valueInt;
$solo_kills = $solo->kills->valueInt;
$duos_kills = $duos->kills->valueInt;
$squads_kills = $squads->kills->valueInt;
$total_matches = ($solo_matches+$duos_matches+$squads_matches);
$total_wins = ($solo_wins+$duos_wins+$squads_wins);
$total_kills = ($solo_kills+$duos_kills+$squads_kills);
$total_kd = (round($total_kills/($total_matches-$total_wins),2));
echo 'Total Matches: '.$total_matches.'<br>';
echo 'Total Wins: '.$total_wins.'<br>';
echo 'Total Kills: '.$total_kills.'<br>';
echo 'Total KD: '.$total_kd.'<br>';
echo $sesh1;
?>
I entered the correct API code. Why is this message written in a JSON file and not my wins? It's so crazy because it should work.
What returns on line 11? You are using var_dump($response);
Could you write die(); under that line and provide us the return that it gives?
There might be something wrong on how you handle the headers. I can't check for sure right now as I am not home. But I might be able to test this out later.

pushcrew - send notification with PHP curl

This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)

PayPal IPN only works with simulator not sandbox or live

My scripts work perfectly with the ipn simulator but it will not work with a sandbox transaction. If I change the url to the live site, it will not work. The simulator prints the incoming post to a file. When using a transaction, nothing happens. How can I make this work?
edit: My wordpress plug-in is overriding paypal's ipn by setting a custom notify_url value. I tried putting the function I need to fire in the Payment complete Jigoshop action but the $_POST variable is either changed or not present. If I fill in these fields with strings, it works fine. This is what I need to fire.
$data = array();
$data['Name'] = $_POST['address_name'];
$data['Company'] = '';
$data['Address1'] = $_POST['address_street'];
$data['Address2'] = '';
$data['City'] = $_POST['address_city'];
$data['State'] = $_POST['address_state'];
$data['Zip'] = $_POST['address_zip'];
$data['Country'] = $_POST['address_country'];
$data['Ship_Method_MSID'] = '1STCLASS';
$data['SpecialInstr'] = $_POST['memo'];
$data['Items'] = array(array('Item_ESID' => 'EVENTBAG', 'Quantity' => intval($_POST['quantity'])));
$json_data = json_encode($data);
$post_data = array('AccountID' => 10019, 'SecretKey' ='jsjxb', 'Method' => 'AddShipment', 'JSON' => $json_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'example.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($ch);
file_put_contents('test.txt', $returndata);
This is what I came up with:
$data = array();
$data['Name'] = $paypal_args['first_name'] . " " . $paypal_args['last_name'];
$data['Company'] = '';
$data['Address1'] = $paypal_args['address1'];
$data['Address2'] = $paypal_args['address2'];
$data['City'] = $paypal_args['city'];
$data['State'] = $paypal_args['state'];
$data['Zip'] = $paypal_args['zip'];
$data['Country'] = $paypal_args['country'];
$data['Ship_Method_MSID'] = '1STCLASS';
$data['SpecialInstr'] = '';
$data['Items'] = array(array('Item_ESID' => 'EVENTBAG', 'Quantity' => intval($paypal_args['quantity_1'])));
$json_data = json_encode($data);
$post_data = array('AccountID' => 10019, 'SecretKey' => 'z1', 'Method' => 'AddShipment', 'JSON' => $json_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'example.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$returndata = curl_exec ($ch);
file_put_contents('test.txt', $returndata);
Which came from:
if ($this->send_shipping=='yes') :
$paypal_args['no_shipping'] = 1;
$paypal_args['address_override'] = 1;
$paypal_args['first_name'] = $order->shipping_first_name;
$paypal_args['last_name'] = $order->shipping_last_name;
$paypal_args['address1'] = $order->shipping_address_1;
$paypal_args['address2'] = $order->shipping_address_2;
$paypal_args['city'] = $order->shipping_city;
$paypal_args['state'] = $order->shipping_state;
$paypal_args['zip'] = $order->shipping_postcode;
$paypal_args['country'] = $order->shipping_country;

Categories