Publishing in facebook page as admin in v2.3 Javascript api - javascript

I try to post in fan page as admin but it does not work:
it works but not as admin
var wallPost = {
access_token: token,
message: 'asdasdasd'
};
FB.api('/xxxxx/feed', 'post', wallPost, function(response) {
console.log(response);
});
This has an error:
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);
});
}else{
console.log(resp);
}
});
the error is:
"(#200) The user hasn't authorized the application to perform this action"
My scope: 'manage_pages,publish_actions,read_stream,user_groups'

Since v2.3, you need permission publish_pages (in addition to manage_pages) to post as a page.
They separated this from publish_actions, which is now for posting as a user only.
(See also: https://developers.facebook.com/docs/apps/changelog#v2_3_changes)

Related

Login With Google Open browser instead of Open goolge plus app Cordova

Hi i tried following this tutorial to use authentication with google plus https://stackoverflow.com/questions/23930744/how-to-use-google-login-api-with-cordova-phonegap but the prolem is when i click to login button it open browser and load google plus from browser. What i want is when i click the login button its pop up the google plus app like other native app ? The question is can i achive that with cordova ? and if yes how do i do that ? thanks
here is how to login with google based on that stacoverflow answer above
var googleapi = {
authorize: function(options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
//which sets the authorization code in the browser's title. However, we can't
//access the title of the InAppBrowser.
//
//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
//authorization code will get set in the url. We can access the url in the
//loadstart and loadstop events. So if we bind the loadstart event, we can
//find the authorization code and close the InAppBrowser after the user
//has granted us access to their data.
$(authWindow).on('loadstart', function(e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function(data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function(response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
// alert('starting');
googleapi.authorize({
client_id: 'client_id',
client_secret: 'Client_Secret',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function(data) {
accessToken = data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
console.log(JSON.stringify(data));
getDataProfile();
});
}
// This function gets data of user.
function getDataProfile() {
var term = null;
// alert("getting user data="+accessToken);
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function(jqXHR, text_status, strError) {},
success: function(data) {
var item;
console.log(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin = "true";
localStorage.gmailID = data.id;
localStorage.gmailEmail = data.email;
localStorage.gmailFirstName = data.given_name;
localStorage.gmailLastName = data.family_name;
localStorage.gmailProfilePicture = data.picture;
localStorage.gmailGender = data.gender;
}
});
disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function(e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
}
});
}

XSRF with AngularJS: DocuSign API Embedded View Client-Side implementation

I have an AngularJS application that is utilizing the DocuSign Embedded Signing REST API to open a tab with the embedded document to DocuSign after the user completes a form.
I have looked around StackOverflow on some topics to help, but I can't find anything like my implementation.
I continue to get a 401 error on login, and I'm pretty sure it's because of CORS being blocked.
Any help is appreciated!
Here is my DocuSign factory:
app.factory('dsFactory', function($http) {
return {
login: function(templateId) {
return $http({
url: 'https://demo.docusign.net/restapi/v2/login_information',
method: 'GET',
params: {
'X-DocuSign-Authentication': {
'DocuSignCredentials': {
'UserName': 'xxx',
'Password': 'xxx',
'IntegratorKey': 'xxx'
}
}
}
});
},
envelope: function(baseUrl, templateId, recipientName, templateRoleName) {
var url = baseUrl + "/envelopes";
return $http({
url: url,
method: 'POST',
params: {
"emailSubject": "DocuSign API call - Embedded Sending Test",
"templateId": templateId,
"templateRoles": [{
"email": "xxx",
"name": recipientName,
"roleName": templateRoleName
}],
"status": "sent"
}
});
},
getUrl: function(baseUrl, envelopeId, recipientName) {
var url = baseUrl + "/envelopes/" + envelopeId + "/views/recipient";
return $http({
url: url,
method: 'POST',
params: {
"returnUrl": "http://www.docusign.com/devcenter",
"authenticationMethod": "email",
"email": "xxx",
"userName": recipientName
}
});
}
};
});
And here is the promise chain to open a new tab with the embedded document view:
// Elaborate promise chain for DocuSign login and document url retrieval
loginPromise = dsFactory.login($scope.templateId);
loginPromise.then(
function(payload) {
$scope.dsBaseUrl = payload.data.loginAccounts[0].baseUrl;
envelopePromise = dsFactory.envelope($scope.dsBaseUrl, $scope.templateId, $scope.businessName, 'Signer');
envelopePromise.then(
function(payload) {
$scope.dsEnvelopeId = payload.data.envelopeId;
urlPromise = dsFactory.getUrl($scope.dsBaseUrl, $scope.dsEnvelopeId, $scope.businessName);
urlPromise.then(
function(payload) {
$scope.dsCompleteUrl = payload.data.returnUrl;
window.open($scope.dsCompleteUrl);
},
function(errorPayload) {
console.log('retrieve DS url failed' + '\n');
console.log('Status: ' + errorPayload.status);
}
);
},
function(errorPayload) {
console.log('retrieve DS envelopeId failed' + '\n');
console.log('Status: ' + errorPayload.status);
}
);
},
function(errorPayload) {
console.log('DS login failed' + '\n');
console.log('Status: ' + errorPayload.status);
}
);
Any thoughts or assistance on how I can get this integration working?
Maybe something to do with the headers?
This issue is not specific to Angular.
If you can either use callback or ask target domain to add your domain in the "Access-Control-Allow-Origin" header. For your specific issue, I don't think you can ask DocuSign to do this. It leaves you with #2.
You can call the API from server side.
Angularjs https (browser)->your server->DocuSign API>your server->browser

OAuth 2.0 and Phonegap's InAppBrowser for Authentication

I am trying to use Oauth 2.0 to authenticate users signing in their google accounts. I will need access to their names and email addresses for this. I am using phonegap's InAppBrowser to do this.
So far I have this:
function openPage() {
var login_url = "https://accounts.google.com/o/oauth2/auth" + '?' + $.param({ client_id: "(not shown)", redirect_uri: "http://www.google.com", response_type: "token", scope: "openid profile email" });
var loginWindow = window.open(login_url, '_blank', 'location=yes');
loginWindow.addEventListener('loadstop', function(e) {
var url = e.url;
var access_token = url.split("access_token=")[1];
validateToken(access_token);
});
function validateToken(token) {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' + token,
data: null,
success: function(responseText){
alert("Validation Success!");
getUserInfo(token);
},
dataType: "jsonp"
});
}
function getUserInfo(token) {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + token,
data: null,
success: function(resp) {
user = resp;
alert(JSON.stringify(user));
},
dataType: "jsonp"
});
}
}
The validation of the token works everytime, but once it calls getUserInfo() the JSON returned is filled with errors and invalid credential strings. What am I doing wrong? Thanks!
I guess you need to set the token in Authorization header as per the documentation for Userinfo endpoint found here

