Post to Facebook Page from Facebook App - facebook

I want to post from my Facebook app to one of my pages using app_id and app_secret. It will help me to post directly without log in to Facebook.
I'm able to post on my profile, but not on my page!
Here is my code:
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type={2}",
app_id, app_secret, "client_credentials");
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("/my-page-FB-ID/feed", new { desctiption = description, picture = picture, link = link, caption = caption, type = type });

Related

Getting 403 forbidden error while accessing linkedIn 2.0 API from SharePoint 2013 web part

API: https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)
App Permission: r_basicprofile, r_emailaddress, w_share
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string requesturl = "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)";
HttpWebRequest webRequest = System.Net.WebRequest.Create(requesturl) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.Host = "api.linkedin.com";
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.Connection = "Keep-Alive";
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
//Stream dataStream = webRequest.GetRequestStream();
//String postData = String.Empty;
//byte[] postArray = Encoding.ASCII.GetBytes(postData);
//dataStream.Write(postArray, 0, postArray.Length);
//dataStream.Close();
WebResponse response = webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
If you are using V2 API and you did not taken permission to use r_basicprofile then either apply for permission to use r_basicprofile to linkedin
OR use r_liteprofile + r_emailaddress for V2
(also check r_liteprofile permission is there in your app or not )
r_liteprofile for firstName,lastName,profilePicture,id
r_emailaddress for getting emailAddress
Check this : https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/migration-faq?context=linkedin/consumer/context

How to get Twitter User Email using Xamarin.Auth library

I m trying to implement twitter authentication for my xamarin app. I checked Request email addresses from users option on developer console but i am not able to get email in user information. Am i doing something wrong
var Twitterauth = new OAuth1Authenticator(
consumerKey: "XXXX",
consumerSecret: "XXX",
requestTokenUrl:new Uri("https://api.twitter.com/oauth/request_token"),
authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"),
accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"),
callbackUrl: new Uri("http://www.isportfoy.com.tr/tr/anasayfa")
);
Twitterauth.Completed += (s, ee) =>
{
if (ee.IsAuthenticated)
{
var request = new OAuth1Request(
"GET",
new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"),
null,
ee.Account);
request.GetResponseAsync().ContinueWith(t =>
{
var res = t.Result;
var resString = res.GetResponseText();
Console.WriteLine("Result Text: " + resString);
});
}
else
{
}
};
Twitter API requires us to indicate if we want to the user email in the response.
Based on the Twitter Documentation this can be done sending the include_email as true.
Full documentation: https://dev.twitter.com/rest/reference/get/account/verify_credentials
if (e.IsAuthenticated)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("include_email","true");
var request = new OAuth1Request(
"GET",
new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"),
param,
e.Account);
}

Service to Service Calls Using Client Credentials

I tried to create an alias for group in office 365 using below code but it shows some error.how to solve this. I tried to use service to service calls method. I got the token generated. How to check its valid or not? Is it possible to create alias using api for group without powershell option? if no kindly advice me to for other options..
string clientId = "************";
string clientsecret = "******";
string tenantId = "********";
//string resourceUri = "http://office.microsoft.com/outlook/";
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
var authUri = "https://login.windows.net/" + tenantId + "/oauth2/authorize/";
var RESOURCE_URL = "https://graph.windows.net";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'displayName': 'mailgrouptest',
'groupTypes': ['Unified'],
'mailEnabled': true,
'mailNickname': 'mailalias1',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups", httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
When i run this code in console it shows an error like this....is the problem with token ? or tenant id?
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {``
"request-id": "*****-***-",
"date": "2016-05-25T04:53:08"
}
}
}
kindly advice me to create alias for group in api
The mailNickName of group is not able to update using the Microsoft Graph at present.
As a workaround, we can create a new group with the specific the mailNickName you wanted and use the new group. Here is the code to create a group with mailNicekName for your reference:
string clientId = "";
string clientsecret = "";
string tenant = "yourdomain.onmicrosoft.com";
var authUri = "https://login.microsoftonline.com/"+tenant+"/oauth2/token";
var RESOURCE_URL = "https://graph.microsoft.com";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'description': 'description-value',
'displayName': 'displayName-value',
'groupTypes': [
'Unified'
],
'mailEnabled': true,
'mailNickname': 'mailNickname-value',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
//var response = client.GetAsync("https://graph.microsoft.com/v1.0/groups").Result;
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups",httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
More detail about Goupr REST API, please refer to here.
For the error “InvalidAuthenticationToken” you were request the access token with incorrect resource. To use the Microsoft Graph API, we need to specify the resource with “https://graph.microsoft.com” instead of “https://graph.windows.net”.
In addition, if you want the mailNickName of group is updateable, you can try to submit the feedback from here.

facebook sharing on servlet, jsp; getting auth code;

