I have been using facebook api to share post on facebook page as facebook app. I have created facebook app.
The post also gets shared but the problem is, it is not being posted as a facebook app. Instead it asks user for login and then it shares post as a user. Any help regarding how could I share a post as a Facebook App would be appreciated as I have been trying this for a long time.
Thanx in advance friends.
The code that I have been using is as follows.
using Facebook;
protected void CheckAuthorization()
{
string authorizationCode = Request.QueryString["code"];
string access_token = Facebook_GetAccessToken(authorizationCode);
FacebookShare(access_token);
}
private string Facebook_GetAccessToken(string pAuthorizationCode)
{
string urlGetAccessToken = "https://graph.facebook.com/oauth/access_token";
urlGetAccessToken += "?client_id=my app id";
urlGetAccessToken += "&client_secret=app secret";
urlGetAccessToken += "&redirect_uri=" + Facebook_GetRedirectUri();
urlGetAccessToken += "&code=" + pAuthorizationCode;
string responseData = RequestResponse(urlGetAccessToken);
if (responseData == "")
{
return "";
}
NameValueCollection qs = HttpUtility.ParseQueryString(responseData);
string access_token = qs["access_token"] == null ? "" : qs["access_token"];
return access_token;
}
protected void FacebookShare(string token)
{
if (token != null)
{
Int64 transactionid = Convert.ToInt64(Cache["transactionid"]);
string app_id = "my app id";
string app_secret = "app secret";
string scope = "offline_access,read_stream,publish_actions,publish_stream,manage_pages,status_update";
dynamic parameters = new ExpandoObject();
parameters.link = "my website link";
parameters.name = "my project name";
parameters.picture= "my website logo";
var client = new FacebookClient(token);
client.Post("/1374775846180409/feed", parameters); // this is my facebook page id where I want to share post.
Response.Cookies["transaction"].Expires = DateTime.Now;
}
else
{
}
}
Regarding above code, I am getting Facebook Authorization code successfully.
You can only ask your user who has logged into your app to post on facebook, apps as such are not allowed to post.
You will need a page access token to post as the page, which have permissions to modify the data belonging to a Facebook Page. To obtain a page access token you need to start by obtaining a user access token, for which your user has to be logged into your app and asking for the manage_pages permission scope. Next, you can GET /me/accounts, which will return a page access token for each page that you manage.
This can not be accomplished using offline access or without logging in.
Related
I have created a facebook page and a facebook application for my website and now I need to post messages onto the facebook page with help of facebook SDK .NET.
This is what I got so far :
public static bool UploadPost(string message)
{
dynamic result;
//https://developers.facebook.com/tools/explorer/
//https://developers.facebook.com/tools/access_token/
FacebookClient client = new FacebookClient("secret access token");
result = client.Get("oauth/access_token", new
{
client_id = "[Client ID number]",
client_secret = "[Client sercret",
grant_type = "client_credentials",
});
result = client.Post("[facebook app Id]/feed", new { message = "Test Message from app" });
//result.id;
result = client.Get("[facebook app Id]");
return false;
}
When running this I get : Additional information: (OAuthException - #200) (#200) The user hasn't authorized the application to perform this action on client.Post. If I remove the client.Post row every thing works good, the correct data is fetched.
I have tried follow some helps on facebook SDK .NET website but it is still not working.
The main problem now is that I get permission exception. I was hoping that my facebook app hade enouth permissions to publish post from my website to the facebook page.
Here is a step wise tutorial to register your application with facebook and get an app Id for your application.
Then for permissions ::
private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream";
This is a string of permissions. Pass it on further for getting correct permissions to post messages on page. Post using your standard code for posting no FB pages.
Cheers. Hope it helps.
Are you trying to post to [facebook app id]?
I would recomend to post to "me/feed" and test if that works.
Also, to post to Facebook you have to have the publish_stream permission
private async Task Authenticate()
{
string message = String.Empty;
try
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream,publish_actions");
App.AccessToken = session.AccessToken;
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/LandingPage.xaml", UriKind.Relative)));
}
catch (InvalidOperationException e)
{
message = "Login failed! Exception details: " + e.Message;
MessageBox.Show(message);
}
}
Should work :)
The following should work.
var fb = new FacebookClient("access_token");
fb.PostCompleted += (o, e) => {
if(e.Error == null) {
var result = (IDictionary<string, object>)e.GetResultData();
var newPostId = (string)result.id;
}
};
var parameters = new Dictionary<string, object>();
parameters["message"] = "My first wall post using Facebook SDK for .NET";
fb.PostAsync("me/feed", parameters);
This was taken directly from the documentation.
By creating a extended page token and use it to make the post everything works just fine. See this : How to get Page Access Token by code?
Im surprised that this simple task was so hard to get running and that there was vary little help to get.
I have a question regarding using facebook graph API (OAuth) to upload photo.
I have created one company page under my account.
When I use my account to upload photo to my company page, my user name appears as a user who uploaded the page.
Is there anyway I can upload page so that company name appears?
Below is the code that I currently implemented.
string access_token = FacebookSystem.RetrieveToken(UserEmail, AppID);
string query = string.Empty;
if (string.IsNullOrEmpty(PageID) || PageID.Equals("default", StringComparison.InvariantCultureIgnoreCase))
{
query = "me/photos";
}
else
{
query = string.Format("{0}/photos", PageID);
}
var fb = new FacebookClient(access_token);
try
{
dynamic parameters = new ExpandoObject();
foreach (string i in args.FileList)
{
parameters.message = args.Comment;
parameters.source = new FacebookMediaObject
{
ContentType = "image",
FileName = Path.GetFileName(i)
}.SetValue(File.ReadAllBytes(i));
fb.Post(query, parameters);
}
}
in order to use Graph API on behalf of a Page, you need to get Page access token - see here for more details: https://developers.facebook.com/docs/facebook-login/access-tokens/#pagetokens
Authenticate the user and request the manage_pages permission
Get the list of pages the user manages from (1): https://graph.facebook.com/me/accounts?access_token=USER_ACCESS_TOKEN
Parse the list and get the token - and use it to post to the feed.
you will do (1) in graph API explorer - and you will get user token. Then insert that token into URL in (2) - and you will see all your pages and corresponding token. Take the one you need and use it in your C# code to upload images.
I am trying to look for an example of how to simply post a tweet on my Twitter account using C# and DotNetOpenAuth. I want to do it from a WinForms application. The examples I found seem to be using ASP.NET and WebForms. Specifically, i'm getting hung up on the "verifier code". Here is the code I have so far:
private McMurryTokenManager TokenManager
{
get
{
McMurryTokenManager tokenManager = null;
string consumerKey = ConsumerKey;
string consumerSecret = ConsumerSecret;
if (!string.IsNullOrEmpty(consumerKey))
{
tokenManager = new McMurryTokenManager
{ ConsumerKey = consumerKey, ConsumerSecret = consumerSecret };
}
return tokenManager;
}
}
public Form1()
{
InitializeComponent();
var twitter = new DesktopConsumer(TwitterConsumer.ServiceDescription, TokenManager);
string requestToken;
twitter.RequestUserAuthorization(null, null, out requestToken);
var accessTokenResponse = twitter.ProcessUserAuthorization(requestToken, null);
}
I'm getting an error saying the verifier code can't be null.
Here's what you need to do:
The RequestUserAuthorization method returns a URL to an authorization page.
You should redirect the user to that page, typically Process.Start(url), where the user will authorize your application.
Twitter the redirects the user to a page with a multi-digit number, which is the verifier.
After you've sent the user to the authorization page, your application should wait with a dialog or prompt so that the user can enter the verifier and submit it to your application.
Once you have the verifier, pass it as the 2nd argument to ProcessUserAuthorization.
Here's a blog post that say's something similar and has a code example:
http://whelkaholism.blogspot.com/2010/08/c-doing-stuff-with-google-using-oauth.html
I've created Facebook page.
I have no application secret and no access token.
I want to post to this page from my .NET desktop application.
How can I do it? Can anyone help please, where can I get access token for this?
Should I create a new Facebook Application? If yes, how can I grant permissions to this application to post on page's wall?
UPD1:
I have no website.
I need to post company's news from .NET desktop application to company's Facebook page.
All I have is Login/Password for Facebook Page Account.
UPD2:
I've created Facebook Application. With AppID/SecretKey. I can get access token. But...
How can I grant permissions to post to page's wall?
(OAuthException) (#200) The user hasn't authorized the application to perform this action
I have created a video tutorial showing how to do this at this location:
http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet
You will notice that, in my example, I am asking for both "publish_stream" and "manage_pages". This let's you also post on pages of which that users is an admin. Here is the full code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace FBO
{
public partial class facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "374961455917802";
string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
string scope = "publish_stream,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
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 = 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('&'))
{
//meh.aspx?token1=steve&token2=jake&...
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);
client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
}
}
}
}
You need to ask the user for the publish_stream permission. In order to do this you need to add publish_stream to the scope in the oAuth request you send to Facebook. The easiest way to do all of this is to use the facebooksdk for .net which you can grab from codeplex. There are some examples there of how to do this with a desktop app.
Once you ask for that permission and the user grants it you will receive an access token which you can use to post to your page's wall. If you need to store this permission you can store the access token although you might need to ask for offline_access permission in your scope in order to have an access token that doesn't expire.
You can use
https://www.nuget.org/packages/Microsoft.Owin.Security.Facebook/ to obtain users login and permission and
https://www.nuget.org/packages/Facebook.Client/
to post to feeds.
Below example is for ASP.NET MVC 5:
public void ConfigureAuth(IAppBuilder app)
{
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Facebook
var facebookOptions = new FacebookAuthenticationOptions
{
AppId = "{get_it_from_dev_console}",
AppSecret = "{get_it_from_dev_console}",
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location",
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken)); // user acces token needed for posting on the wall
return Task.FromResult(true);
}
}
};
facebookOptions.Scope.Add("email");
facebookOptions.Scope.Add("publish_actions"); // permission needed for posting on the wall
facebookOptions.Scope.Add("publish_pages"); // permission needed for posting on the page
app.UseFacebookAuthentication(facebookOptions);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
}
On the callback you get user access token:
public ActionResult callback()
{
// Here we skip all the error handling and null checking
var auth = HttpContext.GetOwinContext().Authentication;
var loginInfo = auth.GetExternalLoginInfo();
var identityInfo = auth.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
var email = loginInfo.Email // klaatuveratanecto#gmail.com
var name = loginInfo.ExternalIdentity.Name // Klaatu Verata Necto
var provider = loginInfo.Login.LoginProvider // Facebook | Google
var fb_access_token = loginInfo.identityInfo.FindFirstValue("FacebookAccessToken");
// Save this token to database, for the purpose of this example we will save it to Session.
Session['fb_access_token'] = fb_access_token;
// ...
}
Which then you can use to post to user's feed or page
public class postcontroller : basecontroller
{
public ActionResult wall()
{
var client = new FacebookClient( Session['fb_access_token'] as string);
var args = new Dictionary<string, object>();
args["message"] = "Klaatu Verata N......(caugh, caugh)";
try
{
client.Post("/me/feed", args); // post to users wall (feed)
client.Post("/{page-id}/feed", args); // post to page feed
}
catch (Exception ex)
{
// Log if anything goes wrong
}
}
}
You need to grant the permission "publish_stream".
Possibly the easiest way to do this is via Facebook PowerShell Module, http://facebookpsmodule.codeplex.com. This allows the same sort of operations as FacebookSDK, but via an IT-Admin scripting interface rather than a developer-oriented interface.
AFAIK there is still a limitation of Facebook Graph API that you will not be able to post references to other pages (e.g. #Microsoft) using the Facebook Graph API. This will apply to FacebookSDK, FacebookPSModule, and anything else built over Facebook Graph API.
You will get information on how to create a facebook app or link your website to facebook on https://developers.facebook.com/?ref=pf.
You will be able to download facebook sdk at http://facebooksdk.codeplex.com/. There are some good example given in the document section of the site.
public void PostImageOnPage()
{
string filename=string.Empty;
if(ModelState.IsValid)
{
//-------- save image in image/
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
// fetching image
filename = Path.GetFileName(file.FileName);
filename = DateTime.Now.ToString("yyyyMMdd") + "_" + filename;
file.SaveAs(Server.MapPath("~/images/Advertisement/") + filename);
}
}
string Picture_Path = Server.MapPath("~/Images/" + "image3.jpg");
string message = "my message";
try
{
string PageAccessToken = "EAACEdEose0cBAAoWM3X";
// ————————create the FacebookClient object
FacebookClient facebookClient = new FacebookClient(PageAccessToken);
// ————————set the parameters
dynamic parameters = new ExpandoObject();
parameters.message = message;
parameters.Subject = "";
parameters.source = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = Path.GetFileName(Picture_Path)
}.SetValue(System.IO.File.ReadAllBytes(Picture_Path));
// facebookClient.Post("/" + PageID + "/photos", parameters);// working for notification on user page
facebookClient.Post("me/photos", parameters);// woring using bingoapp access token not page in(image album) Post the image/picture to User wall
}
catch (Exception ex)
{
}
}
I am having a problem retrieving the user's access token after he/she has authorized my Facebook application to access their information and post for them, etc... Facebook returns a code query string to my website, so I can receive the access token for the user. I use the following code to get the access code.
string AppKey = "[REMOVED]";
string AppSecret = "[REMOVED]";
var oAuth = new Facebook.FacebookOAuthClient();
oAuth.AppId = AppKey;
oAuth.AppSecret = AppSecret;
oAuth.RedirectUri = new Uri("http://www.mywebsite.com");
Label3.Text = Request.QueryString["code"];
try
{
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
string accessTokenString = accessToken.ToString();
HttpCookie aCookie = new HttpCookie("MyWebsite_FBAccessToken");
aCookie.Value = accessTokenString;
Response.Cookies.Add(aCookie);
Response.Redirect("~/Process/ProcessToken.aspx");
}
catch (Facebook.FacebookOAuthException error)
{
Label2.Text = error.Message;
}
My code gets held up here:
var accessToken = oAuth.ExchangeCodeForAccessToken(Request.QueryString["code"]);
And I receive the following error.
(OAuthException) Error validating verification code.
Does this seem like there is a problem with my code, or does it look like there may be a setting problem with my Facebook application? I know my App ID and Secret are correct.