JS Google+ Retrieve Circles List

I'm trying to request the URL to get Circles List for user in an app using JavaScript:
my code is
var scopes = ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.circles.read',
'https://www.googleapis.com/auth/plus.media.upload',
'https://www.googleapis.com/auth/plus.profiles.read',
'https://www.googleapis.com/auth/plus.stream.read',
'https://www.googleapis.com/auth/plus.stream.write',
'https://www.googleapis.com/auth/plus.circles.write',
'https://www.googleapis.com/auth/paymentssandbox.make_payments',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.google.com/m8/feeds/contacts/default/full'];
function getCircles() {
$.ajax({
type: 'GET',
url: 'https://www.googleapis.com/plusDomains/v1/people/me/circles?access_token=' + access_token,
dataType: 'jsonp',
success: function (response) {
console.log(response);
},
error: function (e) {
console.log(e);
}
});
}
and I turned on permissions in my app
Google+ API
Google+ Domains API
But this request retrieved
error
Object { errors=[1], code=403, message="Forbidden"}
code
403
errors
[Object { domain="global", reason="forbidden", message="Forbidden"}]
0
Object { domain="global", reason="forbidden", message="Forbidden"}
domain
"global"
message
"Forbidden"
reason
"forbidden"
message "Forbidden"

OAuthException:(#200) The user hasn't authorized the application to perform this action [duplicate]

This question already has answers here:
Facebook OAuthException: "user hasn't authorized the application to perform this action"
(4 answers)
Closed 7 years ago.
I am trying to post on to the page of Fb from my javascript i am getting this error
(#200) The user hasn't authorized the application to perform this action
"OAuthException"
I am able to post the to my FB wall at the same time but not to the FB fan page where i am admin. Please guide me what is getting wrong. My code :
<input type="submit" class="btn"
onclick="postToFeed(); return false;"
value="Share with Friends"/>
<input type="submit" class="btn"
onclick="postToPage(); return false;"
value="Share On Page"/>
<p id='msg'></p>
<script>
FB.init({appId: '{!appId}', status: true, cookie: true});
function postToPage() {
var page_id = '1426984900889247';
FB.api('https://graph.facebook.com/' + page_id, {fields: 'access_token'}, function(resp) {
console.log(resp);
console.log(resp.access_token);
if(resp.access_token) {
FB.api('https://graph.facebook.com/' + page_id + '/feed',
'post',
{ message: "{!posDetails.Name}",
description :'{!posDetails.CMSR__Job_Description__c}',
link : '{!siteUrl}',
picture: '{!posDetails.CMSR__Linked_In_Url__c}',
caption: '{!posDetails.CMSR__Summary__c}',
access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
alert(resp);
}
function postToFeed() {
var obj = {
method: 'feed',
link: '{!siteUrl}',
picture: '{!posDetails.CMSR__Linked_In_Url__c}',
name: '{!posDetails.Name}',
caption: '{!posDetails.CMSR__Summary__c}',
description: '{!posDetails.CMSR__Job_Description__c}'
};
function callback(response) {
if (response['post_id']) {
var postId = response['post_id'].split('_')[1];
document.getElementById('msg').innerHTML =
"Posted to your wall. "+
"<a href=\"https://www.facebook.com/permalink.php?"+
"id={!me.id}&v=wall&story_fbid="+postId+"\">View your post</a>";
}
}
FB.ui(obj, callback);
}
</script>
<script>
$( document ).ready(function() {
var nameID;
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me/accounts', function(response){
console.log(response);
console.log(response.data);
var data= response['data'];
var ids = new Array();
var name = new Array();
console.log('data');
console.log(data);
console.log('ID');
console.log(ids);
for(var i=0; i<data.length; i++){
ids[i] = data[i].id;
name[i] = data[i].name;
if(ids[i] != null){
console.log(ids[i]);
if(nameID == 'undefined'){
nameID = ids[i]+':'+data[i].name+';';
}
else{
nameID = nameID+' '+ids[i]+':'+data[i].name+';';
}
}
}
setVar(nameID);
console.log('method called ');
console.log(ids);
console.log(name);
console.log(nameID);
});
}
else {
FB.login();
FB.api('/me/accounts', function(response){
console.log(response);
});
}
});
function setVar(param){
jQuery('[id$=myHiddenField]').val(param);
console.log('Param value '+param);
passStringToController();
}
});
</script>
Th error means you have not taken permissions. Get access tokens then try. To write to User feed you will need publish_actions permission.
I believe editing your Graph API call code will do the trick.
FB.api('https://graph.facebook.com/' + page_id + '/feed',
'post',
{
message: "{!posDetails.Name}",
description :'{!posDetails.CMSR__Job_Description__c}',
link : '{!siteUrl}',
picture: '{!posDetails.CMSR__Linked_In_Url__c}',
caption: '{!posDetails.CMSR__Summary__c}',
access_token: resp.access_token
},
function(response) {
console.log(response);
});
},
{scope: 'publish_actions'}
);
The last part is where you take permissions.
You should also try experimenting with your Graph API call before putting them up in code.
Here is a link for Graph call Explorer. Try experimenting here with the Access Tokens(Permissions) & API versions.
If you want a tutorial you will find it on this link http://lynda.com/Facebook-tutorials. Though it is not for Free it is worth it.

Categories