Google shortner issu - php

So i have a small PHP script to generate short links, it work but some times i got this error :
Undefined property: stdClass::$id","file":ShortLink.php","line":31
This is my script :
<?php
class ShortLink {
public static function generateShortLink($longUrl)
{
//This is the URL you want to shorten
$apiKey = 'MY_API_KEY';
//Get API key from : http://code.google.com/apis/console/
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
//change the response json string to object
$json = json_decode($response);
curl_close($curlObj);
return $json->id;
}
}
When i start worked with this script 6 or 7 months ago i hadn't this error but now i start get it and i have no idea why, so please if someone has any idea i will be very appreciative.
Update :
When i vardump my $json i get that :
{ ["domain"]=> string(11) "usageLimits" ["reason"]=> string(26) "userRateLimitExceededUnreg" ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up" ["extendedHelp"]=> string(36) "https://code.google.com/apis/console" } } ["code"]=> int(403) ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up" }}
So i wondered if Google limited the Google shorten service ?

class ShortLink {
public static function generateShortLink($longUrl)
{
//This is the URL you want to shorten
$apiKey = 'YOUR_SERVER_API_KEY';
//Get API key from : http://code.google.com/apis/console/
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
//change the response json string to object
$json = json_decode($response);
curl_close($curlObj);
if(!is_object($json))
{
return(false);
}
return $json->id;
}
}
$api = new ShortLink();
$shorturlid=$api->generateShortLink('http://avecsrthgdgnb.avcd');
echo $shorturlid;
are you using new console then enable URL Shortener API.

Sometimes because of network curl is not returned with response within 30 seconds (default time limit in php for a cmd to finish)
Try changing the time limit in php.ini or if that is not in your control or you do not want to modify it for all the php cmds try bool set_time_limit ( int $seconds ) before calling curl_exec
Update:
I see there is no id field in the json that is returned.
{ ["domain"]=> string(11) "usageLimits"
["reason"]=> string(26) "userRateLimitExceededUnreg"
["message"]=> string(40) "User Rate Limit Exceeded. Please sign up"
["extendedHelp"]=> string(36) "https://code.google.com/apis/console"
}
}
["code"]=> int(403)
["message"]=> string(40) "User Rate Limit Exceeded. Please sign up"
}
}
And if you closely see your User rate limit has been reached See here for details on limitation on using google apis. (You may try different IP i.e. different machine or different api key and same code may start working).
Hope this helps

Related

Twitter API curl request to oauth/request_token returns null - php 5.6

So I have this very simple app that must post to it's own profile, and that's basically it.
As far as I know right now, I need to go through 3-legged oauth to get my token, which, from what I've read, lasts basically forever, which is good.
anyway, I'm doing a little experiment, in which I curl my way to the oauth token I need to post.
Here's the code:
<?php
/*
The Request I wanna make, as described basically here: https://developer.twitter.com/en/docs/basics/authentication/api-reference/request_token
Part of this flow: https://developer.twitter.com/en/docs/basics/authentication/overview/3-legged-oauth
curl -XPOST
--url 'https://api.twitter.com/oauth/request_token'
--header 'OAuth
oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw",
oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1300228849",
oauth_consumer_key="OqEqJeafRSF11jBMStrZz",
oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D",
oauth_version="1.0"'
*/
$request_url = "https://api.twitter.com/oauth/request_token";
$consumer_secret = '[Consumer secret from my apps details > keys & tokens]';
$token_secret = '[token secret I got from my apps details > keys & tokens]';
$signature_key = "$consumer_secret&$token_secret";
$time = time();
$nonce = hash('md5', $time);
$callback = urlencode('http://localhost:8000/admin/twitter.callback.php');
$signature_method = "HMAC-SHA1";
$consumer_key = '[key from my apps detials > keys & tokens]';
$oauth_version = '1.0';
$payload = "oauth_nonce=$nonce&oauth_callback=$callback&oauth_signature_method=$signature_method&oauth_timestamp=$time&oauth_consumer_key=$consumer_key&oauth_version=1.0";
$to_be_signed = "POST&" . urlencode($request_url) . "&" . urlencode($payload);
$signature = base64_encode(hash_hmac('sha1', $to_be_signed, $signature_key, true));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . "OAuth
oauth_nonce=\"$nonce\",
oauth_callback=\"$callback\",
oauth_signature_method=\"$signature_method\",
oauth_timestamp=\"$time\",
oauth_consumer_key=\"$consumer_key\",
oauth_signature=\"$signature\",
oauth_version=\"$oauth_version\""));
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
var_dump($result);
// prints out NULL.
Something is wrong here, I just don't know what.
Thank you in advance.
EDIT:
Changing my headers to:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("OAuth
oauth_nonce=\"$nonce\",
oauth_callback=\"$callback\",
oauth_signature_method=\"$signature_method\",
oauth_timestamp=\"$time\",
oauth_consumer_key=\"$consumer_key\",
oauth_version=\"$oauth_version\",
oauth_signature=\"$signature\""));
will result in the following output:
array(1) {
["errors"]=>
array(1) {
[0]=>
array(2) {
["code"]=>
int(215)
["message"]=>
string(24) "Bad Authentication data."
}
}
}

