C# Facebook SDK extend an accesstoken to 60 days

主宰稳场 提交于 2019-12-03 21:24:26

Use the following code with Facebook.NET and Json.NET in a handler file that is your callback.

public void ProcessRequest (HttpContext context)
    {
        if (context.Request.Params.Get("error_reason") == "user_denied")
        {
            context.Response.Write("Access Denied");
        }
        else if (context.Request.Params.Get("code") != null && context.Request.Params.Get("code") != "")
        {
            string shorttoken = HttpUtility.ParseQueryString(HttpUtil.GetHtmlPage("https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&redirect_uri=http://huadianz.me/mvp/auth/FacebookOAuth.ashx&client_secret=" + APP_SECRET + "&code=" + context.Request.Params.Get("code")))["access_token"];
            string longtoken = HttpUtility.ParseQueryString(HttpUtil.GetHtmlPage("https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&client_secret=" + APP_SECRET + "&grant_type=fb_exchange_token&fb_exchange_token=" + shorttoken))["access_token"];

            Facebook.FacebookClient fc = new Facebook.FacebookClient(longtoken);
            dynamic result = fc.Get("me");

            context.Response.Redirect("/");
            //Store Token here
        }
    }

My Utilities file is here:

public static class HttpUtil
{
    public static string GetHtmlPage(string strURL)
    {
        String strResult;
        WebResponse objResponse;
        WebRequest objRequest = HttpWebRequest.Create(strURL);
        objResponse = objRequest.GetResponse();
        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
        {
            strResult = sr.ReadToEnd();
            sr.Close();
        }
        return strResult;
    }
}
Jon Newman

See How to renew Facebook access token using its C# SDK. Just requesting "oauth/access_token" isn't enough, you have to specify parameters there too. The technique there worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!