发送帖子到Facebook页面

时间:2019-11-26 08:05:26

标签: c# facebook-graph-api oauth

我有一个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)您请求的某些别名不存在:[用户ID]”}

我什至写了我的facebook emailid而不是[user id],但是它仍然无法正常工作,并给我错误:

  

消息:“(OAuthException-#2500)必须使用活动访问令牌来查询有关当前用户的信息。”

任何人都可以建议我如何消除此错误。

1 个答案:

答案 0 :(得分:1)

  • 该代码非常古老,offline_accesspublish_stream已经很多年了。
  • 您必须使用具有publish_pages权限的页面令牌,才能通过API发布到您的页面。
  • 您可以使用“我/提要”或“页面ID /提要”,但不能使用电子邮件。

有关令牌以及如何生成令牌的信息:

在编程之前,请尝试在API资源管理器中进行操作:https://developers.facebook.com/tools/explorer/