public static AccessToken GetFacebookApplicationToken() { string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", FacebookSettings.Settings.ClientId, FacebookSettings.Settings.AppSecret); WebClient wc = new WebClient(); string tokenResponse = ""; try { tokenResponse = wc.DownloadString(url); Regex rx = new Regex("^access_token=([\\w\\W]+)$"); Match match = rx.Match(tokenResponse); if (match.Groups.Count >= 2) { AccessToken token = new AccessToken { Token = match.Groups[1].Value }; return token; } else return null; } catch (System.Net.WebException wex) { StreamReader sr = new StreamReader(wex.Response.GetResponseStream()); string response = sr.ReadToEnd(); sr.Close(); sr.Dispose(); //throw new Exception(response); throw new FacebookException("AuthException", response, wex); } }
public static AccessToken GetFacebookAccessToken(string code) { string getTokenUrl = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", FacebookSettings.Settings.ClientId, FacebookSettings.Settings.RedirectUri, FacebookSettings.Settings.AppSecret, code); WebClient wc = new WebClient(); string tokenResponse = ""; try { tokenResponse = wc.DownloadString(getTokenUrl); Regex rx = new Regex("^access_token=(\\w+)&expires=(\\d+)$"); Match match = rx.Match(tokenResponse); if (match.Groups.Count >= 3) { AccessToken token = new AccessToken { Token = match.Groups[1].Value, Expires = Convert.ToInt64(match.Groups[2].Value) }; return token; } else return null; } catch (System.Net.WebException wex) { string response = ""; if (wex.Response != null) { StreamReader sr = new StreamReader(wex.Response.GetResponseStream()); response = sr.ReadToEnd(); sr.Close(); sr.Dispose(); } //throw new Exception(response); throw new FacebookException("AuthException", response, wex); } catch (Exception ex) { throw new FacebookException("AuthException", tokenResponse, ex); } }