Facebook post as page - javascript

I know this question was asked already often, but I have been trying to fix this problem for like more than 6 hours now and I could use a little help. Error Message: Insufficient permssion to post to target on behalf of the viewer.
I'm trying to post as page, my code so far:
var pageID = "myPage";
FB.init({
appId: "myId",
secret: "mySecret",
status: true,
cookie: true,
});
function postToFeed() {
FB.login(function(response) {
FB.api('/me/accounts', function(response) {
var accessToken = "";
var data = response.data;
for (var i=0; i<data.length; i++) {
if (data[i].id == pageID) {
accessToken = data[i].access_token;
}
}
if (accessToken == "") {
alert("You are not allowed to post.");
}
else {
console.log(accessToken);
FB.api('/' + pageID + '/feed', 'post', {
message : "test",
link : 'Link',
picture : 'Imageurl',
name : 'test',
to : pageID,
from : pageID,
description : 'test'
}, function(response) {
if (!response || response.error) {
alert(JSON.stringify(response.error));
} else {
alert('Post ID: ' + response.id);
}
});
}
});
}, {scope: 'publish_actions,manage_pages,public_profile'});
}
When I echo my accessToken via console and copy the accessToken inside this code, it works perfectly. But that's not an solution because I want it to be dynamic:
function postToFeed() {
FB.login(function(response) {
FB.api('/' + pageID + '/feed', 'post', {
access_token: 'theAcccessToken',
message: "I'm a Page!",
}, function(response) {
console.log(response);
}
);
}, {scope: 'publish_actions,manage_pages,public_profile'});
}

And this does not work? (not sure what you want to do with the "to" and "from" parameters, so i removed them)
FB.api('/' + pageID + '/feed', 'post', {
message : 'test',
link : 'Link',
picture : 'Imageurl',
name : 'test',
description : 'test',
access_token: accessToken
}
The most important thing: You need publish_pages to post "as Page", not publish_actions.
Btw, a small optimization:
for (var i = 0; i < data.length; i++) {
if (data[i].id === pageID) {
accessToken = data[i].access_token;
break;
}
}
if (accessToken === "") {
alert("You are not allowed to post.");
}
...always use typesafe comparison :)

Related

jQuery Execute function after asynchronous data load

I have created a jQuery function extending its own object $. This function translate those elements attached to the element this:
$.fn.extend({
translate: function(sourceLang, targetLang) {
if($(this).text().trim().length < 1 || !isNaN(parseInt($(this).text().trim())) || sourceLang == targetLang)
return;
let $function = this;
$($function).each(function() {
let $each = this;
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: $($each).text(),
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200)
throw "Response: " + response.code;
$($each).text(response.text[0])
} catch(error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', xhr.responseText);
}
});
});
}
});
After loading the code I do this:
$(document).ready(function() {
let lang = $('html').attr('lang').split('-')[0];
$('td td:visible').translate(lang, "en");
});
Note: the HTML tag looks like this <html lang="es-ES"> depending on the logged user language.
The issue I have is the table loads after a couple of seconds (since we are not in Production environment they could be more than 30). Therefore the previous code block is not useful.
Note: the <tbody> tag is created when the data is added.
What I have tried is:
1. Create a setInterval() and clearInterval() when the $('td:visible').length is greater than 0:
let iv = setInterval(function() {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.translate(lang, "en");
clearInterval(iv);
}
}, 1000);
2. Set a .delay() before the translation:
let isTranslated = false;
while(!isTranslated) {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.delay(1000).translate(lang, "en");
isTranslated = true;
}
}
The memory consumed by the browser is greater than 200MB. I also tried with $('table').on('DOMSubstreeModified', 'tbody', function() {}) but it didn't work.
So, what approach would you recommend to use this translation plugin on this table after it loads its tbody?
Edit 1:
I have changed my code so I perform less API requests, thanks to the recommendation of #lucifer63:
let $function = this;
let collection = [];
let translation = '';
$(this).each(function() {
collection.push($(this).text());
});
let text = collection.join('::');
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: text,
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200) {
throw "Response: " + response.code;
}
translation = response.text[0].split('::');
$($function).each(function() {
$(this).text(translation.shift());
});
} catch(error) {
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Message returned by the server:', xhr.responseText);
}
});
But still, I need to figure out how to print after data has loaded.
Well... I think I found the answer I was seeking:
$('body').on('DOMNodeInserted', 'table', function() {
$('td:visible').translate('es', 'en');
});
It seems it is working correctly.

