Create profile photo for user on users facebook page - facebook-graph-api

I'm struggling creating a profile picture on behalf of a user on facebook.
What endpoint do I need to use to update the profile image for a user on facebook? And what permissions do i need as well?
I have the access token and I'm using react native.

Scopes
if querying an App-Scoped User ID:
None
If querying a User ID:
User or Page access token for Facebook Login authenticated requests
App access token for server-side requests
Client access token for mobile or web client-side requests
If querying a Page-Scoped User ID:
Page
Endpoint
Upload the picture to an existing album (or create a new one) using the Graph API. Will look something like this:
$args = array('message' => 'Caption');
$args['image'] = '#' . realpath("the_image.png");
try {
$data = $facebook->api('/'.$album_uid.'/photos', 'post', $args);
}
catch(Exception $e) {
print "<pre>";
print_r($e);
print "</pre>";
}
Then get the uploaded image via the Graph API and redirect to the image's link, add &makeprofile=1 to the querystring. The user will now be redirected to the profile image cropping page:
try {
$pictue = $facebook->api('/'.$data['id']);
header("Location: ".$pictue['link']."&makeprofile=1");
}
catch(Exception $e) {
print "<pre>";
print_r($e);
print "</pre>";
}

Related

Is there any way facebook page access token of by page id?

Is there any way I can get access token of any page by page id, I should be able to post on page behalf of admin?
I'm guessing you don't want to be admin of your clients' pages:
You could create a page so that your clients login to Facebook and
grant permissions to your app.
Then you can get the page access token and save it in your DB.
Finally use that access token to post directly to each page as
admin without being you the actual admin.
Quoting Facebook documentation:
To obtain a page access token you need to start by obtaining a user
access token and asking for the manage_pages permission. Once you have
the user access token you then get the page access token via the Graph
API.
To get user access token (supposing you are logged in to fbk and have granted permissions to your App):
$user = $facebook->getUser();
if(!$user) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,manage_pages',
'fbconnect' => 1,
'redirect_uri' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
}
Don't forget get to a time extended access token
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
With that token you can get the page token via the API:
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
$accounts will be an associative array with all the info of the pages you admin (including the tokens for each page). To get the token of an specific page knowing its ID:
$accounts = $accounts['data'];
foreach($accounts as $account){
if( $account['id'] == $pagId ){
//$pagId would be the ID of the page you want to use
//This is the token of the page with the ID $pagId
$page_access_token = $account['access_token'],
}
}

How do I integrate Facebook SDK login with cakephp 2.x?

