problems displaying json data retrieved using php curl - php

First, thanks for you reading. Here is my code
what my json data looks like when viewed in a browser using the url,
{
"$totalResults": 1500,
"$startIndex": 1,
"$itemsPerPage": 3,
"$resources": [
{
"$uuid": "5e7b9312-52e5-4fe1-b3e4-633ca04c9764",
"$httpStatus": "OK",
"$descriptor": "",
"name": "Heinz Tomato Sauce Sachets Qty 200"
},
{
"$uuid": "1a0f9dca-c417-4cff-94d2-99d16438723f",
"$httpStatus": "OK",
"$descriptor": "",
"name": "Heinz Brown Sauce Sachet Qty 200"
},
{
"$uuid": "126fdb17-81ce-41b4-bdba-91d0a170262a",
"$httpStatus": "OK",
"$descriptor": "",
"name": "Heinz English Mustard Sachets Qty 300"
}
]
}
test2.php
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&format=json';
//SAGE USERNAME & PASSWORD
$username = 'test';
$password = 'test';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$json = json_decode($result);
foreach ($json->{'$resources'} as $mydata) {
echo $mydata->name;
};
?>
errors im getting
Notice: Trying to get property of non-object in C:\xampp\htdocs\Sage Json\test2.php on line 29
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Sage Json\test2.php on line 29
I’m not sure what's going wrong, this works if i get the same data from a file but not if I’m retrieving it from at rest server, and if anyone could shed some light I would be grateful

Ajking11 the reason your getting Invalid argument supplied for foreach() is that $json vairiable is overwritten and has no data try somthing like this
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3';
//SAGE USERNAME & PASSWORD
$username = 'test';
$password = 'test';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$xml = simplexml_load_string($result);
$data = json_encode($xml);
$arr = json_decode($data,TRUE);
foreach ($arr['entry'] as $k=>$v){
echo $v; // etc.
}
note that I have removed &format=json and encoded later hope this help let me know how your getting on

you might like to use this code and refine it to your needs
<?php
// SAGE URL
//$url = 'http://computer_2:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&select=name&count=10&format=json';
$url ='http://localhost:5493/sdata/accounts50/GCRM/-/tradingAccounts?select=name&count=10';
//SAGE USERNAME & PASSWORD
$username = 'MANAGER';
$password = '';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$xml = simplexml_load_string($result);
foreach($xml->xpath("//sdata:payload") as $entry) {
// xpath here must be from payload to tradingAccount
$content = $entry->xpath("./crm:tradingAccount");
foreach($content as $c) {
// Make set of children with prefix crm
$nodes = $c->children('crm', true);
echo $nodes->reference . " | " . $nodes->name . " / " . $nodes->openedDate . "<br />\n";
}
}
thanks PHPhil and splash58 for your assistance with the namespace issue

As Artful_dodger say's the json is the problem here is how I would solve it
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&format=json';
//SAGE USERNAME & PASSWORD
$username = 'MANAGER';
$password = '';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
// doing a substring as there are 3 weird characters being passed back from IIS in front of the string
$json = json_decode(substr($result, 3, strlen($result)), true);
foreach ($json['$resources'] as $mydata) {
echo $mydata['name'] . "<br>";
}

PHP json_decode function returns an array and not an object, so instead of using
foreach ($json->{'$resources'} as $mydata) {
echo $mydata->name;
};
you should use
foreach ($json['$resources'] as $mydata) {
echo $mydata['name'];
};
UPDATE
your test2.php should look like this:
<?php
// SAGE URL
$url = 'http://localhost:5493/sdata/accounts50/GCRM/-/commodities?select=name&count=3&format=json';
//SAGE USERNAME & PASSWORD
$username = 'test';
$password = 'test';
//initiaize
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute
$result = curl_exec($ch);
//close curl session / free resources
curl_close($ch);
$json = json_decode($result);
$json = (array)$json;
foreach ($json['$resources'] as $mydata) {
echo $mydata->name . "<br>";
};
in your code the major problem was in naming of the JSON attribute $resources: it is named as PHP variable and it causes the problem.
Converting the decoded variable into an array solves the problem as the associative array key is a string.

im really sorry for never getting back to you. so it turn out that when you get data from the sage service, it returned to you in "utf 8 bom".
So before i can display any thing i needed to remove the format by clearing the first three characters with in the array. with the substr() function.
$json_data = substr($json_data, 3);
Thank you all for helping with this problem.

Related

My API request keeps using up 25 requests for no apparent reason

