Send notification through facebook application using rest fb api - facebook

I am trying to send notification to facebook users via facebook application using restfb api. When tried to publish such notification, it shows an exception
"com.restfb.exception.FacebookGraphException: Received Facebook error response of type
GraphMethodException: Unsupported post request".
Below is my code:
FacebookType = facebookAppAccessToken.publish("user_id/notification?access_token=app_access_token"),
FacebookType.class, Parameter.with("template","send_notification"),
Parameter.with("href,"sample_link"));
Please help me resolving this. Thanks in advance

public void sendNotification(String externalUserId, String message) {
AccessToken appAccessToken = new DefaultFacebookClient()
.obtainAppAccessToken(APP_KEY, APP_SECRET);
FacebookClient facebookClient = new DefaultFacebookClient(
appAccessToken.getAccessToken());
try {
facebookClient.publish(externalUserId
+ "/notifications", FacebookType.class,
Parameter.with("template", message));
} catch (FacebookOAuthException e) {
if (e.getErrorCode() == 200) {
//Not an app user
} else if (e.getErrorCode() == 100) {
//Message cannot be longer than 180 characters
}
}
}
Handle error codes appropriately. And you can add href and ref as per your requirement.
Here are Details of parameters.

Related

Weird error message for denied fb app item submission

This is not for Facebook api authentication but for item permission management for the app.
I'm currently in the process of resubmitting my application for item approval. One of the items I previously submitted and was rejected was the read_friendlists item. Here's the weird part..
This is the error message that I got from the submission:
it looks like you haven't made any API requests to access content with the read_friendlists permission in the last 30 days
I don't understand what the message means. Im in the process of getting this permission.
You might have to explicitly request those Fields in the request parameter when asking Friend's data.
for example
private void makeMyFriendsRequest(final Session session) {
Request request = Request.newMyFriendsRequest(session, new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
for (GraphUser user : users) {
System.out.println(user.getFirstName() + " " + user.getLastName());
System.out.println(users.get(i).getId());
GraphLocation loc = users.get(i).getLocation();
System.out.println(loc != null ? loc.getCity() : "loc not available");
}
}
}
});
// here add fields explicitly
Bundle bundle = request.getParameters();
bundle.putString("fields", "id,first_name,last_name,birthday,location");
request.executeAsync();
I hope this will help.

How can i post the feed to facebook page as admin using c# sdk?

I want to update the facebookpage using c# sdk. I have partially successful with this, the problem is whenever I post messages to the page, post is visible only for admin(i am the admin of the page)is logged In. I want the post or feed to be visible to every one who visit the page.
(even admin is logged out post's are not visible to admin also)
The following code i am trying to achieve
public ActionResult FacebookPagePost()
{
string app_id = "xxxx";
string app_secret = "xxx";
string scope = "publish_stream,manage_pages";
string page_Id = "xxX";
if (Request["code"] == null)
{
return Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
try
{
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('&'))
{
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 fbAccounts = client.Get("/me/accounts");
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://pic.com/pic.png";
messagePost.link = "http://www.examplearticle.com";
messagePost.name = "name goes here";
messagePost.description = "description goes here";
//Loop over the accounts looking for the ID that matches your destination ID (Fan Page ID)
foreach (dynamic account in fbAccounts.data) {
if (account.id == page_Id)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
messagePost.access_token = account.access_token;
break;
}
}
client.Post("/" + page_Id + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
}
catch (Exception e)
{
}
}
}
1) Create a Facebook App at: developers.facebook.com and get yourself an APPID and APPSECRET. (there are a lot of tutorials online for doing this so I will skip repeating it)
2) Go to: http://developers.facebook.com/tools/explorer and choose your app from the dropdown and click "generate access token".
3) After that do the following steps here:
https://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token to get yourself a permanent page token.
(I can not stress this enough, follow the steps carefully and thoroughly)*
*I have tool I built that does this for me, all I enter is the APPID, APPSECRET and ACCESSTOKEN which the tool then generates a permanent page token for me. Anyone is welcomed to use it and help make it better,
https://github.com/devfunkd/facebookpagetokengenerator
=========================================================================
Ok at this point you should have your APPID, APPSECRET and a PERMANENT PAGE TOKEN.
=========================================================================
In your Visual Studio solution:
4) Using Nuget:Install-Package Facebook
5) Implement the Facebook client:
public void PostMessage(string message)
{
try
{
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
dynamic result = fb.Post("me/feed", new
{
message = message
});
}
catch (Exception exception)
{
// Handle your exception
}
}
I hope this helps anyone who is struggling to figure this out.