How can I get a list of followers from one instagram account?

I am building a website and all i need is a list of followers from one Instagram account. I've gone through the steps to authenticate my web app with auth 2.0. I just realized that with this authentication I can only access the followers of the account to whom each access token belongs.
Is there any other way that I could access the followers from my desired account?
https://api.instagram.com/v1/users/4082347837/followed-by?access_token=AccessToken
Output of API request:-
{ ["meta"]=> object(stdClass)#2 (3) { ["error_type"]=> string(18) "APINotAllowedError" ["code"]=> int(400) ["error_message"]=> string(29) "you cannot view this resource" } }
Probably, you client_id is in a sandbox mode. You can't get info from accounts except whitelisted. You can leave the sandbox mode if you send you app for the review.
But there is a simplier solution. You can get public info from web version (wihout API) just with one call:
$otherPage = 'nasa';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
if ($data !== null) {
$follows = $data['user']['follows']['count'];
$followedBy = $data['user']['followed_by']['count'];
echo $follows . ' and ' . $followedBy;
}
}
Update.
Sorry, I've misunderstood your question. It is possible to get the list without API. You need csrf token and user id in cookies, then call the query:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.instagram.com/query/");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//You need the csrftoken, ds_user_id
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: ..."));
curl_setopt($ch, CURLOPT_POST, 1);
$userId = 528817151;
curl_setopt($ch, CURLOPT_POSTFIELDS,
"q=ig_user($userId) {
followed_by.first(10) {
count,
page_info {
end_cursor,
has_next_page
},
nodes {
id,
is_verified,
followed_by_viewer,
requested_by_viewer,
full_name,
profile_pic_url,
username
}
}
}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
var_dump($server_output);
You can obtain right cookies doing login action on Instagram web.

Unable to integrate Azure ML API with PHP

