I am trying to use Crocodoc api with the following code to get the status.
$croco = new Crocodoc();
$uuids = "786e072b-981c-4d2a-8e80-80e215f1f7c2";
echo "\n\nchecking status of : ", $uuids;
$status = $croco->getStatus($uuids);
echo "\n\nstatus is : ", $status;
class Crocodoc {
public $api_key = 'HPUd6LZXg5174TAENbvBcx30';
public $api_url = 'https://crocodoc.com/api/v2/';
public function getStatus($uuids){
$url = $this->api_url.'document/status';
$token = $this->api_key;
$dataStr = '?token='.$token.'&uuids='.$uuids;
// this is a GET request
$output = $this->doCurlGet($url, $dataStr);
return $output;
}
}
I don't get the status and no error. What is wrong or it does not work in evaluation mode. Right now I am using it local with XAMPP, can that be a problem?
What doCurlGet does?
Because the request (and response) is fine:
HTTP/1.1 200 OK
Server: nginx/1.2.0
Date: Thu, 24 May 2012 10:11:27 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
[
{
"uuid": "786e072b-981c-4d2a-8e80-80e215f1f7c2",
"viewable": true,
"status": "DONE"
}
]
You might try with a real curl, like:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "/* generated url to crocodoc */");
$data = curl_exec($ch);
curl_close($ch);
Or directly:
$data = file_get_contents('/* generated url to crocodoc */');
Edit:
Just tried this code, and it works fine:
$croco = new Crocodoc();
$uuids = "786e072b-981c-4d2a-8e80-80e215f1f7c2";
$status = $croco->getStatus($uuids);
var_dump($status);
class Crocodoc {
public $api_key = 'HPUd6LZXg5174TAENbvBcx30';
public $api_url = 'https://crocodoc.com/api/v2/';
public function getStatus($uuids){
$url = $this->api_url.'document/status';
$token = $this->api_key;
$dataStr = '?token='.$token.'&uuids='.$uuids;
// this is a GET request
return file_get_contents($url.$dataStr);
}
}
Related
I've been trying to select values (students data) from mysql database table and looping through database to send to an API using PHP CURL Post request but it's not working.
This is the API body:
{
"students":[
{
"admissionNumber": "2010",
"class":"js one"
},
{
"admissionNumber": "2020",
"class":"ss one"
}
],
"appDomain":"www.schooldomain.com"
}
Parameters I want to send are "admissionNumber" and "class" parameters while "appDomain" is same for all. Here's my code:
if(isset($_POST['submit'])){
$body = "success";
$info = "yes";
class SendDATA
{
private $url = 'https://url-of-the-endpoint';
private $username = '';
private $appDomain = 'http://schooldomain.com/';
// public function to commit the send
public function send($admNo,$class)
{
$url_array= array('admissionNumber'=>$admNo,'class'=>$class,'appDomain'=>$this-> appDomain);
$url_string = $data = http_build_query($url_array);
// using the curl library to make the request
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $url_string);
curl_setopt($curlHandle, CURLOPT_POST, 1);
$responseBody = curl_exec($curlHandle);
$responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
return $this->handleResponse($responseBody,$responseInfo);
}
private function handleResponse($body,$info)
{
if ($info['http_code']==200){ // successful submission
$xml_obj = simplexml_load_string($body);
// extract
return true;
}
else{
// error handling
return false;
}
}
}
$sms = new SendDATA();
$result = mysqli_query( $mysqli, "SELECT * FROM school_kids");
while ($row = mysqli_fetch_array($result)) {
$admNo = $row['admNo'];
$class = $row['class'];
$sms->send($admNo,$class,"header");
echo $admNo. " ".$class;
}
}
The question is rather unclear; when you say "this is the API body", I presume this JSON fragment is what the REST API at https://url-of-the-endpoint expects. If so, you are building your request body wrong. http_build_query creates an URL-encoded form data block (like key=value&anotherKey=another_value), not a JSON. For a JSON, here's what you want:
$data = array('students' => array
(
array('admissionNumber' => $admNo, 'class' => $class)
),
'appDomain':$this->appDomain
);
$url_string = $data = json_encode($data);
Also, you probably want to remove the HTTP headers from the response:
curl_setopt($curlHandle, CURLOPT_HEADER, false);
I have created a function in PHP for fetching a YouTube video list of my channel in JSON format but I'm getting blank array.
public function channels_list()
{
$method = $_SERVER['REQUEST_METHOD'];
if($method != 'GET')
{
json_output(400,array('status' => 400,'message' => 'Bad request.'));
}
else
{
$data = array();
$json_link="https://www.googleapis.com/youtube/v3/search?key='MY API KEY'&channelId='MY CHANNEL ID'&part=snippet,id&order=date&maxResults=10";
$json = file_get_contents($this->json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
foreach($obj['items'] as $post){
$jsondata['id'] = isset($post['id']['videoId']) ? $post['id']['videoId'] : "";
$jsondata['published_at'] = isset($post['snippet']['publishedAt']) ? $post['snippet']['publishedAt'] : "";
$jsondata['title'] = isset($post['snippet']['title']) ? $post['snippet']['title'] : "";
$jsondata['description'] = isset($post['snippet']['description']) ? $post['snippet']['description'] : "";
$jsondata['thumbnail'] = "https://i.ytimg.com/vi/{$id}/maxresdefault.jpg";
array_push($data, $jsondata);
}
json_output("200", array("list"=>$data),1);
}
}
Try this below code,I'm using this and it's working fine for me.
function get_youtube($url){
$youtube = "http://www.youtube.com/oembed?url=". $url ."&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
return json_decode($return, true);
}
$url = // youtube video url
// Display Data
print_r(get_youtube($url));
Updated:
you don't need OAuth2 login for that. You can simply do it by setting your API key instead.
It's a playlistItems->list request.
Here's demonstration in api explorer: https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet&playlistId=PLjFEz-E0UPUxw3lFpnfV1dDA7OE7YIFRj&_h=2&
Instead of setting clientId and client Secret
set it's API key to your API key from cloud console in Public API access.
$client->setAPIKey($API_KEY);
Example:
$API_key = 'Your_API_Key';
$channelID = 'YouTube_Channel_ID';
$maxResults = 10;
$videoList = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId='.$channelID.'&maxResults='.$maxResults.'&key='.$API_key.''));
I am using ZF2 and curl for connecting with one of my clients API.
For example I am getting the response as
HTTP/1.1 200 OK Access-Control-Allow-Origin: * Content-Type: application/json; charset=ISO-8859-1 Date: Thu, 04 Dec 2014 06:12:13 GMT Server: Google Frontend Cache-Control: private Alternate-Protocol: 80:quic,p=0.02,80:quic,p=0.02 Connection: close { "time": "06:12:13 AM", "milliseconds_since_epoch": 1417673533861, "date": "12-04-2014" }
I need the JSON array only.
My code is:
$data = "";
$adapter = new Curl();
$client = new Client();
$client->setAdapter($adapter);
$client->setUri('http://date.jsontest.com');
$client->setMethod('POST');
$adapter->setCurlOption(CURLOPT_POST, 1);
$adapter->setCurlOption(CURLOPT_POSTFIELDS, $data);
$adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
$adapter->setCurlOption(CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Authorization: Bearer $token'
));
$response = $client->send();
return new ViewModel(array(
'response' => $response,
));
The send() method of the Zend HTTP Client returns a new Response instance after successfully complete the request. You're directly passing that response instance to your view, not the content (body) inside the response.
Try this:
// Your current code..
$response = $client->send();
$viewModel = new ViewModel();
if($response->getStatusCode() === 200) {
$obj = json_decode($response->getBody(), true);
if($obj === null) {
// Json cannot be decoded.. handle it..
}
$viewModel->setVariable('response', $obj);
} else {
// Status code is not 200, handle it..
}
// And return the model
return $viewModel;
Not perfect but it should work..
I'm trying to do a HTTP POST Request to a SMA Datalogger, that uses JSON-RPC to respond to HTTP requests.
Using hurl.it I can make a successful request, for example:
Destination: POST, http://aaa.no-ip.org:101/rpc, follow redirects:on.
Headers: Host: aaa.no-ip.org:101, Content-Type:text/plain.
Body: RPC={"proc":"GetPlantOverview","format":"JSON","version":"1.0","id":"1"}
Then hurl.it process's the following request:
Success
POST http://aaa.no-ip.org:101/rpc
200 OK 401 bytes 3.76 secs
HEADERS
Accept: */*
Accept-Encoding: application/json
Content-Length: 122
Content-Type: text/plain
Host: aaa.no-ip.org
User-Agent: runscope/0.1
BODY
RPC=%7B%22proc%22%3A%22GetPlantOverview%22%2C%22format%22%3A%22JSON%22%2C%22version%22%3A%221.0%22%2C%22id%22%3A%221%22%7D
And the response is:
HEADERS
Cache-Control: no-store, no-cache, max-age=0
Connection: keep-alive
Content-Length: 401
Content-Type: text/html
Date: Wed, 22 Oct 2014 14:15:50 GMT
Keep-Alive: 300
Pragma: no-cache
Server: Sunny WebBox
BODY
{"format":"JSON","result":{"overview":[{"unit":"W","meta":"GriPwr","name":"GriPwr","value":"99527"},{"unit":"kWh","meta":"GriEgyTdy","name":"GriEgyTdy","value":"842.849"},{"unit":"kWh","meta":"GriEgyTot","name":"GriEgyTot","value":"2851960.438"},{"unit":"","meta":"OpStt","name":"OpStt","value":""},{"unit":"","meta":"Msg","name":"Msg","value":""}]},"proc":"GetPlantOverview","version":"1.0","id":"1"}
My problem is, every time I try to replicate these requests I always get:
string(0) ""
It could be because I'm using a shared host. I tried cURL, plain PHP (socket and file_get_contents, and even jQuery.
Can someone please provide an example on how to do this request?
Either jquery or php, I don't even care anymore, I've been trying for 2 weeks, and so many attempts, and either I get code errors or just string(0)"".
PS: for previous attempts examples, see: https://stackoverflow.com/questions/26408153/solar-energy-monitoring-sma-webbox-json-post-request
Here is the JSONRPC Client I have used to successfully make JSON RPC HTTP Requests. Hope this helps:
You may need to change some things to work in your code.
Found here: https://code.google.com/p/pmvc-framework/source/browse/trunk/src/main/php/pmvc/remoting/jsonrpc/JsonRpcClient.class.php?r=328
<?php
use Exception;
use ReflectionClass;
/*
* A client for accessing JSON-RPC over HTTP servers.
*
*/
class JsonRpcClient
{
private $_url = false;
private $_reuseConnections = true;
private static $_curl = null;
private $_nextId = 99;
/*
* Creates the client for the given URL.
* #param string $_url
*/
public function __construct($url)
{
$this->_url = $url;
}
/*
* Returns a curl resource.
* #return resource
*/
private function getCurl()
{
if (!isset(self::$_curl)) {
// initialize
self::$_curl = curl_init();
// set options
curl_setopt(self::$_curl, CURLOPT_FAILONERROR, true);
curl_setopt(self::$_curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt(self::$_curl, CURLOPT_FORBID_REUSE, $this->_reuseConnections===false);
curl_setopt(self::$_curl, CURLOPT_FRESH_CONNECT, $this->_reuseConnections===false);
curl_setopt(self::$_curl, CURLOPT_CONNECTTIMEOUT, 5);
return self::$_curl;
}
}
/*
* Invokes the given method with the given arguments
* on the server and returns it's value. If {#code $returnType}
* is specified than an instance of the class that it names
* will be created passing the json object (stdClass) to it's
* constructor.
*
* #param string $method the method to invoke
* #param Array $params the parameters (if any) to the method
* #param string $id the request id
* #param Array $headers any additional headers to add to the request
*/
public function invoke($method, Array $params=Array(), $id=false, Array $headers=Array())
{
// get curl
$curl = $this->getCurl();
// set url
curl_setopt($curl, CURLOPT_URL, $this->_url);
// set post body
$request = json_encode(
Array(
'jsonrpc' => '2.0',
'method' => $method,
'params' => $params,
'id' => ($id===false) ? ++$this->nextId : $id
)
);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// set headers
$curlHeaders = Array();
$curlHeaders []= "Content-type: application/json-rpc";
for (reset($headers); list($key, $value)=each($headers); ) {
$curlHeaders []= $key.": ".$value."\n";
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
// post the data
$response = curl_exec($curl);
if (!$response) {
throw new Exception('cURL error '.curl_error($curl).' while making request to '.$this->_url);
}
// decode json response
$response = json_decode($response);
if ($response==NULL || curl_error($curl)!=0) {
throw new Exception("JSON parsing error occured: ".json_last_error());
// throw errors
} else if (isset($response->error)) {
$msg = 'JSON-RPC error';
if (isset($response->error->message) && !empty($response->error->message)) {
$msg .= ': "' . $response->error->message . '"';
}
$msg .= "\n";
$msg .= 'URL: ' . $this->_url;
$msg .= "\n";
$msg .= 'Method: ' . $method;
$msg .= "\n";
$msg .= 'Arguments: ' . self::printArguments($params, 2);
if (isset($response->error->code)) {
throw new Exception($msg, intval($response->error->code));
} else {
throw new Exception($msg);
}
}
// get the headers returns (APPSVR, JSESSIONID)
$responsePlusHeaders = Array();
$responsePlusHeaders['result'] = $response->result;
$responsePlusHeaders['headers'] = curl_getinfo($curl);
// return the data
return $responsePlusHeaders;
}
/*
* Printing arguments.
* #param $arg
* #param $depth
*/
private static function printArguments($args, $depth=1)
{
$argStrings = Array();
foreach ($args as $arg) {
$argStrings[] = self::printArgument($arg, $depth);
}
return implode($argStrings, ', ');
}
/*
* Print an argument.
* #param $arg
* #param $depth
*/
private static function printArgument($arg, $depth=1)
{
if ($arg === NULL) {
return 'NULL';
} else if (is_array($arg)) {
if ($depth > 1) {
return '[' . self::printArguments($arg, ($depth - 1)) . ']';
} else {
return 'Array';
}
} else if (is_object($arg)) {
return 'Object';
} else if (is_bool($arg)) {
return ($arg === TRUE) ? 'true' : 'false';
} else if (is_string($arg)) {
return "'$arg'";
}
return strval($arg);
}
}
Usage would then be:
include JsonRpcClient.php
$client = new JsonRpcClient('http://aaa.no-ip.org:101/rpc');
$response = $client->invoke('GetPlantOverview', 1, array('Host: aaa.no-ip.org:101'));
I have been trying to build a USPS Rate Calculator for a site, but unfortunately the test url from USPS does not seem to work. In any case, my code does not return anything at the moment, not even the error message about the url...
Would you take a look to see if I am doing the right thing? I get a bit lost with XML on PHP...
CODE:
$zip = 90002;
$pounds = 0.1;
function USPSParcelRate($pounds,$zip) {
$url = "https://secure.shippingapis.com/ShippingAPITest.dll";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$xml = "API=RateV4&XML=<RateV4Request USERID='USERNAME' >
<Revision/>
<Package ID='1ST'>
<Service>PRIORITY</Service>
<ZipOrigination>10025</ZipOrigination>
<ZipDestination>$zip</ZipDestination>
<Pounds>$pounds</Pounds>
<Ounces>0</Ounces>
<Container></Container>
<Size>REGULAR</Size>
<Width></Width>
<Length></Length>
<Height></Height>
<Girth></Girth>
</Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$xml);
$result = curl_exec($ch);
$data = strstr($result, '<?');
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
echo "TEST";
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see xml tags
return $params['RateV4Response']['1ST']['1']['RATE'];
}
USPSParcelRate($pounds,$zip)
You are missing the curl_init() function since $ch is not defined
$ch = curl_init();
Also you are not printing the response:
**echo** USPSParcelRate($pounds,$zip);
Lastly, you can print the response from curl, change:
echo "TEST";
to:
print "RESPONSE: $result";
I'm getting that RateV4 is not authorized, where is RateV4 coming from?
TEST HTTP/1.1 200 Connection established
HTTP/1.1 200 OK
Connection: close
Date: Mon, 10 Jun 2013 17:16:17 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
<Error>
<Number>80040b1a</Number>
<Description>API Authorization failure. RateV4 is not a valid API name for this protocol.</Description>
<Source>UspsCom::DoAuth</Source>
</Error>
Hope this at least helps with debugging..
RateV4 is a sevice name at USPS API.
check following link - http://uspsship.blogspot.in/