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

本文关键字:访问令牌 获取 C#SDK Facebook 使用 | 更新日期: 2023-09-27 18:00:09

嗨,我正在使用以下代码使用C#SDK 从facebook获取访问令牌

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.

如何解决这个问题??

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

您的项目类型是什么:WinFormsWPFASP。NET

如果使用WinFormsWPF,则必须通过请求OAuth登录对话框和return_type=tokenBrowser Control URL中获取access_token,然后从URL中提取有效的access_token

否则,如果您正在使用ASP。NET,您必须将用户重定向到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超时了?

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

var config = new Dictionary<string, object>();
//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()

为您提供访问令牌。