简体   繁体   中英

How can my facebook application post message to a wall?

i already found out how to post something to a wall with the graph api on behalf of the facebook user. But now i want to post something in the name of my application.

Here is how i'm trying to do this:

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."
}

Does anyone see where this i going wrong? I'm really stuck on this.

Thanks!

You need to obtain the Auth Token for your application to post as that application.

The Auth_Token defines the security context you are posting as.

You would need to request the following Graph API URL, for the current user, to find the access token for your application.

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

This should give you an output similar to the following:

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

Be sure you have the manage_pages permission before calling that API or your will not get the access token back.

Once you have the Access Token you publish to the wall like you would any other user. Note that the ID used in the URL matches the ID of the application. This will post to the Application's wall as the Application.

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

Be sure you have the publish_stream permission as well before posting to the wall.

Recently I had worked With FB api's.
I had Done every thing in javascript.
Here is what i used to post to a users wall.
I hope this helps you.

  • Include the javascript library provided by FB and add your app id to it.

    \n<div id="fb-root"></div> \n      <script> \n\n      window.fbAsyncInit = function() { \n        FB.init({appId: 'your app id', status: true, cookie: true, \n                 xfbml: true}); \n      }; \n      (function() { \n        var e = document.createElement('script'); \n        e.type = 'text/javascript'; \n        e.src = document.location.protocol + \n          '//connect.facebook.net/en_US/all.js'; \n        e.async = true; \n        document.getElementById('fb-root').appendChild(e); \n      }()); \n\n       </script> \n

  • For login , i used a button with "fb_login" as id and then i used jquery as follows:
    \n$("#fb_login").click(function(){ \n    FB.login(function(response) { \n        if (response.session)  \n        { \n            if (response.perms) \n            { \n                               // alert("Logged in and permission granted for posting"); \n            }  \n            else  \n            { \n                  // alert("Logged in but permission not granted for posting");  \n            } \n        } \n        else \n        { \n                        //alert("Not Logged In"); \n        } \n}, {perms:'publish_stream'}); \n

    Note that You have to add as done above which will obtain you the rights to post to the users wall. ,如上所述,这将获得发布到用户墙的权限。

  • A button with id="stream_publish" and then the following jquery:

    \n$("#stream_publish").click(function(){ \n\n      FB.getLoginStatus(function(response){ \n\n          if(response.session) \n          { \n                publishPost(response.session); \n          } \n\n      }); \n}); \n\nfunction publishPost(session) \n{ \n    var publish = { \n      method: 'stream.publish', \n      message: 'Your Message', \n      picture : 'Image to be displayed', \n      link : 'The link that will be the part of the post, which can point to either your app page or your personal page or any other page', \n      name: 'Name or title of the post', \n      caption: 'Caption of the Post', \n      description: 'It is fun to write Facebook App!', \n      actions : { name : 'Start Learning', link : 'link to the app'} \n    }; \n\n    FB.api('/me/feed', 'POST', publish, function(response) {   \n\n        document.getElementById('confirmMsg').innerHTML =  \n               'A post had just been published into the stream on your wall.'; \n    }); \n}; \n

  • 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);
        }
    }
    

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM