I tried use easy curl to get facebook code and access_token via curl. So that I can post message to my wall. I know sdk, but if I only use easy curl way?
some fault return:
Method Not Implemented
Invalid method in request
Here is my code. BY THE WAY: How to remember a access_token if it is still valid in 1 hour period time? Thanks.
$code_url = "https://graph.facebook.com/oauth/authorize?client_id=".$app_id."&redirect_uri=".urlencode($canvas_page_url)."&type=client_cred&display=page&scope=user_photos,publish_stream,read_stream,user_likes";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$code_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
$fb_code = curl_exec($ch); // get code
curl_close($ch);
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$app_id."&client_secret=".$app_secret."&redirect_uri=".urlencode($canvas_page_url)."&code=".$fb_code."";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$token_url);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($curl, CURLOPT_HEADER ,0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER ,1);
$result = curl_exec($curl);
curl_close($curl);
echo $result; //get token for post to wall
EDIT:
$app_id = "14XXXXXXXX";
$app_secret = "77XXXXXXXXXXXXXXXXXXXXXXX";
function get_app_access_token($app_id, $secret) {
$url = 'https://graph.facebook.com/oauth/access_token';
$token_params = array(
"type" => "client_cred",
"client_id" => $app_id,
"client_secret" => $app_secret
);
return str_replace('access_token=', '', post_url($url, $token_params));
}
$token = get_app_access_token($app_id,$app_secret);
echo $token;
Try these helper methods which will make a cURL call to the graph API and return an application access_token.
This function takes a url and an array of parameters and makes a POST via cURL:
function post_url($url, $params) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params, null, '&'));
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
This function takes your app ID and secret provided in the developer app and returns an active access_token for your app:
function get_app_access_token($app_id, $secret) {
$url = 'https://graph.facebook.com/oauth/access_token';
$token_params = array(
"type" => "client_cred",
"client_id" => $app_id,
"client_secret" => $secret
);
return str_replace('access_token=', '', post_url($url, $token_params));
}
You can call the method like so $token = get_app_access_token('APP_ID','SEKRET');
They really ought to make this clearer on the FB guide, but here's what worked for me. Unlike what a lot of people are saying online, you do NOT do a GET curl call but you still do a POST call.
So, the URL you post to will be "https://graph.facebook.com/oauth/access_token?"
And then, your POST variables that you'll feed CURLOPT_POSTFIELDS will be something like:
"client_id=YOUR_CLIENT_ID&redirect_uri=" . urlencode("YOUR_URL") . "&client_secret=YOUR_CLIENT_SECRET&code=YOUR_RECEIVED_CODE"
I was literally trying for at least 1.5 hours trying to get this to work. Every time I went to the URL in a browser it was fine, and every time I tried to run a GET curl command, or a POST command where all the variables were still in the url (and not specified in POSTFIELDS) it failed. It was really annoying.
Related
Hello stackoverflow members.
I'm not a person who likes to ask for a help but in this case it's IMO the only way to solve my problem. Google didn't help me much.
So. My problem:
I want to get some data using Twitch API. Sounds easy? I wish it was. Below I'm posting my actual code (it's small but it was modified various of times and now it look like...):
$user = json_decode(file_get_contents('https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=MY_CORRECT_CLIENT_ID&redirect_uri=http://localhost/php/twitch.php&scope=user_read'), true);
print_r($user); // returns nothing
$token = $user['access_token'];
print_r($token); // same as above
$ch = curl_init();
// some stupid curls
curl_setopt($ch, CURLOPT_URL, 'https://api.twitch.tv/kraken/streams/followed');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Authorization: OAuth '.$token );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$retval = curl_exec($ch);
curl_close($ch);
$result = json_decode($retval, true);
It returns... Nothing. So I used ready solution from discussions.twitch. (I wish I could write the name of the author of this code but I'm too tired to search it again. Either way thanks!):
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
$response = json_decode($data, true);
//var_dump($response);
$access_token = $response["access_token"];
echo $access_token;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$returnobj = curl_exec($ch);
curl_close($ch);
return $returnobj;
}
$testobj = json_decode(get_data("https://api.twitch.tv/kraken/user?oauth_token=".$access_token."&client_id=".$fields['client_id']));
echo "<br>Data: ";
print_r($testobj);
This code above is a bit better. Only a bit. It returns Error 401. Why? Because it can't get auth token. Well, it's something but not what I wanted to get. What should I do now? Maybe it's fault of localhost address?
FAQ(?):
Yes, I'm using correct data from my Twitch application settings page.
Yes, I'm confused
You're making two calls to the Twitch API, and you need to debug them independently.
For now, just skip the second call. Focus on the one where you grab your access token.
Try this:
// to start, just use the code you've already got:
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
// Now, here we believe the first error comes into play, so let's check it out
print_r($data); // confirm that this is not what we want
$info = curl_getinfo($ch); // let's get some details about that last request
// print it out and see what we get
echo '<pre>';
print_r($info);
echo '</pre>';
... that should give you a starting point to figure out what's going on. If you see an auth token, then you're not accessing it in the right way. If you don't, the info will give you some information about why.
I don't know what redirect_uri is (can you link to docs that explain it?) so I can't know if the localhost reference is a problem there.
I just want to use "file_get_html" to get content of specific pages, but this content just avaiable for loggin user, is there any way to send cookie to let target site know that the page is accessed by logged in user.
require_once 'simple_html_dom.php';
$opts = array("Cookie: __qca=P0-1170249003-1395413811270"); //__qca=P0-1170249003-1395413811270
$current_url = 'http://abc.xyz';
// But it will be redirect to
$url = 'http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz'
$context = stream_context_create($opts);
$html = file_get_html($url, FALSE, $context);
echo $html;
I do something like this, but it doesn't work.
How Can I do this with Curl?
Thanks.
$ch = curl_init(); // your curl instance
curl_setopt_array($ch, [CURLOPT_URL => "http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz", CURLOPT_COOKIE => "__qca=P0-1170249003-1395413811270"], CURLOPT_RETURNTRANSFER => true]);
$result = curl_exec($ch); // request's result
$html = new simple_html_dom(); // create new parser instance
$html->load($result); // load and parse previous result
In this example I used curl_setopt_array() to set the various CURL parameters instead of calling curl_setopt() for each one of them.
CURLOPT_URL sets the target URL, CURLOPT_COOKIE sets the cookies to send, if there are multiple cookies then they must be separated with a semicolon followed by a space, finally the CURLOPT_RETURNTRANSFER tells CURL to return the server's response as a string.
curl_exec() executes the request and returns its result.
Then we create an instance of simple_html_dom and load that previous result into it.
Thank you so much #andre, I spent all evening yesterday to find the solution :
The first we make curl exe to login to google account.
and save cookie to a text file (exam : "/tmp/cookie.txt")
and the next time everything we have to do is only take cookie content in this file to get remote content.
<?php
require_once 'simple_html_dom.php';
// Construct an HTTP POST request
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "youracc#gmail.com",
"Passwd" => "yourpasswd",
"service" => "blogger",
"source" => "your application name"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
// Execute
$response = curl_exec($curl);
echo $response;
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: " . $auth;
// Include the Auth string in the headers
// Together with the API version being used
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
$url = 'http://testlink.html';
$curl = curl_init();
// Make the request
curl_setopt($curl, CURLOPT_URL, $url );
//curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$html = new simple_html_dom(); // Create new parser instance
$html->load($response);
foreach($html->find('img') as $img) {
//echo $img->src . '</br>';
}
Today I tried to post a like via PHP (Curl) without luck. The output is that a token is required but I used a working token. I tried the same token with JS and it works.
Did Instagram changed some things bout PHP?
Here is my code:
<?php
$media_id = '615839918291043487_528338984';
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes?";
$access_token_parameters = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba',
'action' => 'like'
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_GET,true);
curl_setopt($curl,CURLOPT_GETFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
?>
Output.:
{"meta":{"error_type":"OAuthParameterException","code":400,"error_message":"Missing client_id or access_token URL parameter."}}
I tried it on several server, with several proxies, several client and token. Hopefully you know what's going on.
To add a like to a photo you need to do it via POST. The following is an modified version of your code to do this.
<?php
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes";
$fields = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
My code, which actually perfectly works with Linkedin and Meetup APIs, doesn't work with Eventbrite API and I definitely don't understand why :
$params = array(
'grant_type' => 'authorization_code',
'client_id' => EVENTBRITE_CONSUMER_KEY,
'client_secret' => EVENTBRITE_CONSUMER_SECRET,
);
// Eventbrite API access token request
$url = 'https://www.eventbrite.com/oauth/token?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(array('http' => array('method' => 'POST')));
// Retrieve access token information
$response = file_get_contents($url, false, $context);
I precise that the API login part to get the authorization code seems to work perfectly well.
Here is the PHP error :
Warning: file_get_contents(https://www.eventbrite.com/oauth/token?grant_type=authorization_code&client_id=ZZ6PPQOMTKSXIHEKLR&client_secret=QQDDIS4RBZXI6ONO7QEYEUZ4JB2ABQQG6K3H7CBD6M5QWK5GSK&code=O63YZASRAYMOUHRMH5AH): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD REQUEST in /var/www/include/actions.php on line 102
Thanks by advance if anybody has a clue :)
UPDATE :
I finally found where is the problem (even if I don't understand why) :
file_get_contents doesn't seem to be a good method to access the oauth page, I used curl instead :
$request_url = 'https://www.eventbrite.com/oauth/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
I hope it will help anybody encountering the same issue ;)
Just so that this question doesn't continue to show up as unanswered in an auto-email, I'm going to add your answer from your update here -- hope that's alight!
file_get_contents doesn't seem to be a good method to access the oauth page, I used curl instead:
$request_url = 'https://www.eventbrite.com/oauth/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
Thanks for making it easy by answering your own question! ;)
I have a news form on my website. After creating this news message I want to publish it on Facebook. I tried alot of things, but nothing was working. Here is my class:
<?php
class Facebook {
const FACEBOOK_APP_ID = 'MY_APP_ID';
const FACEBOOK_APP_SECRET = 'MY_APP_SECRET';
const FACEBOOK_ACCESS_TOKEN_URI = 'https://graph.facebook.com/oauth/access_token';
const FACEBOOK_FEED_URI = 'https://graph.facebook.com/app/feed';
private function getAccessToken() {
$params = array(
'client_id' => self::FACEBOOK_APP_ID,
'client_secret' => self::FACEBOOK_APP_SECRET,
'grant_type' => 'client_credentials',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_ACCESS_TOKEN_URI);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$data = curl_exec($ch);
curl_close($ch);
return substr($data, strpos($data, '=') + 1);
}
public function sendFeed() {
$params = array(
'access_token' => $this->getAccessToken(),
'message' => $message,
'name' => $name,
'link' => $url,
'description' => $description,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_FEED_URI);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close ($ch);
return $data;
}
}
If I call the method sendFeed() it returns the following:
{"id":"404322099626551_404397542952340"}
I think the submit was successfull, but when I visit my page on facebook, there is no new feed. What am I doing wrong? I searched the complete day and couldn't get it to work. I thank you for your help.
What you are doing here is posting it on your user's feed. You are using a user access token. What you want to use is a page access token.
You'll need the manage_pages permission to perform tasks on behalf of your page.
In addition you should consider using the official PHP SDK, it'll make accessing Facebook's API much easier and improve readability.