facebook Access Token 400 bad request

I am using following code to retrieve facebook accessToken
string url = "https://graph.facebook.com/oauth/access_token?" +
"client_id={0}" +
"&redirect_uri={1}" +
"&client_secret={2}" +
"&code={3}";
url = string.Format(url, clientId, redirectUri.EncodeUrl(), clientSecret, code);
//Create a webrequest to perform the request against the Uri
WebRequest request = WebRequest.Create(url);
try
{
//read out the response as a utf-8 encoding and parse out the access_token
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
//string urlRedirects = response.ResponseUri.ToString();
Encoding encode = Encoding.GetEncoding("utf-8");
if (stream != null)
{
StreamReader streamReader = new StreamReader(stream, encode);
string accessToken = streamReader.ReadToEnd().Replace("access_token=", "");
streamReader.Close();
response.Close();
return accessToken;
}
}
}
}
catch
{
return null;
}
however I am constantly receiving this ambiguous error message
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
I checked the code 100 "Invalid parameter" doesn't means much to me at all.
anyone have had similar problem?
Check you are adding correct code in the url
For example
http://www.xyz.com/?code=AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20#_=_
Code must be
code = AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20
code should not include following in the end
#_=_
If above did not solve the problem
2. redirect_uri must end with /
redirect_uri=http://www.xyz.com/
The following gives some times above mentioned error
redirect_uri=http://www.xyz.com
3. A lso make sure
App on Facebook and Website with Facebook Login are set with same addresss
e.g http://www.xyz.com/
You need to send the user to the Facebook Login page to get a valid code. The code should then be used to get the access_token for the user.
Follow the Authentication Guide.
I also got error message 400, when my app id and secret were wrong (i had messed up develop and production id-s and secrets).
Fixing them (watch also out for the correct host) fixed this problem for me.

How to post images to facebook via windows phone?

In my application image has to post to Facebook,mail.Sorry i am new to windows phone.i don't have a idea.please help me.what i can do first.
If you want to share a status you can use your facebook account on your phone using Share link task (with this method you can only post on your wall) http://msdn.microsoft.com/en-us/library/hh394027%28v=vs.92%29.aspx
To post (pictures, messages or others) on every wall you have access you need some things :
First you need to create a facebook application using this link :
Facebook developers
After that you need to identify yourself using a WebBrowser control with the link related to your application. The application requests authorization to perform certain actions such as posting. You need to detail the authorizations like this :
Dictionary<string, string> uriParams = new Dictionary<string, string>() {
{"client_id", "your app id"},
{"response_type", "token"},
{"scope", "user_about_me, offline_access, publish_stream"}, //The rights
{"redirect_uri", "http://www.facebook.com/connect/login_success.html"},
{"display", "touch"}
};
The Dictionary also contains the redirection uri to define if the operation was successful.
Finally you are authentified and receive an access token. Now you can use a WebRequest POST to post a message using this token :
WebRequest request = HttpWebRequest.Create("https://graph.facebook.com/" + the id of your wall + "/feed");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream((reqResult) =>
{
using (Stream strm = request.EndGetRequestStream(reqResult))
using (StreamWriter writer = new StreamWriter(strm))
{
writer.Write(client.AccessToken);
writer.Write("&message=" + HttpUtility.UrlEncode(status));
}
request.BeginGetResponse((result) =>
{
try
{
var response = request.EndGetResponse(result);
using (var rstrm = response.GetResponseStream())
{
var serializer = new DataContractJsonSerializer(typeof(FacebookPostResponse));
var postResponse = serializer.ReadObject(rstrm) as FacebookPostResponse;
callback(true, null);
}
}
catch (Exception ex)
{
callback(false, ex);
}
}, null);
}, null);
Here is how to post a message on a facebook page,
You should give the Facebook C# SDK a try
Facebook C# SDK
I have built this in once in an app of mine. They have plenty examples available which should be useful.

deauthorize the user from facebook app

I am getting
A network error occurred while trying to communicate
with Facebook: Facebook POST failed (HTTP status code 400)
when I
try to deauthorize the user from an app.
I am using restfb1.5.1. I
set the access token and other things correctly. This is how I call .
DefaultFacebookClient facebookClient = new
DefaultFacebookClient(access_token);
boolean result = false;
try {
result = facebookClient.deleteObject(userId);
} catch (com.restfb.FacebookException e) {
e.printStackTrace();
}
Due to facebook, if I don't specify the permission,it will
deauthorizes the app.
Anything that I miss?
Thanks ahead.
Use restfb1.6.6 and Check!!
Best wishes..