I tried integrating Azure ML API with PHP but unfortunately getting an error in response.
Updated: I have used request response API sending through json response
Below is the response obtained on executing PHP script:
array(1) { ["error"]=> array(3) { ["code"]=> string(11) "BadArgument"
["message"]=> string(26) "Invalid argument provided." ["details"]=> array(1)
{[0]=> array(2) { ["code"]=> string(18) "RequestBodyInvalid" ["message"]=>
string(68) "No request body provided or error in deserializing the request
body." } } } }
PHP Script:
$url = 'URL';
$api_key = 'API';
$data = array(
'Inputs'=> array(
'My Experiment Name'=> array(
"ColumnNames" => [['Column1'],
['Column2'],
['Column3'],
['Column4'],
['Column5'],
['Column6'],
['Column7']],
"Values" => [ ['Value1'],
['Value2'],
['Value3'],
['Value4'],
['Value5'],
['Value6'],
['Value7']]
),
),
'GlobalParameters' => new StdClass(),
);
$body = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$api_key, 'Accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = json_decode(curl_exec($ch), true);
//echo 'Curl error: ' . curl_error($ch);
curl_close($ch);
var_dump ($response);
I have followed few examples, still unable to crack it. Please let me know the solution for this.
According to the error information, I think the issue was caused by requesting the ML REST API without correct json body.
I suggest that you can refer to the article "Getting started with the Text Analytics APIs to detect sentiment, key phrases, topics and language" to correctly format your input rows in JSON as the request body and try again.
Hope it helps.
If you can update your question for specifying which ML REST API you used, I think it's very helpful for figuring out the issue.
Expect your update.

ERROR (100) : Parameters do not match any fields that can be updated

I am trying to post Facebook Page status as page(not user) through my script. This returns me an error 100.
Here I am generating temporary user_access_token from Graph Explorer with permission : manage_pages, publish_pages
Code:
<?php
$url='https://graph.facebook.com/v2.3/{$user_id}/accounts?access_token=USER_ACCESS_TOKEN';
$ch=curl_init();
CURL_SETOPT($ch,CURLOPT_URL,$url);
CURL_SETOPT($ch,CURLOPT_RETURNTRANSFER, 1);
$json=json_decode(curl_exec($ch));
$page_access_token=$json->data['0']->access_token;
curl_close($ch);
$page_id='xxx';
$message='helloworld';
$url="https://graph.facebook.com/v2.3/{$page_id}?access_token=$page_access_token";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $message);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$result = json_decode(curl_exec($curl));
var_dump($result);
?>
If everything goes well, a string "helloworld" should get posted on Facebook page. But here it is returning with an error :
object(stdClass)#5 (1) {
["error"]=>
object(stdClass)#6 (3) {
["message"]=>
string(61) "(#100) Parameters do not match any fields that can be updated"
["type"]=>
string(14) "OAuthException"
["code"]=>
int(100)
}
}
What is mistake here ? Thank you.
You're trying to post to /<PAGE_ID>
The correct endpoint for creating a post on a Page is /<PAGE_ID>/feed, documented here: https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed
A valid format for a basic call to create a post would be https://graph.facebook.com/v2.3/<PAGE_ID>/feed?message=helloworld&access_token=<ACCESS_TOKEN>

Get Media ID Instagram

Below is the code I am using
$decode = json_decode($json, true);
var_dump($decode);
This results in the below:
c.ak.instagram.com/hphotos-ak-xfa1/10666256_719752088073218_1127882203_a.jpg"
["full_name"]=> string(26) "Promote OLShop Harga Murah" ["bio"]=> string(0) "" ["id"]=>
string(9) "356515767" } } } }
How do I get Get Media ID?example results :
817757393383064097_356515767
Please help me.
$json = file_get_contents('https://api.instagram.com/v1/tags/gaul/media/recent?access_token=1463408808.e757b44.0738048e481448b48f1cbb23f70f0195&count=1');
$decode = json_decode($json, true);
$media_id = $decode['data'][0]['id']
If you took a look at Embedding you would find a suitable answer, for me i was in need for the media_id for a project, so i wrapped it into a function
function getMediaID($permalink) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.instagram.com/oembed?url=' . $permalink);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$oembed = curl_exec($ch);
curl_close($ch);
$oembed = json_decode($oembed, true);
return $oembed['media_id'];
}
That result you showed are when getting a USER data... not medias. To get media use some like:
https://api.instagram.com/v1/users/USERID/media/recent/?access_token=TOKEN&count=COUNT
Where:
USERID ir the user you want to get medias
TOKEN is your access token that enable you to use the API
COUNT to tell how much photos of that user you want to retrieve at this time
code by Bankzilla is working perfectly. I would upvote it , but for my reputation points are less :/. Also the code isnt echoing anything so the page will be blank.
Here is the code to display the media id. Copy it into a file with php extension for ex: getmedia.php and paste url where your are hosting it in browser and run it.
ex : www.myhost.com/mysite/getmedia.php?url="URL OF THE MEDIA HERE"
<?php
$permalink = $_GET["url"];
getMediaID($permalink) ;
function getMediaID($permalink) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.instagram.com/oembed?url=' . $permalink);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$oembed = curl_exec($ch);
curl_close($ch);
$oembed = json_decode($oembed, true);
echo $oembed['media_id'];
return $oembed['media_id'];
}
?>
You will use:
$search_response = curlRequest("get", "https://api.instagram.com/v1/users/self/media/recent/?access_token={$json_data['access_token']}");
Then:
$photo_id= $search_response['data'][$i]['id'];
echo $photo_id .'<br/>';
($i for exapmle data[1] , data[2] etc.) - (each image data)

Categories