我将Facebook SDK更新到6.0.10,以及一些以前工作的代码不再起作用了。我曾经在用户的墙上发布使用下面的方法。
FacebookClient用于获取AppId
和AppSecret
的类,我没有为我的应用程序提供任何访问令牌。
string uId = "SomeUid";
FacebookClient fb = new FacebookClient(AppId,AppSecret );
string userFeedPath = String.Format("/{0}/feed", uId);
dynamic parameters = new ExpandoObject();
parameters.link = "Test@test";
parameters.message = "test";
try
{
dynamic result = fb.Post(userFeedPath, parameters);
}
catch(Exception ex)
{
}
现在即使我试试这个,
FacebookClient fb = new FacebookClient();
fb.AppId = "1234...";
fb.AppSecret = "76e69e0c334995cecc8c....";
我收到了这个错误:
(OAuthException - #200)(#200)此API调用需要有效的app_id。
如何解决此问题?
答案 0 :(得分:31)
您需要通过提出请求来获取应用访问令牌。
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new {
client_id = "app_id",
client_secret = "app_secret",
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
答案 1 :(得分:4)
代码 - >服务器端流中的用户访问令牌交换 - 而不是(版本5):
FacebookOAuthClient oAuthClient = new FacebookOAuthClient();
oAuthClient.AppId = "...";
oAuthClient.AppSecret = "...";
oAuthClient.RedirectUri = new Uri("https://.../....aspx");
dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
return tokenResult.access_token;
现在使用(版本6):
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("client_id", "...");
parameters.Add("redirect_uri", "https://.../....aspx");
parameters.Add("client_secret", "...");
parameters.Add("code", code);
result = fb.Get("/oauth/access_token", parameters);
string accessToken = result["access_token"];
(见:http://developers.facebook.com/docs/authentication/server-side/)
答案 2 :(得分:3)
我昨天刚刚开始使用这个Facebook库,并认为缺乏能够在不传递JavaScript的情况下向我提供访问令牌是一个主要缺点。这是一个可以获取访问令牌的帮助器。我希望这可以帮助那些和我一样遭受同样挫折的人。我认为这应该都可以。在我发现Facebook NuGet之前,我在网站上有过类似的工作,现在大约工作了一年。
如果有更好的方法,请告诉我。
public class FacebookHelper
{
private string _appId;
private string _appSecret;
private string _accessToken;
public string AccessToken
{
get
{
if (_accessToken == null)
GetAccessToken();
return _accessToken;
}
set { _accessToken = value; }
}
public FacebookHelper(string appId, string appSecret)
{
this._appId = appId;
this._appSecret = appSecret;
}
public string GetAccessToken()
{
var facebookCookie = HttpContext.Current.Request.Cookies["fbsr_" + _appId];
if (facebookCookie != null && facebookCookie.Value != null)
{
string jsoncode = System.Text.ASCIIEncoding.ASCII.GetString(FromBase64ForUrlString(facebookCookie.Value.Split(new char[] { '.' })[1]));
var tokenParams = HttpUtility.ParseQueryString(GetAccessToken((string)JObject.Parse(jsoncode)["code"]));
_accessToken = tokenParams["access_token"];
return _accessToken;
}
else
return null;
// return DBLoginCall(username, passwordHash, cookieToken, cookieTokenExpires, args.LoginType == LoginType.Logout, null);
}
private string GetAccessToken(string code)
{
//Notice the empty redirect_uri! And the replace on the code we get from the cookie.
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", _appId, "", _appSecret, code.Replace("\"", ""));
System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response = null;
try
{
using (response = request.GetResponse() as System.Net.HttpWebResponse)
{
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
return retVal;
}
}
catch
{
return null;
}
}
private byte[] FromBase64ForUrlString(string base64ForUrlInput)
{
int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
result.Append(String.Empty.PadRight(padChars, '='));
result.Replace('-', '+');
result.Replace('_', '/');
return Convert.FromBase64String(result.ToString());
}
}
答案 3 :(得分:1)
我尝试了上面的一些示例,但发现动态不能使用xamarin studio进行编译。这就是我所做的。
public class AccessTokenModel
{
public string Access_Token { get; set;}
}
var fb = new FacebookClient();
var result = fb.Get ("oauth/access_token", new {
client_id = App.FaceBookId,
client_secret = App.FacebookAppSecret,
grant_type = "client_credentials"
});
var accessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessTokenModel> (result.ToString ());
或
FBSession.ActiveSession.AccessTokenData.AccessToken;
答案 4 :(得分:1)
还有另一种方法可以调用Graph API,不需要使用生成的应用访问令牌。您可以在拨打电话时将app id和app secret作为access_token参数传递:
https://graph.facebook.com/endpoint?key=value&access_token=app_id|app_secret
使用生成的访问令牌与此方法的选择取决于 你隐藏你的应用秘密的地方。
来自:https://developers.facebook.com/docs/facebook-login/access-tokens
var client = new FacebookClient($"{appId}|{appSecret}");
答案 5 :(得分:0)
野兔是一种真正的工作方法:
protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
{
// Note: Facebook doesn't like us to url-encode the redirect_uri value
var builder = new UriBuilder("https://graph.facebook.com/oauth/access_token");
builder.AppendQueryArgument("client_id", this.appId);
builder.AppendQueryArgument("redirect_uri", NormalizeHexEncoding(returnUrl.GetLeftPart(UriPartial.Path)));
builder.AppendQueryArgument("client_secret", this.appSecret);
builder.AppendQueryArgument("code", authorizationCode);
using (WebClient client = new WebClient())
{
//Get Accsess Token
string data = client.DownloadString(builder.Uri);
if (string.IsNullOrEmpty(data))
{
return null;
}
var parsedQueryString = HttpUtility.ParseQueryString(data);
return parsedQueryString["access_token"];
}
}
private static string NormalizeHexEncoding(string url)
{
var chars = url.ToCharArray();
for (int i = 0; i < chars.Length - 2; i++)
{
if (chars[i] == '%')
{
chars[i + 1] = char.ToUpperInvariant(chars[i + 1]);
chars[i + 2] = char.ToUpperInvariant(chars[i + 2]);
i += 2;
}
}
return new string(chars);
}