Skip to main content
 首页 » 编程设计

c#之作为页面发布到 Facebook 页面

2024年02月06日10虾米姐

经过一番搜索后,我能够以我自己的身份在 Facebook 页面上发帖。但我的目标是在我作为页面管理的页面上发布。我做了更多研究,并且能够获得我管理的页面的访问 token 。当我尝试在其上发布时,sdk 给了我

用户未授权应用程序执行此操作

这是我的代码供您引用:

        string app_id = "xxxxx"; 
        string app_secret = "yyyyyyy"; 
        string scope = "publish_actions,manage_pages"; 
 
        if (Request["code"] == null) 
        { 
            string url = string.Format( 
                "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", 
                app_id, Request.Url.AbsoluteUri, scope); 
            Response.Redirect(url, false); 
        } 
        else 
        { 
            Dictionary<string, string> tokens = new Dictionary<string, string>(); 
 
            string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}", 
                app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret); 
 
            HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest; 
 
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
            { 
                StreamReader reader = new StreamReader(response.GetResponseStream()); 
 
                string vals = reader.ReadToEnd(); 
 
                foreach (string token in vals.Split('&')) 
                { 
                    tokens.Add(token.Substring(0, token.IndexOf("=")), 
                        token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1)); 
                } 
            } 
 
            string access_token = tokens["access_token"]; 
 
            var client = new FacebookClient(access_token); 
 
            dynamic parameters = new ExpandoObject(); 
            parameters.message = "Check out this funny article"; 
            parameters.link = "http://www.natiska.com/article.html"; 
            parameters.picture = "http://www.natiska.com/dav.png"; 
            parameters.name = "Article Title"; 
            parameters.caption = "Caption for the link"; 
 
            //zzzzzzz is my fan page 
            string pageAccessToken = "";  
            JsonObject jsonResponse = client.Get("me/accounts") as JsonObject; 
            foreach (var account in (JsonArray)jsonResponse["data"]) 
            { 
                string accountName = (string)(((JsonObject)account)["name"]); 
 
                if (accountName == MY_PAGE_NAME) 
                { 
                    pageAccessToken = (string)(((JsonObject)account)["access_token"]); 
                    break; 
                } 
            } 
 
            client = new FacebookClient(pageAccessToken); 
            client.Post("/zzzzzzz/feed", parameters); 

请您参考如下方法:

您需要 publish_pages 权限才能作为页面发布。

https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish