FB API email 'undefined' for some users - facebook

I have an MVC application and i retry Facebook value with this code:
FB.login(function (response) {
if (response.status == 'connected') {
var userId = response.authResponse.userID;
var userToken = response.authResponse.accessToken;
FB.api(
'/' + userId,
{ fields: 'name,email,first_name,last_name' },
function (userInfo) {
if (userInfo && !userInfo.error) {
var uf = new FormData();
uf.append("email", userInfo.email);
uf.append("userId", userInfo.id);
uf.append("name", userInfo.name);
uf.append("first_name", userInfo.first_name);
uf.append("last_name", userInfo.last_name);
var url = "/Account/ExternalRegisterFacebook";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
},
success: function (responseLogin) {
}
});
}
});
}
});
I can correctly log with my account but when i use another Facebook account i have all user value except email, that is 'undefined'.
I have read a lot of posts but i haven't understand how to solve this type of problem. I don't know if is an application error or a security information of each single Facebook profile.
Thanks to all

Related

Getting posts by tag instagram - 404

Below is my current code to get the latest instagram pics.
getInstagram:function(num_photos) {
var token = 'xxxxxx',
userid = xxxxxxxx,
num_photos = num_photos; // how much photos do you want to get
var x;
var instapics = [];
var instalink = [];
$.ajax({
url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent',
dataType: 'jsonp',
type: 'GET',
data: {access_token: token, count: num_photos},
success: function(data){
for( x in data.data ){
instalink.push(data.data[x].link);
instapics.push(data.data[x].images.standard_resolution.url);
}
var index = 0;
var holders = $('.grid .instagram-holder');
$(holders).each(function() {
$(this).html('<img src='+instapics[index]+' />').wrap("");;
index++;
});
},
error: function(data){
}
});
},
I now want to get them by tag 'people', I have added the endpoint
url: 'https://api.instagram.com/v1/tags/people/media/recent',
and
url: 'https://api.instagram.com/v1/tags/people/media/recent?access_token='+token
but get a 404. What am I doing wrong?
Are you sure you're getting a 404 and not a 403?
You probably only have the basic permission. You'll need the public_content permission for that endpoint.

How to use the login credentials with php in ionic project

I want to authenticate the user_name and password field. the user_name and password field is stored in database with php. how to get the data from the server in ionic project.
Thanks in advance.
You can create a service script that can send post data to PHP and receive a JSON response.
Post data should be sent as an object containing element name and values in the following format:
var myObj = {username: 'username', password:'password'};
Below is a service example:
yourApp.service('YourService', function ($q, $http) {
return {
login: function (data) {
var deferred = $q.defer(),
promise = deferred.promise;
$http({
url: 'http://www.example.com/yourPHPScript.php',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
if (response.data.error.code === "000") {
deferred.resolve(response.data.appointments);
} else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error);
});
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
return promise;
}
};
});
From your login controller you call the following code to use the service (make sure you add the name of the service to your controller declaration)
YourService.login(loginData)
.then(function (data) {
// on success do sthg
}, function (data) {
//log in failed
// show error msg
});

upload base64 image facebook graph api how to use this script

Upload Base64 Image Facebook Graph API
i want to use this script that link is attached how i can use this in my wordpress post?
i want to use this for fbcover photo site.
Take a look at this code I hacked together from various examples - you can use this to post a pure base64 string to the Facebook API - no server side processing.
Here's a demo: http://rocky-plains-2911.herokuapp.com/
This javascript handles the converting of a HTML5 Canvas element to base64 and using the Facebook API to post the image string
<script type = "text/javascript">
// Post a BASE64 Encoded PNG Image to facebook
function PostImageToFacebook(authToken) {
var canvas = document.getElementById("c");
var imageData = canvas.toDataURL("image/png");
try {
blob = dataURItoBlob(imageData);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", authToken);
fd.append("source", blob);
fd.append("message", "Photo Text");
try {
$.ajax({
url: "https://graph.facebook.com/me/photos?access_token=" + authToken,
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data);
$("#poster").html("Posted Canvas Successfully");
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
console.log("Posted to facebook");
}
});
} catch (e) {
console.log(e);
}
}
// Convert a data URI to blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/png'
});
}
</script>
This handles the Facebook Authentication and shows basic HTML setup
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
cache: true
});
$.getScript('//connect.facebook.net/en_UK/all.js', function () {
// Load the APP / SDK
FB.init({
appId: '288585397909199', // App ID from the App Dashboard
cookie: true, // set sessions cookies to allow your server to access the session?
xfbml: true, // parse XFBML tags on this page?
frictionlessRequests: true,
oauth: true
});
FB.login(function (response) {
if (response.authResponse) {
window.authToken = response.authResponse.accessToken;
} else {
}
}, {
scope: 'publish_actions,publish_stream'
});
});
// Populate the canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.font = "20px Georgia";
ctx.fillText("This will be posted to Facebook as an image", 10, 50);
});
</script>
<div id="fb-root"></div>
<canvas id="c" width="500" height="500"></canvas>
<a id="poster" href="#" onclick="PostImageToFacebook(window.authToken)">Post Canvas Image To Facebook</a>
I needed this too, and was not happy with all the code around it because it is lengthy and usually needs jQuery. Here is my code for uploading from Canvas to Facebook:
const dataURItoBlob = (dataURI) => {
let byteString = atob(dataURI.split(',')[1]);
let ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: 'image/jpeg'
});
}
const upload = async (response) => {
let canvas = document.getElementById('canvas');
let dataURL = canvas.toDataURL('image/jpeg', 1.0);
let blob = dataURItoBlob(dataURL);
let formData = new FormData();
formData.append('access_token', response.authResponse.accessToken);
formData.append('source', blob);
let responseFB = await fetch(`https://graph.facebook.com/me/photos`, {
body: formData,
method: 'post'
});
responseFB = await responseFB.json();
console.log(responseFB);
};
document.getElementById('upload').addEventListener('click', () => {
FB.login((response) => {
//TODO check if user is logged in and authorized publish_actions
upload(response);
}, {scope: 'publish_actions'})
})
Source: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-from-canvas/