public FacebookConnector() {
try {
FacebookClient.AccessToken token = getFacebookUserToken("???", "http://localhost:8083/CrunchifyJSPServletExample/");
String accessToken = token.getAccessToken();
Date expires = token.getExpires();
fbClient = new DefaultFacebookClient(this.accessToken, Version.LATEST);
myuser = fbClient.fetchObject("me", User.class);
mypage = fbClient.fetchObject(pageID, Page.class);
counter = 0;
} catch (Exception ex) { //So that you can see what went wrong
ex.printStackTrace(System.err); //in case you did anything incorrectly
}
}
public void makeTestPost() {
FacebookType publishMessageResponse = fbClient.publish("me/feed", FacebookType.class, Parameter.with("message", "Test from Graph API"));
System.out.println("Published message ID: " + publishMessageResponse.getId());
}
private FacebookClient.AccessToken getFacebookUserToken(String code, String redirectUrl) throws IOException {
String appId = "My App Id";
String secretKey = "My Secret Key";
WebRequestor wr = new DefaultWebRequestor();
WebRequestor.Response accessTokenResponse = wr.executeGet(
"https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&redirect_uri=" + redirectUrl
+ "&client_secret=" + secretKey + "&code=" + code);
return DefaultFacebookClient.AccessToken.fromQueryString(accessTokenResponse.getBody());
}
I am working on enabling facebook sharing for my application that is built on JSP and servlet.
I am using above code.
I need your inputs on 2 things:
1) If my approach is correct.
2) How to get auth code? So that can help me in getting authentication token.
Help of any sort is appreciated. Thanks. AY
For facebook authentication you can do like that:-
Click
It will generate code then use this code to send request to graph.facebook as you written correctly in your code then it will generate accesscode and use accesscode as per your requirement

Facebook JS connect unsupported browser IE mobile

I am getting error "unsupported browser: IE" when I am trying to login using facebook in windows mobile device(Lumia 800). Is there any way it can be fixed or facebook have to do fixes in their script. Or any other workaround can be done for this issue? Please suggest.
I have faced this problem as well with a big project I did for Microsoft. I needed to oath with Facebook on windows mobile devices, and got the same error. This is how I solved it:
Generally there are two ways to oath with javascript - the simple way (which generates this error) described here:
https://developers.facebook.com/docs/javascript/quickstart
and the manually build login flow described here:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
Here is a quick explanation of what you have to do for the second option:
1) Load SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
2) On page load check for access_token. If the user didn't login, there will be no access token. if the user did, there will be access token appended to the URL as a query but with '#' instead of '?'
I used this function:
function getUrlVars()
{
var query = '#';//normally ?
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf(query) + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Now determine if you got the access_token:
var urlString = getUrlVars();
var hasAccess=false;
var userToken;
if(typeof(urlString)!='undefined' && typeof(urlString.access_token)!='undefined'){
hasAccess=true;
userToken=urlString.access_token;
}
if user has access redirect them to the same (or other) url with the app id, access token and response type:
var appID = 'your app id';
if(!hasAccess){
$('#login').on('click',function(){
var login_redirect_uri = 'http://www.yourpage.com/';
var login_response_type = 'token';
var loginURL = 'https://www.facebook.com/dialog/oauth?client_id='+appID+'&redirect_uri='+login_redirect_uri+'&response_type='+login_response_type;
window.location.replace(loginURL);
});//login-click
}
3) if there is no access token in the url query, use a server side service (we will build below) to validate the token
var tokenValidate = 'https://titan-img-gen.aws.af.cm/toeknValidate.php';
$.ajax({
type: 'GET',
url: tokenValidate,
crossDomain: true,
data:{
token:userToken
},
dataType:'json',
success: function(validateData){
if(validateData.error){
showError();
}else{
username = validateData.username;
firstname = validateData.firstname;
lastname = validateData.lastname
//continue your code
}
},
error: function (responseData, textStatus, errorThrown) {
showError();
}
});
4) Server side service (PHP)
a)generate app token: https://developers.facebook.com/docs/facebook-login/access-tokens/
b)same origin resolution might be needed:
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
c) define app_token :
$app_token='*******';
d)check for token parament in get
$reponse = array();
if(!isset($_GET['token']) || $_GET['token']==NULL ){
$reponse['error'] = true;
}else{
$user_access_token = $_GET['token'];
//continue here...
}
e) use facebook graph service to debug token
$fbDebug = "https://graph.facebook.com/debug_token?input_token=$user_access_token&access_token=$app_token";
f)get the json file, decode it and get the user_id from it. you can then retrieve more info from Facebook easily
try{
$fbResult = file_get_contents($fbDebug);
$fbResultDecode = json_decode($fbResult);
if(isset($fbResultDecode->data->error)){
$reponse['error'] = true;
}else{
$user_id= $fbResultDecode->data->user_id;
$userJSON = file_get_contents("https://graph.facebook.com/$user_id");
$userInfo = json_decode($userJSON);
$reponse['username'] = $userInfo->username;
$reponse['firstname'] = $userInfo->first_name;
$reponse['lastname'] = $userInfo->last_name;
}
}catch(Exception $e){
$reponse['error'] = true;
}
g)return the JSON
header('Content-Type: application/json');
echo json_encode($reponse);
Bada-Bim-Bada-Boom
I lied, it wasn't a quick explanation... but I hope it will save you some time!!!
Tomer Almog