There seems to be very few to no up to date resources on integration of Facebook login with the cakephp Auth component online. I have found the following resources:
Old Bakery Article using cakephp 1.3? and an older version of Facebook SDK
Cakephp Plugin by webtechnick that seems to be in development
Other than this I found no definitive resources. I wanted the integration to be as flexible (without the use of a magic plugin) as possible. So after much research I finally baked a decent solution which I am sharing here today. Please contribute as I am rather new to cake.
Integration of Cakephp 2.x Auth with Facebook Auth for seamless user authentication
To start off you should read up on the fantastic cakePHP Auth Component and follow the Simple Authentication and Authorization Application tutorial from the cakephp book 2.x (Assuming you have also followed the first two tutorials from the series. After you are done, you should have managed to build a simple cakePHP application with user authentication and authorization.
Next you should download the facebook SDK and obtain an App ID from facebook.
First we will copy the Facebook sdk in to App/Vendors. Then we will import and initialize it in the AppController beforeFilter method.
//app/Controller/AppController.php
public function beforeFilter() {
App::import('Vendor', 'facebook-php-sdk-master/src/facebook');
$this->Facebook = new Facebook(array(
'appId' => 'App_ID_of_facebook',
'secret' => 'App_Secret'
));
$this->Auth->allow('index', 'view');
}
We are initializing the Facebook SDK in AppController so that we will have access to it through out the application. Next we will generate the Facebook login URL using the SDK and pass it to the view. I normally do this in the beforeRender method.
Note: The above configuration details (appId & secret) should preferably be saved in App/Config/facebook.php. You should then use cake Configure.
//app/Controller/AppController.php
public function beforeRender() {
$this->set('fb_login_url', $this->Facebook->getLoginUrl(array('redirect_uri' => Router::url(array('controller' => 'users', 'action' => 'login'), true))));
$this->set('user', $this->Auth->user());
}
We will update our layout so that we can display this link to facebook login for all users who have not logged in. Notice how we have set redirect_uri to our applications User/login action. This is so that once facebook has authenticated a user, we can log him in using cake::Auth as well. There are various benefits to this, including the solution for this question.
<!-- App/Views/Layouts/default.ctp just after <div id="content"> -->
<?php
if($user) echo 'Welcome ' . $user['username'];
else {
echo $this->Html->link('Facebook Login', $fb_login_url) . ' | ';
echo $this->Html->link('Logout', array('controller' => 'user', 'action' => 'logout'));
?>
When the user clicks the login link, facebook SDK will login the user and redirect them to our app Users/login. We will update this action for handling this:
// App/Controller/UsersController.php
// Handles login attempts from both facebook SDK and local
public function login()
{
// If it is a post request we can assume this is a local login request
if ($this->request->isPost()){
if ($this->Auth->login()){
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalid Username or password. Try again.'));
}
}
// When facebook login is used, facebook always returns $_GET['code'].
elseif($this->request->query('code')){
// User login successful
$fb_user = $this->Facebook->getUser(); # Returns facebook user_id
if ($fb_user){
$fb_user = $this->Facebook->api('/me'); # Returns user information
// We will varify if a local user exists first
$local_user = $this->User->find('first', array(
'conditions' => array('username' => $fb_user['email'])
));
// If exists, we will log them in
if ($local_user){
$this->Auth->login($local_user['User']); # Manual Login
$this->redirect($this->Auth->redirectUrl());
}
// Otherwise we ll add a new user (Registration)
else {
$data['User'] = array(
'username' => $fb_user['email'], # Normally Unique
'password' => AuthComponent::password(uniqid(md5(mt_rand()))), # Set random password
'role' => 'author'
);
// You should change this part to include data validation
$this->User->save($data, array('validate' => false));
// After registration we will redirect them back here so they will be logged in
$this->redirect(Router::url('/users/login?code=true', true));
}
}
else{
// User login failed..
}
}
}
And we are done! Most of the heavy lifting is done by this action as you can see. You should preferably move some of the above code in to UserModel. So here's a summary of what is going on.
At first we check if the login request is send from the login form of our application # Users/login. If it is, then we simply log the user in. Otherwise we check if the user exists in our database and if he does log him in or create a new user, and then log him in.
Be careful to verify the user here with more than their email, like their facebook_id. Otherwise there is a chance the user could change their facebook email and hijack another user of your application.
Happy Coding!

Facebook API - App using Oauth to update status of page

I have built an app using the PHP Facebook SDK. It allows users to authenticate my app with facebook OAth so that they can update their status' via my App. This works great, however a lot of my users have business pages and they want to update the status on their business page not their main personal feed. How is this possible? Below is what I have so far.
if ($status != ''){
try {
$parameters = array(
'message' => "$status"/*,
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']*/
);
//add the access token to it
$parameters['access_token'] = $access_token;
//build and call our Graph API request
$newpost = $facebook->api(
'/me/feed',
'POST',
$parameters
);
$success['status'] = "$xml->status";
$xml2 = new XMLGenerator($success, 'facebook','status');
$returnData = $xml2->output;
$returnData = APIResponse::successResponse('200', "$xml->status");
} catch (Exception $e) {
$returnData = APIResponse::errorResponse('400', 'Facebook Error: '.$e);
}
I assume I would have to change '/me/feed'? but to what? What is they have multiple pages how would my app know which page to post to?
Any help with this would be much appreciated.
You can substitute me with the PAGE_ID to post to a page e.g., /013857894/feed. Make sure that you have completed the OAuth process with the manage_pages and publish_stream permissions. You can learn more at the link below:
https://developers.facebook.com/docs/reference/api/page/#statuses
If the user has multiple Pages then you will first need to give them some way of selecting which page they want to post to. You can find out which Facebook Pages a given user is the administrator of by calling /me/accounts for that user. You can find out more about this approach in the Connections section of this page:
https://developers.facebook.com/docs/reference/api/user/

Posting photo to user's photos offlne using facebook php api

To post a photo to logged in user's photos these are the api function parameters:
$result = $facebook->api('/me/photos/', 'post', $attachment);
I would like to post a photo in offline mode using this:
$result = $facebook->api('/'.$user_id.'/photos/', 'post', $attachment);
But this does not work, because I think user_id is read as a album id.
What is the proper url for posting to user's photos when I have a user id?
Where can I find the list of all these "url"s for different graph actions?
Note:User has granted publish and offline permissions to the app.
As long as the token is active you can use me so $result = $facebook->api('/me/photos/', 'post', $attachment); should still work back when offline_access was possible. Even now with 2 month tokens you can use me, again as long as the access token is valid.

Don't know how to get user data after oAuth Dialog

i'm developing a FB app.
The app is authenticating within a canvas page, redirect to OAuth Dialog upon page load
if(!isset($data['user_id']) && $data['page']['liked']){ ?>
<script>
var oauth_url = 'https://www.facebook.com/dialog/oauth/';
oauth_url += '?client_id=XXXX';
oauth_url += '&redirect_uri=' + encodeURIComponent('https://apps.facebook.com/YYYY/');
window.top.location = oauth_url;
</script>
<?php
}
When the user authenticate i just need to read the Name of the User, but i can't find that info into the signed_request.
What am i doing wrong?
You need to do the following steps:
Decode the signed request as mentioned here.
Extract the access token.
Make a new request with the extracted access token to retrieve the user's name.