Posting a photo and tagging a friend using Facebook Graphs API

I have this code which posts to the user's wall:
FB.api('/me/photos', 'post', {
message:'photo description',
url:imgURL
}, function(response){
console.log(response);
if (!response || response.error) {
console.log(response);
}else{
FB.api(response.id+'/tags/me', {
to: $("#recipientID").val()
}, function(response){
console.log(response)
});
}
});
The first part works perfectly I just cannot figure out how to tag a friend into it, my tag call gives me an empty array back. Facebook documentation is really difficult to understand and it doesn't really give any examples of how to do this so please don't just give me a link to their documentation because I've already read anything they have that's relevant and I still can't do it.
Also tried this with no success:
FB.api('/me', function(response){
var userId = response.id;
FB.api('/'+response.id+'/tags/'+userId, {
to: $("#recipientID").val()
}, function(response){
console.log(response)
});
});
I finally managed to crack it, it's a different call than what I was using:
FB.api('/me/photos', 'post', {
message:'Checking tags',
url:imgURL
}, function(response){
if (!response || response.error) {
console.log(response);
}else{
//tags friend
var postId = response.id;
FB.api(postId+'/tags?to='+friendID, 'post', function(response){
if (!response || response.error) {
console.log(response);
}
});
}
});
you cant upload and tag friends in the same call , you have to upload first , then tag the friends . if there is more then on friend then you have to tag them one by one using loop , other will it'll not work ,
I started with the code in this post to tag multiple people in a photo. It works in my code base, I've tried to distill it but it could use some more work, not sure. Figured it might help someone trying to do the same thing.
If anyone has any ideas for improvement I'm all ears:
//Set empty array of Friend ID's
var friendIds = []
//Get friend ID's
getFriendById = function(id) {
var i, len;
id = id.toString();
for (i = 0, len = friends.length; i < len; i += 1) {
if (friends[i].id === id) {
return friends[i];
}
}
friendIds.push(friends);
};
var postToWall = function(){
//Assign Friends to variables
var name1 = getFriendById(friendIds[0]);
var name2 = getFriendById(friendIds[1]);
var name3 = getFriendById(friendIds[2]);
//Set empty array for tags
var tags = [];
//Loop through friends and make an array ready for posting
$.each(selectfriends, function(i,friend){
var new_tag = {tag_uid: friend};
tags.push(new_tag);
})
//Post photo to wall
FB.api('/me/photos', 'post', {
message:'Enter custom message',
url: 'link/to/photo.jpg'
}, function(response){
console.log(response)
if (!response || response.error) {
console.log('error');
} else {
//Tag Friends
var postId = response.id;
//Use stringify to send the array in string to facebook
FB.api(postId+'/tags?tags='+JSON.stringify(tags), 'post', function(response){
if (!response || response.error) {
console.log('error');
}
});
}
});
}

Send a wall post using Jquery's AJAX (Post)

I'm trying to post a wall message from a local desktop application (I can't use the FB JS SDK).
Here's a a snippet of my code
var url = "https://graph.facebook.com/me/feed";
var params = "access_token=" + token + "&message=" + encodeURI(text);
$.ajax({
crossDomain: true,
data: params,
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
The request ignores the message parameter.
I receive a list of feeds as it were a GET request.
I've tried to set the parameters as map but it didn't help.
BTW - when using CURL (in C++) i manage to post the data correctly.
Any ideas why it ignores the parameters?
I would put the "params" into the data element like so:
var url = "https://graph.facebook.com/me/feed";
$.ajax({
crossDomain: true,
data: { access_token: token, message: text },
dataType: "jsonp",
url: url,
type: 'POST',
success: function (data) {
if (callback) {
var isOK = (data && data.id && !data.error);
callback(isOK, data);
}
},
error: function (data, e1, e2) {
}
});
Let jQuery encode the parameters from there.
Below worked fine in Jquery 1.6.4 + jquery.mobile-1.0rc2 by setting $.mobile.allowCrossDomainPages = true; in mobileinit bind
$.ajax( {
url : "https://graph.facebook.com/me/feed",
type : "POST",
data : "access_token=" + your_access_token + "&message=my first wall post",
cache : false,
success : function(res) {
if (!response || response.error) {
alert("Couldn't Publish Data");
} else {
alert("Message successfully posted to your wall");
}
},
error : function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
}
});