2012-03-28 89 views
7

我將Facebook SDK更新爲6.0.10,並且一些曾經工作的代碼不再工作。我曾經在用戶的牆上張貼使用下面的方法。如何使用C#SDK獲取訪問令牌

FacebookClient類用於採取AppIdAppSecret,我沒有給它提供我的應用程序的任何訪問令牌。

string uId = "SomeUid"; 
FacebookClient fb = new FacebookClient(AppId,AppSecret); 

string userFeedPath = String.Format("/{0}/feed", uId); 

dynamic parameters = new ExpandoObject(); 
parameters.link = "[email protected]"; 
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) This API call requires a valid app_id.

我該如何解決這個問題?

+0

你能確定你的憑證仍然有效的更新的SDK?您可能需要獲取新的憑據(例如,由於正在使用的OAuth類型的升級)。 – JTeagle 2012-03-28 11:27:47

+0

對於將來面臨問題的人,下面是一個完整的教程:[使用Facebook C#SDK](http://www.thepcwizard.in/2013/02/working-with-facebook-c--sharp-sdk。html) – ThePCWizard 2013-02-25 06:46:52

回答

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; 
+0

這是否意味着版本6.0有突變?我現在剛開始使用V 6.0,但是我正在學習一個教程,我無法使它工作......類型不在那裏曾經存在過(看過Codeplex和舊版本的文件)。沮喪不用說... – Robert 2012-03-30 02:45:45

+0

嗨Prabir。我嘗試了這種方法,沒有任何運氣。首先,我認爲它應該是result.access_token才能獲得價值。但除此之外,它似乎會得到應用程序的訪問令牌,而不是該應用程序的特定用戶。這聽起來像是獲得用戶訪問令牌的唯一方式是通過JavaScript SDK?那是對的嗎?或者C#SDK提供了一些我缺少的其他方式?謝謝! – 2012-04-06 21:22:06

+0

謝謝。我更新爲result.access_token。它用於應用程序訪問令牌。對於用戶訪問令牌,您需要使用服務器端流程或使用js sdk。 – prabir 2012-04-07 06:08:04

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/

+0

Full sample:http://stackoverflow.com/questions/8162613/exception-in-getting-facebook-api-user- access-token-and-c-sharp – Mateusz 2012-04-27 21:11:36

+0

嚴格遵循您的代碼,我得到: (OAuthException - #101)驗證應用程序時出錯。由於系統錯誤,無法獲取應用程序信息。 – 2013-11-24 07:49:23

+0

我認爲要點是需要回調。這意味着您必須提供一個重定向url,它將接受「code」參數並將其應用於用戶。 – 2014-04-07 20:52:07

3

我昨天剛剛開始使用此Facebook庫,並認爲缺乏賦予m訪問令牌沒有通過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()); 
    } 
} 
+0

這看起來很有希望,你能告訴我更多一點嗎?我的cookies列表中沒有看到fbsr_ [appId] cookie – 2014-04-07 21:09:23

+0

什麼是JObject? – Kiquenet 2014-11-15 15:35:02

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; 
+0

我使用WinForms和單元測試項目。什麼是FBSession? – Kiquenet 2014-11-15 16:08:35

1

There is another method to make calls to the Graph API that doesn't require using a generated app access token. You can just pass your app id and app secret as the access_token parameter when you make a call:

https://graph.facebook.com/endpoint?key=value&access_token=app_id|app_secret

The choice to use a generated access token vs. this method depends on where you hide your app secret.

來自:https://developers.facebook.com/docs/facebook-login/access-tokens

var client = new FacebookClient($"{appId}|{appSecret}"); 
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); 
     } 
相關問題