I am following this part of the documentation: http://developers.marketo.com/rest-api/assets/tokens/ and I always get the following an error: Fields cannot be empty.
Have anyone make it worked?
public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
$folder_id = intval($folder_id);
$endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
$body = new stdClass();
$body->folderType = $folder_type;
$body->name = $name;
$body->type = 'rich text';
$body->value = $content;
$body_encoded = json_encode($body);
echo $url = $this->url . $endpoint . ".json?access_token=" . self::$token;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_encoded);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
The reason for the Content-Type header was a suggestion from Marketo: https://www.screencast.com/t/CL5ZtPo1o
This is the answer from the request I keep getting:
object(stdClass)#1934 (4) {
["success"]=>
bool(false)
["warnings"]=>
array(0) {
}
["errors"]=>
array(4) {
[0]=>
object(stdClass)#1935 (2) {
["message"]=>
string(20) "name cannot be null."
["code"]=>
string(3) "701"
}
[1]=>
object(stdClass)#1936 (2) {
["message"]=>
string(20) "type cannot be null."
["code"]=>
string(3) "701"
}
[2]=>
object(stdClass)#1937 (2) {
["message"]=>
string(101) "Token type is either null, blank or invalid. Please refer to the documentation for valid token types."
["code"]=>
string(3) "701"
}
[3]=>
object(stdClass)#1938 (2) {
["message"]=>
string(21) "value cannot be null."
["code"]=>
string(3) "701"
}
}
["requestId"]=>
string(16) "11d1#15b49284636"
}
You don't have to post token fields as JSON object: json_encode($body)
Fields are passed as request parameters or as a regular form
This request with works well for me:
POST https://123-FOO-456.mktorest.com/rest/asset/v1/folder/1039/tokens.json?value=TestTokenValue&folderType=Program&name=TestToken&type=text
In this case, you also don't have to specify content type Content-Type: x-www-form-urlencoded
I'm not PHP dev, but you can look here for examples how to post form data - PHP + curl, HTTP POST sample code?
Related
I am trying to get response from YTS API, however I can't understand what went wrong here. I do believe that status and status_message are objects.
Errors
PHP Notice: Trying to get property 'status' of non-object in /var/www/html/movies/inc/YTS.php on line 232
Notice: Trying to get property 'status' of non-object in /var/www/html/movies/inc/YTS.php on line 232
PHP Notice: Trying to get property 'status_message' of non-object in /var/www/html/movies/inc/YTS.php on line 233
Notice: Trying to get property 'status_message' of non-object in /var/www/html/movies/inc/YTS.php on line 233
PHP Fatal error: Uncaught Exception: API request failed. Error was: in /var/www/html/movies/inc/YTS.php:233
Code:
$url = "https://yts.mx/api/v2/list_movies.json?limit=1";
private function getFromApi($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if($e = curl_error($curl)) {
throw new Exception("Curl request failed: " . $e);
}
else {
$data = json_decode($response);
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
}
curl_close($curl);
}
var_dump($data)
object(stdClass)#1 (4) { ["status"]=> string(2) "ok" ["status_message"]=> string(20) "Query was successful" ["data"]=> object(stdClass)#2 (4) { ["movie_count"]=> int(40807) ["limit"]=> int(1) ["page_number"]=> int(1) ["movies"]=> array(1) { [0]=> object(stdClass)#3 (26) { ["id"]=> int(41604) ["url"]=> string(66) "https://yts.mx/movies/a-chinese-odyssey-part-one-pandoras-box-1995" ["imdb_code"]=> string(9) "tt0112778" ["title"]=> string(41) "A Chinese Odyssey Part One: Pandora's Box" ["title_english"]=> string(41) "A Chinese Odyssey Part One: Pandora's Box" ["title_long"]=> string(48) "A Chinese Odyssey Part One: Pandora's Box (1995)" ["slug"]=> string(44) "a-chinese-odyssey-part-one-pandoras-box-1995" ["year"]=> int(1995) ["rating"]=> float(7.6) ["runtime"]=> int(87) ["genres"]=> array(3) { [0]=> string(6) "Action" [1]=> string(9) "Adventure" [2]=> string(6) "Comedy" } ["summary"]=> string(391) "Fantasy adventure about the arrival of Buddhism in China. When the Goddess of Happiness tosses the Longevity Monk and his disciples out of heaven (because the Monkey King tried to attain immortality), the Monkey King is reincarnated as the Joker. He now spends his time chasing two jealous women. When one of them is dying, the Joker goes back in time in an attempt to save her. —Anonymous" ["description_full"]=> string(391) "Fantasy adventure about the arrival of Buddhism in China. When the Goddess of Happiness tosses the Longevity Monk and his disciples out of heaven (because the Monkey King tried to attain immortality), the Monkey King is reincarnated as the Joker. He now spends his time chasing two jealous women. When one of them is dying, the Joker goes back in time in an attempt to save her. —Anonymous" ["synopsis"]=> string(391) "Fantasy adventure about the arrival of Buddhism in China. When the Goddess of Happiness tosses the Longevity Monk and his disciples out of heaven (because the Monkey King tried to attain immortality), the Monkey King is reincarnated as the Joker. He now spends his time chasing two jealous women. When one of them is dying, the Joker goes back in time in an attempt to save her. —Anonymous" ["yt_trailer_code"]=> string(11) "ZPri1X1RVeo" ["language"]=> string(2) "cn" ["mpa_rating"]=> string(0) "" ["background_image"]=> string(95) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/background.jpg" ["background_image_original"]=> string(95) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/background.jpg" ["small_cover_image"]=> string(96) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/small-cover.jpg" ["medium_cover_image"]=> string(97) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/medium-cover.jpg" ["large_cover_image"]=> string(96) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/large-cover.jpg" ["state"]=> string(2) "ok" ["torrents"]=> array(2) { [0]=> object(stdClass)#4 (10) { ["url"]=> string(72) "https://yts.mx/torrent/download/0575F561D71DD1961F01FC2CBBE22AF5598A6CF1" ["hash"]=> string(40) "0575F561D71DD1961F01FC2CBBE22AF5598A6CF1" ["quality"]=> string(4) "720p" ["type"]=> string(6) "bluray" ["seeds"]=> int(0) ["peers"]=> int(0) ["size"]=> string(9) "810.78 MB" ["size_bytes"]=> int(850164449) ["date_uploaded"]=> string(19) "2022-04-20 20:07:01" ["date_uploaded_unix"]=> int(1650478021) } [1]=> object(stdClass)#5 (10) { ["url"]=> string(72) "https://yts.mx/torrent/download/633A2CAE8DE3C9F50B2E3B89A5BC6304E4770BFE" ["hash"]=> string(40) "633A2CAE8DE3C9F50B2E3B89A5BC6304E4770BFE" ["quality"]=> string(5) "1080p" ["type"]=> string(6) "bluray" ["seeds"]=> int(0) ["peers"]=> int(0) ["size"]=> string(7) "1.63 GB" ["size_bytes"]=> int(1750199173) ["date_uploaded"]=> string(19) "2022-04-20 21:16:40" ["date_uploaded_unix"]=> int(1650482200) } } ["date_uploaded"]=> string(19) "2022-04-20 20:07:01" ["date_uploaded_unix"]=> int(1650478021) } } } ["#meta"]=> object(stdClass)#6 (4) { ["server_time"]=> int(1650488761) ["server_timezone"]=> string(3) "CET" ["api_version"]=> int(2) ["execution_time"]=> string(4) "0 ms" } } Query was successful
Code that was working using file_get_content(), but knew to fail sometimes and so I was told to use curl.
private function getFromApi($url)
{
if (!$data = file_get_contents($url)) {
$error = error_get_last();
throw new Exception("HTTP request failed. Error was: " . $error['message']);
} else {
$data = json_decode($data);
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
}
}
Current code
<?php
$url = "https://yts.mx/api/v2/list_movies.json?limit=1";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if($e = curl_error($curl)) {
throw new Exception("Curl request failed: " . $e);
}
curl_close($curl);
$data = json_decode($response);
var_dump($data);
if (!$data) {
throw new Exception("JSON decode error: " . json_last_error_msg());
}
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
You're probably getting an empty response, so json_decode() is failing. You need to check for this, since an empty response doesn't necessarily trigger a curl error.
private function getFromApi($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if($e = curl_error($curl)) {
throw new Exception("Curl request failed: " . $e);
}
curl_close($curl);
$data = json_decode($response);
if (!$data) {
throw new Exception("JSON decode error: " . json_last_error_msg());
}
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
}
Also, there's no need to use else if the if block throws, since it never returns.
I have a radio service Icecast, And I need to get the data of the transmission, As are the listeners, Current song, etc.
The information is given to me in a Json file: http://213.5.176.74:8002/status-json.xsl
What I need is to create variables to store the listeners data, current song, etc.
I tried to do this:
<?php
$url="http://213.5.176.74:8002/status-json.xsl";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
When I write the code above I get this:
array(1) { ["icestats"]=> array(7) { ["admin"]=> string(19) "icemaster#localhost" ["host"]=> string(9) "127.0.0.1" ["location"]=> string(5) "Earth" ["server_id"]=> string(13) "Icecast 2.4.3" ["server_start"]=> string(31) "Wed, 08 Feb 2017 19:16:01 +0000" ["server_start_iso8601"]=> string(24) "2017-02-08T19:16:01+0000" ["source"]=> array(13) { ["audio_info"]=> string(10) "bitrate=24" ["genre"]=> string(3) "POP" ["listener_peak"]=> int(1) ["listeners"]=> int(0) ["listenurl"]=> string(28) "http://127.0.0.1:8002/stream" ["server_description"]=> string(6) "(null)" ["server_name"]=> string(6) "AutoDJ" ["server_type"]=> string(10) "audio/mpeg" ["server_url"]=> string(19) "https://habbosk.com" ["stream_start"]=> string(31) "Wed, 08 Feb 2017 19:19:02 +0000" ["stream_start_iso8601"]=> string(24) "2017-02-08T19:19:02+0000" ["title"]=> string(21) "AKONs Lonely Lyrics" ["dummy"]=> NULL } } }
The problem is that I do not know how to make variables with the previous content, so I use it on the website where I will put the statistics of the radio.
I appreciate your answers.
I speak Spanish, and I use google translate
Greetings.
Building on what you have... you are close!
You just need to parse the variable from the nested arrays returned to you.
Here is your same data variable, separated to show the nested array relationships:
array(1) {
["icestats"]=> array(7) {
["admin"]=> string(19) "icemaster#localhost" ["host"]=> string(9) "127.0.0.1" ["location"]=> string(5) "Earth" ["server_id"]=> string(13) "Icecast 2.4.3" ["server_start"]=> string(31) "Wed, 08 Feb 2017 19:16:01 +0000" ["server_start_iso8601"]=> string(24) "2017-02-08T19:16:01+0000"
["source"]=> array(13) {
["audio_info"]=> string(10) "bitrate=24" ["genre"]=> string(3) "POP" ["listener_peak"]=> int(1) ["listeners"]=> int(0) ["listenurl"]=> string(28) "http://127.0.0.1:8002/stream" ["server_description"]=> string(6) "(null)" ["server_name"]=> string(6) "AutoDJ" ["server_type"]=> string(10) "audio/mpeg" ["server_url"]=> string(19) "https://habbosk.com" ["stream_start"]=> string(31) "Wed, 08 Feb 2017 19:19:02 +0000" ["stream_start_iso8601"]=> string(24) "2017-02-08T19:19:02+0000" ["title"]=> string(21) "AKONs Lonely Lyrics" ["dummy"]=> NULL
}
}
}
So here is your original code...
<?php
$url="http://213.5.176.74:8002/status-json.xsl";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
And here we process the variable working deeper
$result = json_decode( $result, true ); /* UPDATED */
$stats = $result['icestats'];
echo 'Admin is: ' . $stats['admin'];
echo 'Server ID is: ' . $stats['server_id'];
// and deeper
$source = $stats['source'];
echo 'Genre is: ' . $source['genre'];
echo 'Song Title is: ' . $source['title'];
actually I'm working on coding an API for my business, I have an issue on my code and I couldn't figure out the problem, here is the class:
<?php
class ApiCaller
{
//some variables for the object
private $_app_id;
private $_app_key;
private $_api_url;
//construct an ApiCaller object, taking an
//APP ID, APP KEY and API URL parameter
public function __construct($app_id, $app_key, $api_url)
{
$this->_app_id = $app_id;
$this->_app_key = $app_key;
$this->_api_url = $api_url;
}
//send the request to the API server
//also encrypts the request, then checks
//if the results are valid
public function sendRequest($request_params)
{
//encrypt the request parameters
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
//create the params array, which will
//be the POST parameters
$params = array();
$params['enc_request'] = $enc_request;
$params['app_id'] = $this->_app_id;
//initialize and setup the curl handler
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request
$result = curl_exec($ch);
//json_decode the result
$result = #json_decode($result);
//check if we're able to json_decode the result correctly
if( $result == false || isset($result->success) == false ) {
throw new Exception('Request was not correct');
}
//if there was an error in the request, throw an exception
if( $result->success == false ) {
throw new Exception($result->errormsg);
}
//if everything went great, return the data
return $result->data;
}
}
The problem that there is no data returned from the sendRequest function, just throw 'Request was not correct' exception, I tried to test the code but with no luck. I'm using xampp-win32-5.6.8-0-VC11 and I have curl-7.43.0-win64 installed,,,
Any help will be appreciated and thanks.
Edit:
I use this code to test the function and it worked:
<?php
$_app_key = '28e336ac6c9423d946ba02d19c6a2632';
$_api_url = 'http://localhost/myAPI/simpletodo_api/';
$_app_id = 'APP001';
$params = array(
'controller' => 'todo',
'action' => 'read',
'username' => 'nikko',
'userpass' =>'test1234'
);
$enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $_app_key, json_encode($params), MCRYPT_MODE_ECB));
$pa = array();
$pa['enc_request'] = $enc_request;
$pa['app_id'] = $_app_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pa);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$errorNo = curl_errno ($ch );
$result = #json_decode($result);
var_dump($result);
and the result:
"object(stdClass)#1 (2) { ["data"]=> array(2) { [0]=> object(stdClass)#2 (5) { ["todo_id"]=> string(10) "1323343689" ["title"]=> string(10) "test title" ["description"]=> string(28) "test description weee wasted" ["due_date"]=> string(10) "12/02/2011" ["is_done"]=> string(4) "true" } [1]=> object(stdClass)#3 (5) { ["todo_id"]=> string(10) "1323429521" ["title"]=> string(3) "wee" ["description"]=> string(11) "adsa wasada" ["due_date"]=> string(10) "12/21/2011" ["is_done"]=> string(4) "true" } } ["success"]=> bool(true) }"
So where is the problem then??
Be carefull with the following line :
$result = #json_decode($result);
You are hiding any error message by using the #.
I would suspect you are not receiving a valid json response and then $result would be set to false, because json_decode would not work.
So what happens if you not getting a valid json back? Your code should handle that error case.
In order to debug, try to add var_dump($result); just after the curl_exec call, that should help you understand what's wrong.
As stated in the comments you should check the curl error codes
$errorNo = curl_errno ($ch );
http://php.net/manual/en/function.curl-errno.php
In the case of a 404 or other error you have no way to know in your code as formatted.
I'd like to display the number of likes for my Facebook page on my website. The previous method I used isn't working anymore since a couple of days.
When I call the Facebook graph API like this:
https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/549585444&format=json
It gives me the following output (fictional example):
[{"url":"http:\/\/www.facebook.com\/549585444","normalized_url":"http:\/\/www.facebook.com\/549585444","share_count":0,"like_count":122,"comment_count":0,"total_count":122,"click_count":0,"comments_fbid":null,"commentsbox_count":0}]
Now I like to echo the like count:
<?php
$fb_page = "549585444";
$url = "https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/".$fb_page."&format=json";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_returned = curl_exec($curl);
curl_close($curl);
$json_returned = json_decode($json_returned, true);
echo $json_returned['like_count'];
?>
But the number doesn't appear. Any idea why?
As you can see in the JSON output, the answer is wrapped in an array:
array(1) {
[0]=>
array(9) {
["url"]=>
string(33) "http://www.facebook.com/549585444"
["normalized_url"]=>
string(33) "http://www.facebook.com/549585444"
["share_count"]=>
int(0)
["like_count"]=>
int(0)
["comment_count"]=>
int(0)
["total_count"]=>
int(0)
["click_count"]=>
int(0)
["comments_fbid"]=>
NULL
["commentsbox_count"]=>
int(0)
}
}
To get the number output, you'll have to get the first item in the array by changing this row:
echo $json_returned['like_count'];
To this:
echo $json_returned[0]['like_count'];
I'm building a script to verify a transaction receipt with Apple's itunesconnect site (iphone dev) and I can't figure out where's the error in my code. I want to get the "status" value.
Please help me to find what am I doing wrong:
<?php
include("config.php");
$receipt = json_encode(array("receipt-data" => $_GET["receipt"]));
$response_json = do_post_request($url, $receipt);
$response = json_decode($response_json);
//Here's where I try to get the "status" key but doesn't work
echo $response['status'];
//echo $response->status;
function do_post_request($url, $data)
{
//initialize cURL
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
// howmany parameter to post
curl_setopt($ch, CURLOPT_POST, 1);
// the receipt as parameter
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result= curl_exec ($ch);
curl_close ($ch);
return $result;
}
?>
and the answer to the iPhone looks like:
{"receipt":{"item_id":"327931059", "original_transaction_id":"1000000000074412", "bvrs":"1.0", "product_id":"sandy_01", "purchase_date":"2009-09-29 16:12:46 Etc/GMT", "quantity":"1", "bid":"com.latin3g.chicasexy1", "original_purchase_date":"2009-09-29 16:12:46 Etc/GMT", "transaction_id":"1000000000074412"}, "status":0}
but only "status":0 matters for now
- Thank's
From the manual on json_decode()
Returns an object or if the optional
assoc parameter is TRUE, an
associative array is instead returned.
NULL is returned if the json cannot
be decoded or if the encoded data is
deeper than the recursion limit.
So either send TRUE for the 2nd parameter
$response = json_decode($response_json, true);
Or access the decoded JSON with object syntax
$response->status;
EDIT
Isolated test
$json = <<<JSON
{"receipt":{"item_id":"327931059", "original_transaction_id":"1000000000074412", "bvrs":"1.0", "product_id":"sandy_01", "purchase_date":"2009-09-29 16:12:46 Etc/GMT", "quantity":"1", "bid":"com.latin3g.chicasexy1", "original_purchase_date":"2009-09-29 16:12:46 Etc/GMT", "transaction_id":"1000000000074412"}, "status":0}
JSON;
$response = json_decode( $json );
echo $response->status;
$response2 = json_decode( $json, true );
echo $response2['status'];
Output is
00
You should be able to use:
$response->status;
Passing an optional param of true to the json_decode function will bring the results back as an associative array.
Have you checked your response_json variable to check that the data is being deserialised correctly? i.e:
var_dump($response);
Which should yield:
object(stdClass)#1 (2) {
["receipt"]=>
object(stdClass)#2 (9) {
["item_id"]=>
string(9) "327931059"
["original_transaction_id"]=>
string(16) "1000000000074412"
["bvrs"]=>
string(3) "1.0"
["product_id"]=>
string(8) "sandy_01"
["purchase_date"]=>
string(27) "2009-09-29 16:12:46 Etc/GMT"
["quantity"]=>
string(1) "1"
["bid"]=>
string(22) "com.latin3g.chicasexy1"
["original_purchase_date"]=>
string(27) "2009-09-29 16:12:46 Etc/GMT"
["transaction_id"]=>
string(16) "1000000000074412"
}
["status"]=>
int(0)
}