I am collecting an access_token for facebook web app
so, I have the following:
$fb_url = "https://graph.facebook.com/oauth/authorize?type=user_agent& .
client_id=132456789&redirect_uri=http%3A%2F%2Fmysite.com .
&scope=user_photos,email,user_birthday,user_online_presence";
When I go to that URL it forwards me to:
mysite.com?access_token=5sdf5s5wrrg4e645e645
So how can I fire the URL and collect variable access_token without actually going there which obviously cannot happen... if that makes sense!
Generally speaking, you need to make a curl request programmatically and interpret the response. Practically it would be easier if you used a specialized "facebook connector" class. Did you check out Facebook's developer docs?
You could try to send a HTTP-Request manually and then work with the result
http://php.net/manual/en/httprequest.send.php
how can I fire the URL and collect variable access_token without actually going there
You can't.
You can however actually go there without sending the user's browser to that URL, if that is what you mean. You can do that using cURL, which makes that request serverside. You can then present the result to the user, or do whatever you want to do with it.
Here's how I did it - facebook sdk is daunting at times then all of a sudden it all makes stupid sense!
require '/home/***/public_html/pages/social_login/fb_lib/facebook.php';
$config = array();
$config[‘appId’] = '__APP_ID__';
$config[‘secret’] = '__SECRET__';
$facebook = new Facebook($config);
//TO GET ACCESS TOKEN
$access_token = $facebook->getAccessToken();
Related
I have stored the access_token and PageId and i wanted to know is it possible to share a message when offline Open Graph API i mean using curl.
I am using below code
$page_id = 'XXXXXXXX';
$token = 'XXXXXXXXXX';
$app_namespace = 'test_app';
$ret_obj = $facebook->api('/'.$page_id .'/'.$app_namespace .':test','access_token'=>$token,'post', array(
'testing' => 'http://example.com/meta.php',
Even i had accessed offline_access too share isn't working.
The array you post must have a "message" element - you have "testing". This won't work as a facebook post does not have a testing element.
Maker sure you follow the documentation exactly!
Also, wrap your API calls in a try/catch block, and catch the errors. This gives you a clue as to what is going wrong.
I've been implementing an OAuth login via the Google Identity toolkit in php. I've got as far as getting an authenticated session, the userdata, id, photo etc, which seems to be working more or less ok.
However, I'd like to be able to login using methods that don't rely on redirection on the user's browser (thinking of remote APIs for an application), but bit lost on how to achieve this.
Imagine a request which is something like:
$details = new stdClass();
$details->secret = $config->secret;
$details->client_id = $config->client_id;
$details->app_name = 'my awesome oauth app';
$details->login = array();
$details->login['email'] = 'some google account email # example.com';
$details->login['password'] = '1234';
$token = $this->do_auth($details);
if($token) {
// do stuff, setup cookies, insert token in session table etc
}
I'm using CodeIgniter. Are there any libraries that can do this..? I've seen android apps doing similar things, using custom login forms, so I'm guessing it's achievable in php.
You HAVE to redirect, it's a core essential of the way OAuth works, there is no way around this. That's why there is a redirect_uri parameter.
You only have to do this once though: when the user is logging in and you are requesting an access token. After that, you simply use curl for example to request your data.
I have started off by reading Displaying Facebook posts to non-Facebook users which is of some use but I cannot believe it is this difficult to get a public feed from Facebook.
The page I want a feed from is public, you do not need to be logged into get to it.
Am I right in presuming that I need an access_token to get to this information, attempting to access the URL without results in an OAuth error.
So the flow should be like this (massively, overly complex):
Authenticate using a user (what if the user isn't on Facebook?)
Some complex OAuth nonsense - just to read the feed, I do not even want a like button or post to wall functionality
Get the feed using a PHP request to the correct URL with the user's access_token
Render the feed
Assuming the user isn't on Facebook, what do you do, use a generic app to get the feed?
Hardcode an auth request to Facebook using my generic app's ID and secret
Some complex OAuth nonsense
Get the feed using a PHP request to the correct URL with the app's access_token
Render the feed
Oh no, the auth has expired, re-auth and capture this new access_token for use in future requests.
This seems really complex for no reason other than Facebook wants to know EVERYTHING that is going on, it'd be easier to do a cURL and scrape the content from the public URL using XPath.
Any help on this would be great.
Thanks,
Jake
EDIT
An edit to show this is not an exact duplicate.
I had this working with an access_token in place, but now it fails, the token has expired and I can no longer use it to obtain information from the public wall.
I attempted to extend the expiration date of this token using the methods mentioned in other posts but this didn't work and the expiration was not extended - we are now here, with an invalid token and no further along.
It seems that the manual process of having to approve the OAuth request means that it is impossible to programatically get the feed of a public page.
Two years later, you can programmatically do this with a Facebook App (an example using PHP and Slim): https://developers.facebook.com/apps/
$base_api="https://graph.facebook.com/";
$client_id="XXXXXX";
$app_secret="XXXXXX";
//get a profile feed (can be from a page, user, event, group)
$app->get('/feed/:profileid/since/:start_date', function ($profile_id,$start_date) {
$start_time=date('m/d/Y h:i:s',$start_date);
$request = new FacebookRequest(
getSession(),
'GET',
'/'.$profile_id.'/feed?since='.$start_time
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
//do something with $graphObject
});
function getSession(){
$session = new FacebookSession(getAccessToken());
return $session;
}
function getAccessToken(){
global $base_api, $client_id, $app_secret;
$url=$base_api."oauth/access_token?client_id=".$client_id."&client_secret=".$app_secret."&grant_type=client_credentials";
$str = file_get_contents($url);
$token = str_replace ( "access_token=" , "" , $str );
return $token;
}
I have some success with reading in the direct feed without tokens etc.
(using magpie, simplepie or querypath or similar).
http://www.facebook.com/feeds/page.php?format=rss20&id=........
http://www.facebook.com/feeds/page.php?format=atom10&id=........
found on: http://ahrengot.com/tutorials/facebook-rss-feed/
Facebook has changed how to retrieve a public Facebook page's feed since the other answers were posted.
Check out my answer/question. It's not PHP, but it provides the URLs and process you need.
I'm working on building a small web app connecting into the instagram API. Currently using this library on GitHub which makes things a bit easier. I can connect and initially login fine, and the page will display all user data.
But once you refresh the page all the data is lost, and it appears the script can't find my access token anymore. I tried storing this into a PHP session variable - but maybe I'm doing the whole process incorrectly? I just want to keep the same user session throughout an entire website once the OAuth is performed.
You can check out the small app live here: http://spyrestudios.com/demos/instagram-api/index.php
Additionally my callback URL is http://spyrestudios.com/demos/instagram-api/instagammy.php - this is the script which will work right after you connect. But try refreshing the page and all the data is gone! Also here is my bit of code which *should use the library to store the current user's access token:
session_start();
require_once 'Instagram.php'; // the library code
$config = array(
'client_id' => 'f0d225aa955c4bd9ae563f87f831efab', // Your client id
'client_secret' => '377b77afc1274a89bd2df7d77e934689', // Your client secret
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://spyrestudios.com/demos/instagram-api/instagammy.php', // The redirect URI you provided when signed up for the service
);
// Instantiate the API handler object
$instagram = new Instagram($config);
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
Really struggling for a solution, so I'd appreciate any help I can get. Willing to post examples of my code if needed..
Thanks in advance!
What you have already looks fine (although I have no experience in Instagram), assuming that $accessToken is actually being stored correctly in the session.
But surely at some point you need to feed back in $accessToken so that it can be verified. Like I said, I've not used Instagram before, so I don't know how you would do this.
Just in case you still care..
The problem is that refreshing is hitting the oauth landing page again when you refresh or back, but there is no authorization for it to collect the information from. In theory you could just wrap your setting of the session variable around a check:
$instagram = new Instagram($config);
$accessToken = $instagram->getAccessToken();
if ($accessToken != '')
$_SESSION['InstagramAccessToken'] = $accessToken;
That would stop an unwanted to call to your oauth landing page from clearing the current session value.
But better still would be to have the landing page redirect to a different page for the display. ie have your instagammy.php end there and add a
header("Location: http://spyrestudios.com/demos/instagram-api/dosomethinghere.php");
die();
That way the user won't ever see the "instagammy.php" page in their history and won't be able to go back to it.
This work for me, instead the original file instagammy.php
$instagram = new Instagram($config);
if ($_SESSION['InstagramAccessToken'] == ''){
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
}else{
$accessToken = $_SESSION['InstagramAccessToken'];
$instagram->setAccessToken($_SESSION['InstagramAccessToken']);
}
I've successfully made my way through the LinkedIn OAuth process (using the REST API - OAuth 1.0a). However I'm having trouble with my first API call after the callback. I set the UserToken, UserTokenSecret and UserVerfier in the library I am writing, and this call this function to get my profile information:
public function getUserProfile()
{
$consumer = new OAuthConsumer($this->consumer_key, $this->consumer_secret, NULL);
$auth_token = new OAuthConsumer($this->getUserToken(), $this->getUserTokenSecret());
$access_token_req = new OAuthRequest("GET", $this->access_token_endpoint);
$params['oauth_verifier'] = $this->getUserVerifier();
$access_token_req = $access_token_req->from_consumer_and_token($this->consumer,
$auth_token, "GET", $this->access_token_endpoint, $params);
$access_token_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,
$auth_token);
$after_access_request = $this->doHttpRequest($access_token_req->to_url());
$access_tokens = array();
parse_str($after_access_request,$access_tokens);
# line 234 below
$access_token = new OAuthConsumer($access_tokens['oauth_token'], $access_tokens['oauth_token_secret']);
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
var_dump($after_request);
}
The function var_dumps a string, which is the basic synopsis of my profile:
string(402) " User Name etc. etc. http://www.linkedin.com/profile?viewProfile=&key=28141694&authToken=HWBC&authType=name&trk=api*a137731*s146100* "
That's good. However, the minute I refresh the page, the same function call fails with:
Undefined index: oauth_token, line number: 234
(this line marked with comment in above code block).
Then, of course, the var_dump reports this error from LinkedIn:
string(290) " 401 1310652477038 R8MHA2787T 0 [unauthorized]. The token used in the OAuth request is not valid. "
something to note:
the user token, secret, and verifier are persisted during the initial authorization callback (right before this function is called). So, they are the same during the first call (when it works, right after coming back from linkedin) and during a page reload (when it fails on line 234).
Also, I must admit I'm not 100% sure I understand everything that's going on in this function. I actually took examples from this tutorial (about a different service, not linkedin) http://apiwiki.justin.tv/mediawiki/index.php/OAuth_PHP_Tutorial and combined it with the information I gathered from the LinkedIn API documentation, spread throughout their developer site. Most notable was the addition of the 'verifier' which the tutorial did not use.
Any insight into this problem would be greatly appreciated. Thanks in advance.
-Nick
UPDATE
The only way I've been able to get this going is to do a new OAuth handshake every single time. Is this the way it's supposed to happen? I was under the impression that once I got my user token/secret and verifier, that I could then use these for continuous API calls until the token expired or was revoked.
As it is now, every time the page reloads I'm requesting a new user token, secret and verifier, then immediately calling to get the user profile (which succeeds). Next reload, I get a whole new key/secret and verifier. Seems like quite a lot of work for each call, and as I understood it, you should be able to perform offline operations with this method - and if I need new authorization each time, then I guess I can't do that?
Well. I've finally figured out what was going on so thought I'd post the answer here, just in case someone else runs into this.
The example that I was using as a guide was flawed. After the access token is retrieved, you should then create a new OAuthRequest object, instead of using the existing $access_token_req instance.
So this:
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
Should be changed to this:
$api_req = new OAuthRequest("GET", $this->api_url.$api_call);
// prepare for get profile call
$api_req = $api_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$api_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($api_req->to_url());