【发布时间】:2020-03-21 14:21:27
【问题描述】:
我有一个 c# asp.net web 应用程序。
我正在通过他们的 javascript sdk 使用 facebook 登录,它会进行登录。
现在我有一个简单的所见即所得编辑器,其中添加的任何内容都应该发布在该登录用户的 Facebook 页面上。
以下是代码:
string FacebookApiId = "952214336368241";
string FacebookApiSecret = "fb2213d66523c8cb0bc99306f46ee457";
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
private string GetAccessToken(string apiId, string apiSecret)
{
string AuthenticationUrlFormat = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret);
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd(); // this gives me {"access_token":"952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6Bt","token_type":"bearer"}
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"]; // This line throws error
}
//if (accessToken.Trim().Length == 0)
//throw new Exception("There is no Access Token");
return "952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6B"; // hard-coded to get it working;
}
private void PostMessage(string accessToken, string v)
{
try
{
FacebookClient facebookClient = new FacebookClient(accessToken);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
messagePost.message = v;
var result = facebookClient.Post("/[user id]/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle something
}
catch (Exception ex)
{
//handle something else
}
}
这会引发错误:
{"(OAuthException - #803) (#803) 您请求的某些别名不存在:[user id]"}
我什至写了我的 facebook emailid 而不是 [user id] 但它仍然不起作用并给我错误:
消息:“(OAuthException - #2500) 必须使用活动访问令牌来查询有关当前用户的信息。”
谁能告诉我如何消除这个错误。
【问题讨论】:
-
永远不要暴露您的应用程序秘密...尽快使其无效/刷新。它被称为秘密是有原因的。此外,您似乎有 2 个不同的应用程序机密。确保你完全理解发生了什么,不要只是复制/粘贴(非常旧的)代码并假设它会以某种方式工作。
标签: c# facebook-graph-api oauth