3

我已经知道如何代表 facebook 用户使用图形 api 在墙上发布一些东西。但是现在我想以我的应用程序的名义发布一些东西。

这是我尝试这样做的方法:

protected void btn_submit_Click(object sender, EventArgs e)
{

    Dictionary<string, string> data = new Dictionary<string, string>();
    data.Add("message", "Testing");
    // i'll add more data later here (picture, link, ...)
    data.Add("access_token", FbGraphApi.getAppToken());
    FbGraphApi.postOnWall(ConfigSettings.getFbPageId(), data);

}

FbGraphApi.getAppToken()

// ...
private static string graphUrl = "https://graph.facebook.com";
//...

public static string getAppToken() {
    MyWebRequest req = new MyWebRequest(graphUrl + "/" + "oauth/access_token?type=client_cred&client_id=" + ConfigSettings.getAppID() + "&client_secret=" + ConfigSettings.getAppSecret(), "GET");
    return req.GetResponse().Split('=')[1];
}

FbGraphApi.postOnWall()

public static void postOnWall(string id, Dictionary<string,string> args)
    {
        call(id, "feed", args);
    }

FbGraphApi.call()

private static void call(string id, string method, Dictionary<string,string> args )
{
    string data = "";
    foreach (KeyValuePair<string, string> arg in args)
    {

        data += arg.Key + "=" + arg.Value + "&";

    }

    MyWebRequest req = new MyWebRequest(graphUrl +"/" + id + "/" + method, "POST", data.Substring(0, data.Length - 1));


    req.GetResponse();  // here i get: "The remote server returned an error: (403) Forbidden."
}

有谁知道我哪里出错了?我真的坚持这一点。

谢谢!

4

3 回答 3

3

您需要获取 Auth Token 才能让您的应用程序作为该应用程序发布。

Auth_Token 定义您发布的安全上下文。

您需要为当前用户请求以下 Graph API URL,以查找您的应用程序的访问令牌。

https://graph.facebook.com/me/accounts?access_token=XXXXXXXX

这应该会为您提供类似于以下内容的输出:

{
   "data": [
      {
         "name": "My App",
         "category": "Application",
         "id": "10258853",
     "access_token": "xxxxxxxxxxxxxxxx"
      }
   ]
}

在调用该 API 之前,请确保您拥有 manage_pages 权限,否则您将无法取回访问令牌。

拥有访问令牌后,您就可以像任何其他用户一样将其发布到墙上。请注意,URL 中使用的 ID 与应用程序的 ID 匹配。这将作为应用程序发布到应用程序的墙上。

https://graph.facebook.com/10258853/feed?access_token=XXXXXXX

在发布到墙上之前,请确保您也拥有 publish_stream 权限。

于 2011-04-16T14:58:41.187 回答
2