My request functions from PUBG official API
<?php
function getProfile($profile, $div){
$pubgapikey = 'xxxxxxxxxxxxx';
$id = getID($profile);
$url = "https://api.pubg.com/shards/pc-na/players/$id/seasons/$div";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
if($json["data"]["type"] == "playerSeason"){
return $json["data"]["attributes"];
}else {
return false;
}
}
function getID($name){
$pubgapikey = 'xxxxxxxxxxxxxxxxxxx';
$url = "https://api.pubg.com/shards/pc-na/players?filter[playerNames]=$name";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
return $json["data"][0]["id"];
}
So That's my function for requesting the data. I'll include the ways I call this.
// My index.php file (All requests go through here)
$page = explode("/", trim($_SERVER["REQUEST_URI"], "/"));
switch($page[0]){
case "profile":
require("controllers/search_controller.php");
$data = getProfile($page[1], "division.bro.official.2018-09");
if($data != false){
include("pages/profile.php");
}else{
include("pages/home.php");
echo '<script> document.getElementById("error").innerHTML = "Cannot find user. Remember To Be Capital Sensitive!"; </script>';
}
break;
}
I know that I'm using a really dumb way to include pages and what not but I don't wanna use or build my own php framework atm and this works just fine for what I'm doing
// Here is my php for calling the function
<?php
if (isset($_POST['username'])) {
$user = $_POST['username'];
if($user != ""){
header("Location: http://www.statstreak.us/profile/$user");
die();
}
}
?>
That's pretty much it. The form is just a basic html form.
For some reason this keeps using up my 25 requests/minute that I got from PUBG which is annoying as I can't find a reason why it would use up more than 2 requests per user

Binance REST API - Placing a PHP Order (POST) via Query String

I am struggling using Binance's REST API. I have managed to get working GET request via query string such as pinging the server, ticker information, etc. My challenge now is performing POST request via query string using cURL. I have been scraping code from various places and referring back to the API to get pieces to work but I am unsure as to why I am getting this error returned from the result... {"code":-1102,"msg":"Mandatory parameter 'signature' was not sent, was empty/null, or malformed."}
(ERROR SHOWN ON WEBPAGE). I echo out the signature and its a load of gibberish so I would believe that the hash_hmac performed at the top would be working, but honestly I got pretty lucky making the GET request work. Does anyone have any suggestions as to why this would be broken? Thanks!
$apikey = "MYKEY";
$apisecret = "MYSECRET";
$timestamp = time()*1000; //get current timestamp in milliseconds
$signature = hash_hmac('sha256', "TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp, $apisecret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.binance.com/api/v3/order/test");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
As per their API docs:
SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
You are sending the signature via neither of these methods and are instead sending it through the header.
Change this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
To this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=" . $timestamp . "&signature=" . $signature);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey));
<?php
$secret = "F................";
$key = "D.................";
$s_time = "timestamp=".time()*1000;
$sign=hash_hmac('SHA256', $s_time, $secret);
$url = "https://api.binance.com/api/v3/account?".$s_time.'&signature='.$sign;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$result = json_decode($result, true);
echo '<pre>';
var_dump($result);
echo '</pre>';
?>
Here is an example, using php-curl-class
// Variables
// url, key and secret is on separate file, called using require once
$endPoint = "/api/v3/order/test";
$coin = "BTC";
$fiat = "EUR";
$symbol = $coin . "" . $fiat;
$side = "BUY";
$type = "LIMIT";
$timeInForce = "GTC";
$quantity = 1;
$price = 10000;
$timestamp = time();
// Constructing query arrays
queryArray = array(
"symbol" => $symbol,
"side" => $side,
"type" => $type,
"timeInForce" => $timeInForce,
"quantity" => $quantity,
"price" => $price,
"timestamp" => $timestamp*1000
);
$signature = hash_hmac("sha256", http_build_query($queryArray), $secret);
$signatureArray = array("signature" => $signature);
$curlArray = $queryArray + $signatureArray;
// Curl : setting header and POST
$curl->setHeader("Content-Type","application/x-www-form-urlencoded");
$curl->setHeader("X-MBX-APIKEY",$key);
$curl->post($url . "" . $endPoint, $curlArray);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
}
$order = $curl->response;
print_r($order);
I had the same problem, and nothing of above doesn't helped.
So I finaly figured out how to make order on my way.
So, maybe this helps someone.
function Kupovina($buy_parametri) {
$key = "xxxxxxxxxxxxxxx";
$secret = "xxxxxxxxxxxx";
$s_time = "timestamp=".time()*1000;
$timestamp = time()*1000; //get current timestamp in milliseconds
$sign = hash_hmac('sha256', $buy_parametri."&timestamp=".$timestamp, $secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.binance.com/api/v3/order");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $buy_parametri."&".$s_time."&signature=".$sign);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$key));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$buy_parametri = "symbol=BTCUSDT&type=market&side=buy&quantity=0.00086";
Call function:
Kupovina($buy_parametri);

php json_decode is not working Properly

When i am Decoding using commented "$jsonString" String it is working very well.
But after using curl it is not working, showing Null.
Please Help Me in this.
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
$url = 'http://ExampleStatus.php?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// $jsonString = '[{"branchname":"BHUBNESHWAR","consignee":"ICICI BANK LTD","currentstatus":"Delivered by : BHUBNESHWAR On - 25/07/2015 01:00","dlyflag":"Y","PODuploaded":"Not Uploaded"}]';
if ($jsonString != '') {
$json = str_replace(array('[', ']'), '', $jsonString);
echo $json;
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}
}
}
After curl I used following concept to get only JSON data from HTML Page.
1) fetchData.php
$url = 'http://DocketStatusApp.aspx?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// now get only value
$dom = new DOMDocument();
$dom->loadHTML($jsonString);
$thediv = $dom->getElementById('Label1');
echo $thediv->textContent;
2) JSONprocess.php
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
ob_start(); // begin collecting output
include_once 'fetchData.php';
$result = ob_get_clean(); // Completed collecting output
// Now it will show & take only JSON Data from Div Tag
$json = str_replace(array('[', ']'), '', $result);
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}

How to use the WHMCS API without actually displaying WHMCS?

Is there any way in which i can use the WHMCS API without displaying WHMCS to the clients and users.
I want my PHP scripts to first create a WHMCS client, add an order for the client and then copy some files to the client's directory.
But i don't want my clients to be able to login to their WHMCS panel or even be able to see the WHMCS
WHMCS has something called External API that will help you.
Here is the documentation. But for what you need yo should do this:
Connect to the API
$url = "http://www.yourdomain.com/includes/api.php"; # URL to WHMCS API file goes here
$username = "Admin"; # Admin username goes here
$password = "demoxyz"; # Admin password goes here
Add the Client
$postfields = array();
$postfields["username"] = $username;
$postfields["password"] = md5($password);
$postfields["action"] = "addclient";
$postfields["firstname"] = "Test";
$postfields["lastname"] = "User";
$postfields["companyname"] = "WHMCS";
$postfields["email"] = "demo#whmcs.com";
$postfields["address1"] = "123 Demo Street";
$postfields["city"] = "Demo";
$postfields["state"] = "Florida";
$postfields["postcode"] = "AB123";
$postfields["country"] = "US";
$postfields["phonenumber"] = "123456789";
$postfields["password2"] = "demo";
$postfields["customfields"] = base64_encode(serialize(array("1"=>"Google")));
$postfields["currency"] = "1";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch)) die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));
curl_close($ch);
$arr = json_decode($jsondata); # Decode JSON String
print_r($arr); # Output XML Response as Array
Add the Order
$postfields = array();
$postfields["username"] = $username;
$postfields["password"] = md5($password);
$postfields["action"] = "addorder";
$postfields["clientid"] = "1";
$postfields["pid"] = "1";
$postfields["domain"] = "whmcs.com";
$postfields["billingcycle"] = "monthly";
$postfields["addons"] = "1,3,9";
$postfields["customfields"] = base64_encode(serialize(array("1"=>"Google")));
$postfields["domaintype"] = "register";
$postfields["regperiod"] = "1";
$postfields["paymentmethod"] = "mailin";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch)) die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));
curl_close($ch);
$arr = json_decode($jsondata); # Decode JSON String
print_r($arr); # Output XML Response as Array
Then you can copy the files to the client's directory. Hope it helps!

php youtube json decode

I tried to use JSON decode to get the youtube API feed. However, when I paste the JSON result in http://www.jsonlint.com/ I noticed something like
"media$group": {
"media$category": [
Unfortunately some symbols are rejected by php. Here is my code, I tried to remove this $ symbol, but maybe not success. How do I solve this?
$url = 'http://gdata.youtube.com/feeds/api/videosq=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
...
}
Your problem is the usage of PHP identifiers to access the contents. The simplest solution here would be to get an array instead of an object:
$data = json_decode ( $json , $assoc = true );
This allows access to fields with:
echo $result['media$group']['media$description'];
If you want to keep the object syntax, that's possible with this kludge:
echo $result->{'media$group'}->{'media$category'};
(But arrays are safer here. You don't get a fatal error should the format change and properties be absent.)
This work:
<?php
$url = 'http://gdata.youtube.com/feeds/api/videos?q=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) {
var_dump($result);
}
?>

Categories