Java Facebook离线访问分步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1059640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Facebook offline access step-by-step
提问by
UPDATE: Facebook
offline_access
permission is being deprecated. Please refer to the official documentationfor more information.
You'll have till May 1, 2012, at which date this setting will be disabled. refer to the Developer Roadmapfor more info.
更新:Facebook
offline_access
权限已被弃用。更多信息请参考官方文档。
您将在2012年5 月 1 日之前禁用此设置。有关更多信息,请参阅开发人员路线图。
After searching literally 1 day on facebook and google for an up-to-date and workingway to do something seemingly simple:
在 facebook 和 google 上搜索了 1 天后,寻找一种最新且有效的方法来做一些看似简单的事情:
I am looking for a step-by-step explanation to get offline_access for a user for a facebook app and then using this (session key) to retrieve offline & not within a browser friends & profile data.
我正在寻找分步说明,以便为 facebook 应用程序的用户获取 offline_access,然后使用此(会话密钥)离线检索而不是在浏览器朋友和个人资料数据中检索。
Preferrably doing this in the Fb Java API.
最好在 Fb Java API 中执行此操作。
Thanks.
谢谢。
And yes I did check the facebook wiki.
是的,我确实检查了 facebook wiki。
Update: Anyone?
更新:有人吗?
this:
http://www.facebook.com/authorize.php?api_key=<api-key>&v=1.0&ext_perm=offline_access
gives me offline_Access, however how to retrieve the session_key?
这个:
http://www.facebook.com/authorize.php?api_key=<api-key>&v=1.0&ext_perm=offline_access
给了我offline_Access,但是如何检索session_key?
Why can't facebook just do simple documentation, I mean there are like 600 people working there?
为什么 facebook 不能只做简单的文档,我的意思是有 600 人在那里工作?
The seemingly same question: Getting offline_access to work with FacebookDoes not answer how to retrieve the session key
看似相同的问题: 让 offline_access 与 Facebook 一起工作不回答如何检索会话密钥
Edit: I am still stuck with that. I guess nobody really tried such a batch access out yet...
编辑:我仍然坚持这一点。我想还没有人真正尝试过这样的批量访问......
回答by Leonid L
I know two solutions: Java and JavaScript
我知道两个解决方案:Java 和 JavaScript
Java : a. servlet code (don't forget to import relevant jar's) :
爪哇:servlet 代码(不要忘记导入相关的 jar):
String url="http://www.facebook.com/login.php?api_key=YOUR_API_KEY&v=1.0";
url+="&fbconnect=true&return_session=true&req_perms=offline_access,status_update";
url+="&next=http://YOUR_FaceBookCallback_SERVLET";
response.sendRedirect(url);
return;
//You will get prompt to log in to facebook and permit the extended permissions
//您将收到登录facebook并允许扩展权限的提示
b. Don't forget to define your ConnectUrl(in your facebook account application) as http://YourUrlFromWhereDoYouTurnToTheServletAbove
湾 不要忘记将您的 ConnectUrl(在您的 facebook 帐户应用程序中)定义为http://YourUrlFromWhereDoYouTurnToTheServletAbove
c. make another servlet : YOUR_FaceBookCallback_SERVLET (see above) with this code:
C。使用以下代码制作另一个 servlet:YOUR_FaceBookCallback_SERVLET(见上文):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String session = request.getParameter("session");
//from this string you can obtain your infinite session_key.In order to do this, parse this string as JSON.
//Save it in the database or in the other data storage
response.sendRedirect(ThePlaceThatYouWant);}
d. Use this secret session_key like this:
d. 像这样使用这个秘密 session_key:
FacebookXmlRestClient client = new FacebookXmlRestClient(YOUR_API_KEY, FACEBOOK_APPLICATION_SECRET,SECRET_SESSION_KEY);
client.setIsDesktop(false);
client.users_setStatus("YourMessage");
If anybody wants the JavaScript solution(the big hole in security) write me
如果有人想要 JavaScript 解决方案(安全性的大漏洞),请写信给我
回答by Jonathan Reyes
I did a tutorial not too long ago on my blog. It doesn't require any plugins or whatnot, it is done in PHP, and I have tested it. I did it for mainly wall posts, but after you authenticate you can use whatever function you want.
不久前我在我的博客上做了一个教程。它不需要任何插件或诸如此类的东西,它是用 PHP 完成的,我已经对其进行了测试。我主要是为墙上的帖子做的,但是在您进行身份验证后,您可以使用任何您想要的功能。
EDIT: Post no longer exists. FB API is updated anyway...
编辑:帖子不再存在。无论如何,FB API 已更新...
回答by Naren
I figured out how to "retrieve" the offline access infinite session key after a lot of hair-splitting, some trial and error & wondering about all the other productive ways I could have spent that time... agree facebook documentation could be a lot better
我想出了如何“检索”离线访问无限会话密钥经过大量的头发分裂,一些试验和错误以及想知道我可以花那段时间的所有其他有效方式......同意facebook文档可能很多更好的
1) If you are using the facebook-java-api.. then take a look at the facebook demo site for "mobile web" on how to format the URL for requesting offline access
http://itsti.me/index.php
1) 如果您使用的是 facebook-java-api .. 然后查看“移动网络”的 facebook 演示站点,了解如何格式化请求离线访问的 URL
http://itsti.me/index.php
<a href="http://www.facebook.com/connect/prompt_permissions.php?api_key=YOUR_API_KEY&ext_perm=publish_stream%2Coffline_access&next=http%3A%2F%2Fmysite%2Ffacebookconnect&cancel=http%3A%2F%2Fmysite%2Fhome&display=wap"><img alt="Connect" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_medium_long.gif" id="fb_login_image"/></a>
2) As to how get the offline session key from the session..The trick is : when facebook redirects the user to the "next" url right after granting offline access, you should get the facebook session "again"..this new session will have the infinite session key.
here is an example for mobile web...you should be able to figure it out for a regular website.The auth_token is used only for mobile web sites.. you may not need it for a regular web site
2)关于如何从会话中获取离线会话密钥..诀窍是:当 Facebook 在授予离线访问权限后立即将用户重定向到“下一个”网址时,您应该“再次”获取 facebook 会话..这个新会话将拥有无限会话密钥。
这是移动网络的示例...您应该能够为常规网站找出答案。auth_token 仅用于移动网站...您可能不需要它用于常规网站
FacebookJsonRestClient fbc = new FacebookJsonRestClient(MY_API_KEY, SECRET, sessionKey);
String auth_token = request.getParameter("auth_token");
System.out.println("infinite session kEY = " + fbc.auth_getSession(auth_token));
回答by Chris
With the new Facebook Graph API, things got a bit simpler but far less well documented. Here's what I did to be able to load my wall posts as me from a server side only (not part of a browser session) php script:
使用新的 Facebook Graph API,事情变得更简单了,但文档却少了很多。这是我所做的,以便能够仅从服务器端(不是浏览器会话的一部分)php 脚本加载我的墙贴:
create a facebook application, if you don't already have one usable for this project
http://www.facebook.com/developers/apps.php#!/developers/createapp.php
-- and set sandbox/developer mode on! @ Advanced Settings > Sandbox Mode > Enable (Lets only the developers of your application see it.) You'll need the Application ID (APP_ID) and Secret Key (SECRET_KEY) that are listed on your developer account summary of that application but not the old API Key.load in your browser, already logged in to fb as the account you want your server side app to connect as, and click "allow" for the requested permissions:
https://graph.facebook.com/oauth/authorize?client_id=APP_ID&scope=offline_access,read_stream&redirect_uri=http://www.facebook.com/connect/login_success.html
copy the "code" parameter from the resulting url's query string, use that in:
https://graph.facebook.com/oauth/access_token?client_id=APP_ID&redirect_uri=http://www.facebook.com/connect/login_success.html&client_secret=APP_SECRET&code=CODE_FROM_2
And copy the right hand side of access_token= in the resulting page's text, which will be in the structure of: APP_ID|HEXNUM-USER_ID|WEIRD_KEYnow download either from the graph api or the classic rest api using the oath access token you just got ala (where SOURCE_ID is the facebook id for the user/group/whatever that you are looking up):
<?php $stream = json_decode(file_get_contents("https://api.facebook.com/method/stream.get?source_ids=SOURCE_ID&access_token=ACCESS_TOKEN&format=json")); var_dump($stream); // this one gives a 500 internal server error from the http get if any of the fields are invalid, but only in php, not when loaded in a browser... weird. $feed = json_decode(file_get_contents("https://graph.facebook.com/SOURCE_ID/feed?fields=id,from,created_time,link,type&access_token=ACCESS_TOKEN")); var_dump($feed); ?>
创建一个 facebook 应用程序,如果您还没有可用于该项目的应用程序
http://www.facebook.com/developers/apps.php#!/developers/createapp.php
- 并设置沙箱/开发人员模式!@ 高级设置 > 沙盒模式 > 启用(仅让您的应用程序的开发人员看到它。)您需要该应用程序的开发人员帐户摘要中列出的应用程序 ID (APP_ID) 和密钥 (SECRET_KEY),但不需要旧 API 密钥。在您的浏览器中加载,已作为您希望服务器端应用程序连接的帐户登录到 fb,然后单击“允许”以获得请求的权限:
https://graph.facebook.com/oauth/authorize?client_id=APP_ID&scope=offline_access,read_stream&redirect_uri=http://www.facebook.com/connect/login_success.html
从结果 url 的查询字符串中复制“代码”参数,将其用于:
https://graph.facebook.com/oauth/access_token?client_id=APP_ID&redirect_uri=http://www.facebook.com/connect/login_success.html&client_secret=APP_SECRET&code=CODE_FROM_2
并在结果页面的文本中复制 access_token= 的右侧,其结构为:APP_ID|HEXNUM-USER_ID|WEIRD_KEY现在使用您刚刚获得的 oath 访问令牌从图形 api 或经典的 rest api 下载 ala(其中 SOURCE_ID 是用户/组/您正在查找的任何内容的 facebook id):
<?php $stream = json_decode(file_get_contents("https://api.facebook.com/method/stream.get?source_ids=SOURCE_ID&access_token=ACCESS_TOKEN&format=json")); var_dump($stream); // this one gives a 500 internal server error from the http get if any of the fields are invalid, but only in php, not when loaded in a browser... weird. $feed = json_decode(file_get_contents("https://graph.facebook.com/SOURCE_ID/feed?fields=id,from,created_time,link,type&access_token=ACCESS_TOKEN")); var_dump($feed); ?>
Noting that the graph api and rest api return not just different structures, but also different information -- so here, I prefer the results from the rest api (the first one) even though I like being able to restrict the fields in the new graph api (the second one).
注意到图形 api 和 rest api 不仅返回不同的结构,而且还返回不同的信息——所以在这里,我更喜欢 rest api(第一个)的结果,即使我喜欢能够限制新图中的字段api(第二个)。
Look at http://developers.facebook.com/docs/authentication/in the sections "Requesting Extended Permissions" and "Authenticating Users in a Web Application" for the official (sparse) details.
查看http://developers.facebook.com/docs/authentication/部分“请求扩展权限”和“在 Web 应用程序中对用户进行身份验证”中的官方(稀疏)详细信息。
If you want to do this routinely, i.e. programmatically, here's the automated version of steps 2+3:
如果您想定期执行此操作,即以编程方式执行此操作,请使用步骤 2+3 的自动化版本:
Put this on your web server as "facebook_access_token.php":
把它作为“facebook_access_token.php”放在你的网络服务器上:
<?php $token = explode('=', file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=APP_ID&redirect_uri=http://$_SERVER[SERVER_NAME]$_SERVER[PHP_SELF]&client_secret=APP_SECRET&code=" .
(get_magic_quotes_gpc() ? stripslashes($_GET['code']) : $_GET['code'])));
echo $token[1];
// store this, the access token, in the db for the user as logged in on your site -- and don't abuse their trust! ?>
And direct users in their browsers to:
https://graph.facebook.com/oauth/authorize?client_id=APP_ID&scope=offline_access,read_stream&redirect_uri=http://www.example.com/facebook_access_token.php
并在浏览器中引导用户:
https://graph.facebook.com/oauth/authorize?client_id=APP_ID&scope=offline_access,read_stream&redirect_uri=http://www.example.com/facebook_access_token.php
回答by Nemo
For session access, i had to use the loginurl provided by the facebook php api, as there seem to be 2/3 additional variables that it sends in the auth request, including return_session and session_version. Also the new php5-sdk sends the request to login.facebook.com instead of https://graph.facebook.com/oauth/authorize. Here's how i worked it out :
对于会话访问,我必须使用 facebook php api 提供的 loginurl,因为它在身份验证请求中发送了 2/3 的附加变量,包括 return_session 和 session_version。此外,新的 php5-sdk 将请求发送到 login.facebook.com 而不是https://graph.facebook.com/oauth/authorize。这是我如何解决的:
$b=new facebook(array('appId'=>APP_ID,'secret'=>SECRET))
$b=new facebook(array('appId'=>APP_ID,'secret'=>SECRET))
To ask for authentication :
要求认证:
$facebook->getLoginUrl(array('next'=>$redirect_uri,'req_perms'=>$scope))
$facebook->getLoginUrl(array('next'=>$redirect_uri,'req_perms'=>$scope))
Rember to include offline_access in $scope. Once you are redirected to this page (after logging in to fb, and granting permissions), you will have a $_GET['session'] in json format.
记得在 $scope 中包含 offline_access。一旦你被重定向到这个页面(登录到 fb 并授予权限后),你将有一个 json 格式的 $_GET['session'] 。
Just store it wherever you want (I do it in a database). The next time you wish to do something with the user's account, just use the following:
只需将其存储在您想要的任何位置(我在数据库中进行)。下次您希望对用户帐户执行某些操作时,只需使用以下命令:
$session = json_decode($db->query("SELECT ..."));//get session from db
$this->facebook->setSession($session);
$session = json_decode($db->query("SELECT ..."));//get session from db
$this->facebook->setSession($session);
After this any requests that the api makes will be via this user's access.
在此之后,api 发出的任何请求都将通过该用户的访问。
The worst thing about the current facebook graph api is (correct me if I'm wrong) that the current api neglects the session (which seems to be a remain from the old api) in all its documentation and only talks about the access_token. But the current api (php5-sdk) has got no feature to send an actual request using only the access_token. If there is a function to start a session a session using only the access_token, I'm not aware of it.
当前 facebook 图形 api 最糟糕的事情是(如果我错了,请纠正我)当前的 api 在其所有文档中都忽略了会话(这似乎是旧 api 的遗留),只讨论了 access_token。但是当前的 api (php5-sdk) 没有仅使用 access_token 发送实际请求的功能。如果有一个函数可以只使用 access_token 来启动一个会话,我不知道。
回答by Quentin
If you want finally want to use PHP, with the Facebook PHP SDK v3 (see on github), it is pretty simple. To log someone with the offline_access
permission, you ask it when your generate the login URL. Here is how you do that.
如果您最终想使用 PHP,使用 Facebook PHP SDK v3(参见 github),这非常简单。要登录具有该offline_access
权限的人,您在生成登录 URL 时询问它。这是你如何做到的。
Get the offline access token
获取离线访问令牌
First you check if the user is logged in or not :
首先检查用户是否登录:
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he is not, you generate the "Login with Facebook" URL asking for the offline_access
permission :
如果他不是,你会生成“用 Facebook 登录”的 URL 请求offline_access
许可:
if (!$user) {
$args['scope'] = 'offline_access';
$loginUrl = $facebook->getLoginUrl($args);
}
And then display the link in your template :
然后在您的模板中显示链接:
<?php if (!$user): ?>
<a href="<?php echo $loginUrl ?>">Login with Facebook</a>
<?php endif ?>
Then you can retrieve the offline access token and store it. To get it, call :
然后您可以检索离线访问令牌并存储它。要获得它,请致电:
if ($user) {
$token = $facebook->getAccessToken();
// store token
}
Use the offline access token
使用离线访问令牌
To use the offline access token when the user is not logged in :
在用户未登录时使用离线访问令牌:
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$facebook->setAccessToken("...");
And now you can make API calls for this user :
现在您可以为该用户进行 API 调用:
$user_profile = $facebook->api('/me');
Hope that helps !
希望有帮助!
回答by daaku
You want to start by reading the Server Side Flowsection in the authentication guide. Basically, start with this URL:
您希望首先阅读身份验证指南中的服务器端流程部分。基本上,从这个 URL 开始:
https://www.facebook.com/dialog/oauth
Add your application id(available here) to the URL, which in OAuth parlance is client_id
:
将您的应用程序 ID(可在此处获得)添加到 URL,在 OAuth 的说法中是client_id
:
https://www.facebook.com/dialog/oauth?client_id=184484190795
Add the offline_access
permissionor scope
in OAuth parlance:
添加offline_access
权限或scope
在 OAuth 说法中:
https://www.facebook.com/dialog/oauth?client_id=184484190795&scope=offline_access
Add a redirect_uri
which is where Facebook will redirect to after the user completes the authorization step ("Allow" or "Dont Allow", look at docs for response format or just try it out):
添加redirect_uri
用户完成授权步骤后 Facebook 将重定向到的位置(“允许”或“不允许”,查看响应格式的文档或尝试一下):
https://www.facebook.com/dialog/oauth?client_id=184484190795&scope=offline_access&redirect_uri=https%3A%2F%2Ffbrell.com%2Fecho
If you follow the link above, it will take you to a prompt, and then upon clicking Allow/Dont Allow it'll take you to a page that "echos" back the request. If you click Allow, you'll get a code
parameter back, which you can exchange for an access_token
by making an HTTP request to Facebook from your server, which does something along the lines of this:
如果您点击上面的链接,它将带您进入提示,然后在单击允许/不允许时,它将带您到“回显”请求的页面。如果您单击“允许”,您将code
返回一个参数,您可以access_token
通过从您的服务器向 Facebook 发出 HTTP 请求来交换该参数,该请求会执行以下操作:
https://graph.facebook.com/oauth/access_token?client_id=184484190795&client_secret=XXX&code=YYY&redirect_uri=ZZZ
You need to pass in your client_id
, your application secretmust be passed in as the client_secret
, the same redirect_uri
as you used earlier and the code
you received as the response. This will return the offline_access
enabled access_token
for that user.
您需要传入您的client_id
,您的应用程序机密必须作为 传入client_secret
,与redirect_uri
您之前使用的以及code
作为响应收到的相同。这将返回该用户的offline_access
启用access_token
。
One thing to keep in mind though is that even if you request offline_access
your application must gracefully handle invalid or expired access_tokens, as that can happen for various reasons.
但要记住的一件事是,即使您请求offline_access
您的应用程序也必须妥善处理无效或过期的 access_token,因为各种原因可能会发生这种情况。