How can I post message in Yammer Group with link user?

Yammer REST api json. My code send message in group succesfull. But I need to send msg with "cc", link some user, like this:
function yamPostRequest(val) {
var msg_value = document.getElementById('msg_body').value;
var groupID = document.getElementById('group_id').value;
if (msg_value == "") {
alert("Message body cannot be empty!");
return false;
}
if (groupID == "") {
var conf = confirm("Group ID is empty, message will be posted to All Company");
if (conf == false) {
return false;
}
}
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages.json",
method: "POST",
data: {
"body": msg_value,
//"title" : msg_title,
"group_id": groupID,
},
success: function(msg) {
alert("Post was Successful!");
},
error: function(msg) {
alert("Post was Unsuccessful");
}
})
}
I found it.
function PostYammerWithNotification(group_id, message, userCC) {
var yammerData;
yammerData = {
group_id: group_id,
body: message
};
yammerData.cc = "[[user:" + userCC + "]]";
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages.json",
method: "POST",
data: yammerData,
success: function(msg) {
alert("Post was Successful!");
},
error: function(msg) {
alert("Post was Unsuccessful");
}
});
}
You need to use user ID:
PostYammerWithNotification(/*Group ID*/,"test msg",/*User ID*/)
Found it here

How to call web service in sencha touch 2?

I 'm beginner in sencha touch 2 and i need to call webservice.The code of web service is:
public function loginAction()
{
$request = $this->getRequest();
$username = $request->request->get('username');
$password= $request->request->get('password');
$success=false;
$token="error";
$error="test";
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('username' => $username));
if (! $user)
{
$token="username not exists";
$success=false;
}
else
{
$password_user=$user->getPassword();
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($password, $user->getSalt());
if ($password!=$password_user)
{
$token="password incorrect";
$success=false;
}
else
{
$token="logged";
$success=true;
}
}
$info= array("token" => $token);
$res=array("success"=> $success);
$res = array("status"=> $res,
"resultat"=>$info
);
$serializer = $this->get('jms_serializer');
$response = $serializer->serialize($res,'json');
return new Response($response);
}
and i make in project sencha a view: Login.js and a controller: Login.js. The problem is in calling the web service and the code in controller Login.js:
Ext.define('Sample.controller.Login', {
extend: 'Ext.app.Controller',
config: {
refs: {
loginView: 'loginview',
mainMenuView: 'mainmenuview'
},
control: {
loginView: {
signInCommand: 'onSignInCommand'
},
mainMenuView: {
onSignOffCommand: 'onSignOffCommand'
}
}
},
// Session token
sessionToken: null,
// Transitions
getSlideLeftTransition: function () {
return { type: 'slide', direction: 'left' };
},
getSlideRightTransition: function () {
return { type: 'slide', direction: 'right' };
},
onSignInCommand: function (view, username, password) {
console.log('Username: ' + username + '\n' + 'Password: ' + password);
var me = this,
loginView = me.getLoginView();
if (username.length === 0 || password.length === 0) {
loginView.showSignInFailedMessage('Please enter your username and password.');
return;
}
loginView.setMasked({
xtype: 'loadmask',
message: 'Signing In...'
});
Ext.Ajax.request({
url: 'http://localhost/dawinilastversion/web/app_dev.php/api/login',
method: 'post',
params: {
username: username,
password: password
},
success: function (response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
me.sessionToken = loginResponse.sessionToken;
me.signInSuccess(); //Just simulating success.
} else {
me.signInFailure(loginResponse.message);
console.log('erreur.');
}
},
failure: function (response) {
me.sessionToken = null;
me.signInFailure('Login failed. Please try again later.');
}
});
},
signInSuccess: function () {
console.log('Signed in.');
var loginView = this.getLoginView();
mainMenuView = this.getMainMenuView();
loginView.setMasked(false);
Ext.Viewport.animateActiveItem(mainMenuView, this.getSlideLeftTransition());
},
singInFailure: function (message) {
var loginView = this.getLoginView();
loginView.showSignInFailedMessage(message);
loginView.setMasked(false);
},
onSignOffCommand: function () {
var me = this;
Ext.Ajax.request({
url: 'http://localhost/dawinilastversion/web/app_dev.php/api/login',
method: 'post',
params: {
sessionToken: me.sessionToken
},
success: function (response) {
// TODO: You need to handle this condition.
},
failure: function (response) {
// TODO: You need to handle this condition.
}
});
Ext.Viewport.animateActiveItem(this.getLoginView(), this.getSlideRightTransition());
}
});
And the web service login work with success:
you need to go one step deeper into the JSON response:
if (loginResponse.status.success === true)
and check against the bool true not the string true

