从Facebook获取用户access_token

时间:2012-10-31 10:14:10

标签: facebook facebook-c#-sdk

我正在构建一个应用程序,允许用户从应用程序向他们的Facebook发布消息。问题我有,我不知道如何获取用户access_token的publish_stream权限。

这是我到目前为止所得到的:

        var fb = new FacebookClient();
        dynamic result = fb.GetLoginUrl(new
        {
            client_id = AppID,
            client_secret = AppSecret,
            grant_type = "client_credentials",
            scope = "publish_stream",
            state = "http://localhost:17578/Facebook.aspx",
            redirect_uri = "http://localhost:17578/Facebook.aspx"
        });

工作正常,它在查询字符串中返回'代码'。但是,我不知道如何处理该代码。 “旧的”Facebook C#sdk包含具有FacebookOAuthClient方法的ExchangeCodeForAccessToken()类,但我不知道新SDK中替换此静态方法的原因。

所以问题实际上是:如何交换为access_token返回的代码?

1 个答案:

答案 0 :(得分:2)

获得代码查询字符串参数后,您必须调用Facebook Graph API以获取访问令牌。

https://developers.facebook.com/docs/howtos/login/server-side-login/

FacebookClient client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new { client_id = Settings.Social_Facebook_App_Id, client_secret = Settings.Social_Facebook_Secret_Key, code = Request.QueryString["code"], redirect_uri = Settings.Social_Facebook_Login_Redirect_URI });
if (result.error == null)
{
    Session["AccessToken"] = client.AccessToken = result.access_token;
    dynamic user = client.Get("me", new { fields = "name,username,email" });
    string userName = user.username;

    mu = Membership.GetUser(userName);
    if (mu == null)  // Register
    {
        RegisterModel rm = new RegisterModel();
        rm.Email = user.email;
        rm.UserName = userName;
        return View("Register", rm);
    }
    else
    {
        FormsAuthentication.SetAuthCookie(userName, true);
        return RedirectToAction(MVC.Home.Index());
    }
}