使用Facebook C#SDK获取访问令牌

您好我正在使用以下代码从Facebook使用C#SDK获取访问令牌

var fb = new FacebookClient(); dynamic result = fb.Get("oauth/access_token", new { client_id = "clientId", client_secret = "clientSecret", redirect_uri = "redirectUri", code = "code" }); return result.access_token; 

上面的代码大部分时间都是完美的,但有时候会出现这个错误

 (OAuthException - #100) Invalid verification code format. 

如何解决这个问题?

你的项目类型是什么: WinFormsWPFASP.NET

如果您正在使用WinFormsWPF ,则必须通过请求OAuth登录对话框和return_type=token来获取访问Browser Control URL的access_token ,然后从URL中提取有效的access_token

否则,如果您正在使用ASP.NET处理Web应用程序,则必须将用户重定向到OAuth对话登录页面,然后Facebook将使用URL上的代码重定向您,您将从QueryString获取此代码并进行制作一个HTTPRequest到Facebook获取有效的access_token

你可以使用我的方法来做到这一点:

  public string GetAccessTokenFromCode(string AppID, string AppSecret, string RedirectURL, string Code) { WebClient wc = new WebClient(); string u2 = "https://graph.facebook.com/oauth/access_token?client_id=" + AppID + "&redirect_uri=" + RedirectURL + "&client_secret=" + AppSecret + "&code=" + Code + "&state=anytexthere"; string access = wc.DownloadString(u2); access = access.Substring(access.IndexOf("access_token") + 13); if (access.Contains("&")) { string accesstoken = access.Substring(0, access.IndexOf("&")); return accesstoken; } return access; } 

你可以从Page_Load调用它:

 if (Request.QueryString["code"] != null) { code = Request.QueryString["code"].ToString(); string AT = GetAccessTokenFromCode(AppID, AppSecret, RedirectUrl, Code); } 

您应该具有与询问code时相同的redirect_uri
此外,您在Facebook上的“Facebook登录网站”部分中配置的网站url末尾必须有一个斜杠“/”。
这是一个完整的教程: 使用C#SDK

这个页面让我想知道你的代码是否应该更像这样:

  dynamic result = fbClient.Get("oauth/access_token", new { client_id = fbClient.AppId, client_secret = fbClient.AppSecret, grant_type = "fb_exchange_token", fb_exchange_token = accessToken }); 

也许你的accessToken超时或什么?

从http://www.nuget.org/packages/Facebook.CSharp.SDK/下载sdk之后

 var config = new Dictionary(); //your application id and secret from https://developers.facebook.com/apps config.Add("appId", "3955......."); config.Add("secret", "4c1d..............."); config.Add("fileUpload", true); //optional FacebookClient client = new FacebookClient(config); ulong facebookId = client.getUser(); //retrieve user id. if user is not added the app this value is 0 client.getAccessToken() 

为您提供访问令牌。