How to post to Facebook fanpage as fanpage, not user

How can I post on fanpage wall as fanpage not as a user - using javascript sdk.
RIght now on Init im receiving menage_pages and acquiring suitable fanpage id, how can i change call below?
var target = '/'+params.target+'/feed'
FB.api(target,
'post',
{ message: params.message,
link: params.link,
picture: params.picture,
caption: params.caption,
description: params.description,
name: params.name
}
,function(response) {
if (!response || response.error) {
$("#error").removeClass('hidden');
} else {
$("#success").removeClass('hidden');
}
});
You need the following permissions:
publish_stream
manage_pages
Now we call the page object to retrieve the page's access_token and then post with that token, something like:
function postToPage() {
var page_id = 'MY_PAGE_ID';
FB.api('/' + page_id, {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "I'm a Page!", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}
Result:
More about this in my tutorial.
All you need is those three functionalities to be implemented:
First one is for setting the basic parameters for your Application(XXX-APP needs to be changed with your real id of application).
Second, function fol login to Facebook and granting needed permissions to be able to post to Facebook.
Third function is for posting to Facebook(XXX-page need to be changed with ID of the Page that you want to post something)
FB.init({ appId: 'XXX-APP', status: true, cookie: true, xfbml: true, oauth: true });
access_token = '';
function loginFB(){
FB.login(function(response) {
if (response.authResponse) {
access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_stream,manage_pages'});
}
function postToPage() {
FB.api('/XXX-page', {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "MSG", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}

(#3) App must be on whitelist facebook

I'm trying to post a messsage to a wall using FB.api
My perms are: 'email, read_stream, publish_stream' and my code is:
FB.getLoginStatus(function(response){
if(response.session) {
var accessToken = response.session.access_token;
var tokenUrl = "https://graph.facebook.com/me/feed?access_token=" + accessToken + "&callback=?";
var shareUserId = document.getElementById("shareHidden").value;
var shareTxtAreaMsg = document.getElementById("shareTxtArea").value;
console.log("friends user Id: " + shareUserId + " & " + "message: " + shareTxtAreaMsg);
var data = {
message: "shareTxtAreaMsg",
display: 'iframe',
caption: "Caption",
name: "Name",
picture: 'http://someDomain.com/Dev/img/share-force-wall-img.jpg',
link: "http://www.facebook.com/pages/someapp/XXXXXXXXXXX?sk=app_XXXXXXXXXXXXXX", // Go here if user click the picture
description: "Description field",
actions: [{ name: 'action_links text!', link: 'some link' }],
}
console.log(accessToken);
FB.api(tokenUrl, 'post', data, function(response){
if (response)
{
//console.log(response);
if (response.error)
{
console.log(response.error.message);
}
else
{
if (response.id)
console.log("Posted as post_id "+response.id);
else if (response.post_id)
console.log("Posted as post_id "+response.post_id);
else
console.log("Unknown Error");
}
}
});
}
});
When when try to post the message I'm getting a "(#3) App must be on whitelist" returned. Why is this happening?
Try FB.api('/me/feed'... instead of tokenUrl because FB.api will automatically add the full url prefix.

Categories

Resources