So I wanted to do the following: a php script should upload a picture with a title to a facebook page.
I then googled around a bit and found this: Simple example to post to a Facebook fan page via PHP?
Everything works fine, but sadly the result is not what I wanted. Instead of a "full" image, I only get a cripple: http://i.imgur.com/2qINX.jpg
Can you help me out? The script will need offline access and I've already an app. I will only need it to upload pictures along with a title, nothing more.
Before this I was uploading pictures through the Email provided by Facebook for mobile users, but that's not satisfying anymore. I mean, it can't be that hard. But if I don't figure this out, I will rent a virtual windows server and run a script that loggs into Facebook and posts the image.
You can upload a picture to your page using-
$image['file'] = PATH_TO_PICTURE;
$args = array( 'access_token' => PAGE_ACCESS_TOKEN, 'message' => '','no_story' => 0);
$args['image'] = '#' . $image['file'];
$target_url = "https://graph.facebook.com/ALBUM_ID/photos";
$ch = curl_init();
curl_setopt ($ch,CURLOPT_URL,$target_url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_exec($ch);
curl_close ($ch);
PAGE_ACCESS_TOKEN
Get the list of pages/apps-
$facebook->api("/USER_ID/accounts");
Get the pages' access token-
$facebook->api("/PAGE_ID?fields=access_token");
This will load up a picture to a specific gallery:
$newphotodata = array(
'access_token' => $fanPageAccessToken,
'message' => $message,
'no_story' => 1,
'aid' => $albumId,
'image' => '#' . $picturePath);
$uploadedphoto = $facebook->api('/' . $albumId . '/photos/', 'post', $newphotodata);
You need the following permissions too though:
read_stream, manage_pages, publish_stream, photo_upload, user_photos, user_photo_video_tags
I'm not sure whether the user_photos and user_photo_video_tags are actually needed, so try without if you get it working with.
Also, you need the following line before you make the call:
$facebook->setFileUploadSupport(true);
You basically need to do two things first though.
First you need to query the API to get an access token for whatever page you want to post to.
You do this by the following api call:
$fanpages = $facebook->api('me/accounts?access_token='.$accessToken);
You then loop through $fanpages['data'], to find the page you want:
$fanPageAccessToken = $fanPage['access_token']
You then make the call given above, using the appropriate album id.
Now, if you don't know what album id you require, take a look at the following:
$fan_albums = $facebook->api($fanPageId.'/albums/');
This will show all the albums. The key fields at the moment will be ['id'] and ['name'].
Once you have made the post, there will be no evidence of it. So what you should then do is post a link to the photo on the links feed. If you need help with that then ask and I will provide the info.
Alternatively, check out these two articles I wrote a while ago, which cover the same thing.
http://facebookanswers.co.uk/?p=262
http://facebookanswers.co.uk/?p=322
Related
I am trying to show Instagram content from a user (mines) on a website. My client-side page would make an AJAX request to my server-side script, which in turn, would do the necessary stuff to pull the content from Instagram API (using cUrl) and send back a JSON response.
Sadly, I am little bit confused with the Authentication instructions, particularly Step One: Direct your user to our authorization URL.
In order to get an access_token to work with the API, I need to pass client_id, redirect_uri, and code. I have the client_id and redirect_uri. The problem is the last item, code, which gets found after redirecting from https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code. The redirected page will be REDIRECT-URI?code=CODE which has the CODE to use to make the request to get the access_token.
Is there a way to "automate" this last part ? Or more precisely, is it possible to make a request (using cUrl) and then grabbing this CODE
Hopefully, this is clear. Unlike other APIs, Instagram seems to make things difficult. My goal is so that when users come on the page, they will see a gallery of images from my Instagram account. They shouldn't need to log into Instagram or do anything to see these images.
Edit
$clientId = 'XXX';
$clientSecret = 'YYY';
$redirectUri = 'ZZZ';
// step 1: authorize
$url = "https://instagram.com/oauth/authorize/?client_id={$clientId}&redirect_uri={$redirectUri}&response_type=code";
try {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url
));
$data = json_decode(curl_exec($ch), true);
// how to get CODE from response?
curl_close($ch);
} catch(Exception $e) {
echo $e->getMessage();
}
I'm trying to setup a simple app that should:
get the client ID of an artist from its URL
display the two latest tracks
However I'm not that practical with soundcloud and i just know basic php. I started to play with soundcloud but i wasn't able to handle it. A problem i have is that any code i write, it gets
Fatal error: Uncaught exception 'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 302.'
The easiest setup come straight from the documentation and is an example to retrieve the comments from the track id, starting from a give URL.
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('my_client','my_secret');
// a permalink to a track
$track_url = 'https://url_to_a_track';
// resolve track URL into track resource
$track = json_decode($client->get('resolve', array('url' => $track_url), array('CURLOPT_FOLLOWLOCATION', TRUE )));
// now that we have the track id, we can get a list of comments, for example
foreach (json_decode($client->get('tracks/' . $track->id . 'comments')) as $c)
print 'Someone said: ' . $c->body . ' at ' . $c->timestamp . "\n"; ?>
Just added ('CURLOPT_FOLLOWLOCATION', TRUE) because I've read about it around the web... And I always get the fatal error... why?
'How can I use the soundcloud API resolve resource with PHP?'
to use the resolve resource of the soundcloud API with php, following frafor's code, do:
$client->setCurlOptions(array(CURLOPT_FOLLOWLOCATION => 1));
$response = json_decode($client->get('resolve',array('url' => $track_url)));
?>
So first CURLOPT_FOLLOWLOCATION and then the API call, your where almost there! :)
Hope it helps someone!
Cheers,
T
the soundcloud servers have switched to secure and they now use https protocol for API / JSON as well.
My apps were not working any more so these are the other cURL options to get the JSON.
SSL verification must both be set to disable. I got it working only with this.
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
);
Hope it helps.
I've been able to solve it. If the resources are public, then you don't need to authenticate. Here's the code that:
Get user URL from a wordpress custom-field
Retrieve ID from json object
Retrieve the latest 2 tracks and display 2 embedded players
It just need your own Client ID you can get easily by registering on soundcloud developers section, and then substitute it to {Your_ID}
// get user URL from Wordpress custom field
$sc_url = get_post_meta(get_the_id(), 'sc_url', true);
// if $sc_url is not empty, do
if (!empty($sc_url)) {
$unparsed_json = file_get_contents('https://api.soundcloud.com/resolve.json?url='.$sc_url.'&client_id={Your_ID}');
$json_object = json_decode($unparsed_json);
// retrieve the user ID from json_object
$roster_id = $json_object->{'id'};
// get last two tracks from the user and generate embed code for each tracks
$tracks_json = file_get_contents('http://api.soundcloud.com/users/'.$roster_id.'/tracks?client_id={Your_ID}&order=latest&limit=2&format=json');
$tracks = json_decode($tracks_json);
foreach ($tracks as $track){
$trackID = $track->id;
echo '<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F'.$trackID.'"></iframe>';
}}
Hope it can help others :)
I have spent quite some time now trying to establish how, and then the best practise to push some data from my web server to the facebook page created for this purpose.
I have read and understand the process of using access tokens. I have generated an access token for myself, which can be used to post to the page as me ok. I understand this should be used to generate the access token for the page to post as the page which is a ittle more tricky. However, this process involves me logging in and generating an access token which seem inherently bad / inconvenient for an automated process.
For this reason i followed the guides to create an app. I (think I have) linked the app to the page, and thus attempt to push data via the appid and secret from my php code to the page.
When doing this I am presented with this error
{"error":{"message":"(#210) Subject must be a page.","type":"OAuthException","code":210}}
my testing code is this:
$data['picture'] = "http://www.example.com/image.jpg";
$data['link'] = "http://www.example.com/";
$data['message'] = "Your message";
$data['caption'] = "Caption";
$data['description'] = "Description";
$data['access_token'] = $app_token2;
$post_url = 'https://graph.facebook.com/'.$app_id.'/feed';
$url1 = "https://graph.facebook.com/endpoint?key=value&access_token=".$app_id."|". $app_secret ;
echo "<br>$post_url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
//curl_setopt($ch, CURLOPT_URL, $url1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
echo "$return";
I appreciate using the app for server initiated posting using a permanent (ish) secret is the correct way, but I have found very little documentation on how this process is achieved, hence this question.
Your $post_url is pointing to your $app_id variable, the message says it should point to a page, try getting the id of your page from the /me/accounts endpoint of the graph and putting that in there instead. Though I suspect you will need to use a page access_token (also from the /me/accounts endpoint ) to post to your page
Right, I have worked on this for quite some time and found several errors in my code, but have not answered the question fully.
For starters, you do not post to the appid as mentioned above - its just wrong. The code for posting to userid/feed works when using an access token generated from appid + secret using
$url2 = "https://graph.facebook.com/oauth/access_token?client_id=".$app_id."&client_secret=". $app_secret."&grant_type=client_credentials";
this app access token is valid for as long as your app secret is. Also, if I generate a temporary access code for ME via the graph explorer, parse me/accounts manually and use the page token in
$post_url = 'https://graph.facebook.com/'.$page_id.'/feed';
It posts correctlly as the page.
Secondly, all server side call are required to have appsecret_spoof in them which is generated from
$appsecret_proof= hash_hmac('sha256', $app_token2, $app_secret);
now, according to the facebook docs, a http get call to my userid/accounts should yield page access tokens for all pages the user administers (and also presumably the app).
This can also be called directly by using
$url3 = "https://graph.facebook.com/".$page_id."?fields=access_token";
so when a get is made to this address (including app access token & appsecret_spoof) all i get is 'True' ??
Likewise, when the correct call to
$rob1 = "https://graph.facebook.com/".$user_id."/accounts";
I receive an error
{"error":{"message":"(#10) Application does not have permission for this action","type":"OAuthException","code":10}}
OK permission issue then ! Well the documentation says that only manage_pages is required to retrieve the page token from page_id/accounts, so I trawl through lots of pages and find you can do this by calling this url
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope=read_stream
This throws up via facebook gui an accept / deny page for each scope (i ended up adding manage_pages, publish_stream & read_stream to my app) none of which seem to solve the problem !
Right sorted !! FWIW the code above functions correctly, however the way it is setup on facebook leaves a lot to be desired !!!
I began messing with my app and changed its name, type (was an app linked to the page - now isnt) removed perms and also changed the domain name (removed) and all site url details (also removed). this prompted a different error msg which stated the domains did not match. So, I readded just the app domain & site url, saved and all of a sudden my failed code started working !
Having tidied my code up a little I can now see the page access token just fine as I expected. I just wish the facebook guides would cross reference this setup as it is not at all obvious !!!
my working code ended up as thus ($perm_url is used as one time link to allow perms via gui)
$perm_url = "https://www.facebook.com/dialog/oauth?client_id=".$appid."&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope=publish_stream,manage_pages,read_stream,status_update";
echo "<br>Test";
$facebook = new Facebook(array('appId' => $appid , 'secret' => $appsecret ,));
$access_token = $facebook->getAccessToken();
$pageinfo = $facebook->api("/".$page_id."?fields=access_token");
$page_access_token = $pageinfo['access_token'];
echo "<br>Holy Grail = $page_access_token ";
<?php
require "facebook.php";
$facebook = new Facebook(array(
'appId' => '3288##########',
'secret' => 'ca2##################',
));
$user = $facebook->getUser();
I have made the app in the graph api and I have very little knowledge of graph api . I want to make a facebook login page in which user clicked on it and my app will generate the oauth for the user . after that i need the USERNAME, EMAIL,BIRTHDAY,NAME in the fre filled forms
I'm searching for this code from 3 night, but i didn't find the solution! If you have a suggestion, please write to me it! Please, anyway thanks and good day :)
You could use POST request to simulate login. I don't know Facebook's inputs, so you need to look closely into it's HTML, but here is a code for a simple PHP cURL request.
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.facebook.com/login.php',
CURLOPT_USERAGENT => 'Facebook Login',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'username' => 'username',
'password' => 'myfbpass'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
Of course, Facebook has automatic login detection by using those hidden fields for getting the sessions, but using DOM Document, you can easily get those values and emulate it, at least thats how I was able to simulate login for http://z8games.com/
Good luck
Code Credit:
http://codular.com/curl-with-php
Edit:
If you are lazy, you can go ahead and try this page - http://www.daniweb.com/web-development/php/code/290893/facebook-login-with-curl
Temboo makes it simple to implement Facebook OAuth by breaking the process down into two steps:
ÌnitializeOAuth returns the Facebook authorization URL that you need to show your users so that they can grant your app access to their Facebook accounts.
FinalizeOAuth returns the access token you need to programmatically read/write a user's Facebook data.
What's more, you can test these calls from your browser and generate the source code you need in the language of your choice.
Here's a short video that shows you how to do this with Temboo, and you can check out an example and source code here.
(Full disclosure: I work at Temboo, so let me know if you have any questions!)
I was trying to get the feeds of friends' fan pages with a cURL and to post a like via app.
The cURL GET works fine, but when it comes to liking the object (that has for sure likes enabled because it's facebook), all I get is a boolean (and no action).
I had seen on SO that you post a like with
($access_token, "https://graph.facebook.com/$post_id/likes", 'POST')
However, it is not working (it says either that the app has no permissions to do that, or that I need a valid url).
I have tried all possible solutions but nothing seems to work. The profile is mine, the access token too, and I gave publish_stream permissions to my own app.
After having given a try to the SDK PHP Likbrary, I tried a direct cURL post, with the following code:
function likeit($url){
//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $url);
curl_exec($ch);
curl_close($ch);
}
The execution i a puzzle. When it does not return an OAuth Exception it returns boolean and stops there (there is no way for me to "like" the post I want to like). The last attempt (but I've tried them all, even the whole url in some tests) is
foreach ($feeds->data as $feed_data)
$message = $feed_data->message;
$title = $feed_data->name;
$link = $feed_data->link;
$id = $feed_data->id;
$myaccesstoken = "longlastingaccesstokenstring";
$post=likeit($myaccesstoken, "https://graph.facebook.com/$post_id/likes", 'POST');
Does anybody have a suggestion on how to do this? It seems trivial and yet there is no way for me to accomplish it. Thank you so much in advance!
I've found a solution, and thus am posting it here for future reference (hoping it is helpful for anybody with the same problem):
the only problem was that after the new permissions with facebook I needed to re-authorize my app.
After that, it is possible to post a like with the SDK facebook library, normally:
$facebook->api("/$id/likes", 'post', array(
'access_token' => $myaccesstoken));
No need to use cURL directly. Hope this helps someone with the same question.