最近我使用了 FB api。
我已经用 javascript 完成了所有事情。
这是我曾经发布到用户墙上的内容。
我希望这可以帮助你。

  • 包含 FB 提供的 javascript 库并将您的应用程序 ID 添加到其中。

    <div id="fb-root"></div>
          <脚本>
    
          window.fbAsyncInit = function() {
            FB.init({appId: '你的应用 id', status: true, cookie: true,
                     xfbml: 真});
          };
          (功能() {
            var e = document.createElement('script');
            e.type = '文本/javascript';
            e.src = document.location.protocol +
              '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
          }());
    
           </脚本>
    

  • 对于登录,我使用了一个带有“fb_login”作为 id 的按钮,然后我使用了 jquery,如下所示:
    $("#fb_login").click(function(){
        FB.登录(功能(响应){
            如果(响应。会话)
            {
                如果(response.perms)
                {
                                   // alert("已登录并授予发帖权限");
                }
                别的
                {
                      // alert("已登录但未授予发帖权限");
                }
            }
            别的
            {
                            //alert("未登录");
            }
    }, {perms:'publish_stream'});
    

    请注意,您必须像上面那样添加{perms:'publish_stream'},这将使您获得发布到用户墙的权利。

  • 带有 id="stream_publish" 的按钮,然后是以下 jquery:

    $("#stream_publish").click(function(){
    
          FB.getLoginStatus(函数(响应){
    
              如果(响应。会话)
              {
                    发布帖子(response.session);
              }
    
          });
    });
    
    功能发布发布(会话)
    {
        变种发布 = {
          方法:'stream.publish',
          消息:'你的消息',
          图片 : '要显示的图像',
          link : '将成为帖子一部分的链接,可以指向您的应用页面或您的个人页面或任何其他页面',
          name: '帖子的名称或标题',
          标题:“帖子的标题”,
          description: '写 Facebook 应用很有趣!',
          操作:{名称:'开始学习',链接:'链接到应用程序'}
        };
    
        FB.api('/me/feed', 'POST', publish, function(response) {  
    
            document.getElementById('confirmMsg').innerHTML =
                   '一个帖子刚刚发布到你墙上的信息流中。';
        });
    };
    

  • 于 2011-04-16T19:20:11.123 回答
    1
    private class FbWebViewClient extends WebViewClient {
    
        boolean started=false;
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d("Facebook-WebView", "Redirect URL: " + url);
            if (url.startsWith(Facebook.REDIRECT_URI)) {
                Bundle values = Util.parseUrl(url);
    
                String error = values.getString("error");
                if (error == null) {
                    error = values.getString("error_type");
                }
    
                if (error == null) {
                    mListener.onComplete(values);
                } else if (error.equals("access_denied")
                        || error.equals("OAuthAccessDeniedException")) {
                    mListener.onCancel();
                } else {
                    mListener.onFacebookError(new FacebookError(error));
                }
    
                FbDialog.this.dismiss();
                return true;
            } else if (url.startsWith(Facebook.CANCEL_URI)) {
                mListener.onCancel();
                FbDialog.this.dismiss();
                return true;
            } else if (url.contains(DISPLAY_STRING)) {
                return false;
            }
            // launch non-dialog URLs in a full browser
            getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    
        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mListener.onError(new DialogError(description, errorCode,
                    failingUrl));
            FbDialog.this.dismiss();
        }
    
        public Map<String, String> getUrlParameters(String url)
                throws UnsupportedEncodingException {
            Map<String, String> params = new HashMap<String, String>();
            String[] urlParts = url.split("\\?");
            if (urlParts.length > 1) {
                String query = urlParts[1];
                for (String param : query.split("&")) {
                    String pair[] = param.split("=");
                    String key = URLDecoder.decode(pair[0], "UTF-8");
                    String value = "";
                    if (pair.length > 1) {
                        value = URLDecoder.decode(pair[1], "UTF-8");
                    }
    
                    params.put(key, value);
    
                }
            }
            return params;
        }
    
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("Facebook-WebView", "Webview loading URL: " + url);
    
            String newUrl="http://www.facebook.com/dialog/feed?_path=feed&app_id="; 
            if (url.contains("touch") && started==false) {
    
                started=true;
                ChildTabBibleLessonActivity.fbMaterial=ChildTabBibleLessonActivity.fbMaterial.replace(" ", "+");
                url=url+"&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg&description="+ChildTabBibleLessonActivity.fbMaterial;
            /*  Map<String,String> param;
                try {
                    param = getUrlParameters(url);
                    newUrl=newUrl+param.get("app_id")+"&redirect_uri="+"https://deep-rain-6015.herokuapp.com"+"&display=page&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg"+"&name=MiniBible&description=heregoesMyMessage";
    
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                */
                view.loadUrl(url);
                //super.onPageStarted(view, url, favicon);
            }
            else
            {
            super.onPageStarted(view, url, favicon);
            }
            mSpinner.show();
        }
    
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mSpinner.dismiss();
            /*
             * Once webview is fully loaded, set the mContent background to be
             * transparent and make visible the 'x' image.
             */
            mContent.setBackgroundColor(Color.TRANSPARENT);
            mWebView.setVisibility(View.VISIBLE);
            mCrossImage.setVisibility(View.VISIBLE);
        }
    }
    
    于 2011-11-22T16:23:52.447 回答