Post a feed on facebook after a form on my website - php

I have a news form on my website. After creating this news message I want to publish it on Facebook. I tried alot of things, but nothing was working. Here is my class:
<?php
class Facebook {
const FACEBOOK_APP_ID = 'MY_APP_ID';
const FACEBOOK_APP_SECRET = 'MY_APP_SECRET';
const FACEBOOK_ACCESS_TOKEN_URI = 'https://graph.facebook.com/oauth/access_token';
const FACEBOOK_FEED_URI = 'https://graph.facebook.com/app/feed';
private function getAccessToken() {
$params = array(
'client_id' => self::FACEBOOK_APP_ID,
'client_secret' => self::FACEBOOK_APP_SECRET,
'grant_type' => 'client_credentials',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_ACCESS_TOKEN_URI);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$data = curl_exec($ch);
curl_close($ch);
return substr($data, strpos($data, '=') + 1);
}
public function sendFeed() {
$params = array(
'access_token' => $this->getAccessToken(),
'message' => $message,
'name' => $name,
'link' => $url,
'description' => $description,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_FEED_URI);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close ($ch);
return $data;
}
}
If I call the method sendFeed() it returns the following:
{"id":"404322099626551_404397542952340"}
I think the submit was successfull, but when I visit my page on facebook, there is no new feed. What am I doing wrong? I searched the complete day and couldn't get it to work. I thank you for your help.

What you are doing here is posting it on your user's feed. You are using a user access token. What you want to use is a page access token.
You'll need the manage_pages permission to perform tasks on behalf of your page.
In addition you should consider using the official PHP SDK, it'll make accessing Facebook's API much easier and improve readability.

Related

Twitch API - can't get auth token using PHP

Hello stackoverflow members.
I'm not a person who likes to ask for a help but in this case it's IMO the only way to solve my problem. Google didn't help me much.
So. My problem:
I want to get some data using Twitch API. Sounds easy? I wish it was. Below I'm posting my actual code (it's small but it was modified various of times and now it look like...):
$user = json_decode(file_get_contents('https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=MY_CORRECT_CLIENT_ID&redirect_uri=http://localhost/php/twitch.php&scope=user_read'), true);
print_r($user); // returns nothing
$token = $user['access_token'];
print_r($token); // same as above
$ch = curl_init();
// some stupid curls
curl_setopt($ch, CURLOPT_URL, 'https://api.twitch.tv/kraken/streams/followed');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Authorization: OAuth '.$token );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$retval = curl_exec($ch);
curl_close($ch);
$result = json_decode($retval, true);
It returns... Nothing. So I used ready solution from discussions.twitch. (I wish I could write the name of the author of this code but I'm too tired to search it again. Either way thanks!):
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
$response = json_decode($data, true);
//var_dump($response);
$access_token = $response["access_token"];
echo $access_token;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$returnobj = curl_exec($ch);
curl_close($ch);
return $returnobj;
}
$testobj = json_decode(get_data("https://api.twitch.tv/kraken/user?oauth_token=".$access_token."&client_id=".$fields['client_id']));
echo "<br>Data: ";
print_r($testobj);
This code above is a bit better. Only a bit. It returns Error 401. Why? Because it can't get auth token. Well, it's something but not what I wanted to get. What should I do now? Maybe it's fault of localhost address?
FAQ(?):
Yes, I'm using correct data from my Twitch application settings page.
Yes, I'm confused
You're making two calls to the Twitch API, and you need to debug them independently.
For now, just skip the second call. Focus on the one where you grab your access token.
Try this:
// to start, just use the code you've already got:
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
// Now, here we believe the first error comes into play, so let's check it out
print_r($data); // confirm that this is not what we want
$info = curl_getinfo($ch); // let's get some details about that last request
// print it out and see what we get
echo '<pre>';
print_r($info);
echo '</pre>';
... that should give you a starting point to figure out what's going on. If you see an auth token, then you're not accessing it in the right way. If you don't, the info will give you some information about why.
I don't know what redirect_uri is (can you link to docs that explain it?) so I can't know if the localhost reference is a problem there.

Instagram POST "like" in PHP isn't working any more?

Today I tried to post a like via PHP (Curl) without luck. The output is that a token is required but I used a working token. I tried the same token with JS and it works.
Did Instagram changed some things bout PHP?
Here is my code:
<?php
$media_id = '615839918291043487_528338984';
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes?";
$access_token_parameters = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba',
'action' => 'like'
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_GET,true);
curl_setopt($curl,CURLOPT_GETFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($curl);
?>
Output.:
{"meta":{"error_type":"OAuthParameterException","code":400,"error_message":"Missing client_id or access_token URL parameter."}}
I tried it on several server, with several proxies, several client and token. Hopefully you know what's going on.
To add a like to a photo you need to do it via POST. The following is an modified version of your code to do this.
<?php
$url = "https://api.instagram.com/v1/media/615839918291043487_528338984/likes";
$fields = array(
'access_token' => '191573449.9e262d9.ff708911edcd4f809ca31dd76d08c0ba'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>

Post to page via Facebook API

I'm the admin of FB app and FB page (but this page on a separate account). How do I can post something to this page's wall via this FB app using FB API and PHP (in order to be able to do it with CRON)? Is that possible? Thank you in advance for your answers!
Yes it is possible.
First of all, to post on a page on its behalf is done using the page access token.
Get a normal token from your app (may be using Graph API Explorer directly by selecting your app from top-right drop down menu) with the permission: manage_pages, then follow the steps I've mentioned here: https://stackoverflow.com/a/18322405/1343690 - this will get you a never-expiring page access token.
Save it somewhere and use with your cron-job while posting. Code for posting-
$url = 'https://graph.facebook.com/{page-id}/feed';
$attachment = array(
'access_token' => $page_access_token,
'message' => '{your-message}'
);
$result = PostUsingCurl($url, $attachment);
$result = json_decode($result, TRUE);
if( isset($result['error']) ) {
echo "Error: ".$result['error']['message']."<br/>";
}
else{
echo "Feed posted successfully!<br/>";
}
function PostUsingCurl($url, $attachment)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close ($ch);
return $result;
}
I use this personally. Though you will need to already have an access_token generated. If you do not, you could use Facebook's Graph Explorer tool to grant your account the appropriate permissions.
$attachment = array(
"access_token" => $fb_token,
"link" => "$postLink",
"name" => "$postName",
"description" => "$postDescription",
"message" => "$postMessage",
"fb:explicitly_shared" => true
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://graph.facebook.com/'.$fb_page_id.'/feed');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);
Hope this helps out!
Add Api to your page
<script id="facebook-jssdk" src="//connect.facebook.net/en_US/all.js#xfbml=1"></script>`
click function to call fb page
$('#facebook').click(function(){
FB.init({
appId: 12345, // your app ID
status: true,
cookie: true
});
FB.ui({
method: 'feed',
name: "post name",
link: "http://postlink.com,
//picture: "http:/imageurl.com,
description: "this is the body of the text"
});
})

Instagram authenticaton for self feed?

I'm trying to get photos from my Instagram-Feed but everytime Il have to login in my Authentication-Popup, although i use my access token from DB
//FIRST TIME
$array = array(
'client_id'=>'XXX',
'client_secret' => 'XXX',
'grant_type' => 'authorization_code',
'redirect_uri' => REDIRECT_URL,
'code' => $_GET['code']
);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$access_token = $res['access_token'];
//SAVE ACCESS_TOKEN INTO DB
//NEXT TIME
$url = 'https://api.instagram.com/v1/users/self/feed?access_token='.$db['access_token'].'&client_id='.$array['client_id'].'&client_secret='.$array['client_secret'];
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
What am I doing wrong?
Sorry, there was a mistake in the lines above this.
I requested the code every time and this redirect shows me the login form.
Before:
if(!isset($_GET['code'])) {
header('location: https://api.instagram.com/oauth/authorize/?client_id=xxx&redirect_uri='.REDIRECT_URL.'&response_type=code');
}else{
$url = 'https://api.instagram.com/oauth/access_token/';
// ...
After:
if(!isset($_GET['code']) && !isset($access_token) ) {
header('location: https://api.instagram.com/oauth/authorize/?client_id=xxx&redirect_uri='.REDIRECT_URL.'&response_type=code');
}else{
$url = 'https://api.instagram.com/oauth/access_token/';
// ...
Now it works fine.

Uploading a picture to facebook

I am trying to upload a image to a gallery on a facebook fan page, here is my code thus far,
$ch = curl_init();
$data = array('type' => 'client_cred', 'client_id' => 'app_id','client_secret'=>'secret_key',' redirect_uri'=>'http://apps.facebook.com/my-application/'); // your connect url here
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$rs = curl_exec($ch);
curl_close($ch);
$ch = curl_init();
$data = explode("=",$rs);
$token = $data[1];
$album_id = '1234';
$file= 'http://my.website.com/my-application/sketch.jpg';
$data = array(basename($file) => "#".realpath($file),
//filename, where $row['file_location'] is a file hosted on my server
"caption" => "test",
"aid" => $album_id, //valid aid, as demonstrated above
"access_token" => $token
);
$ch2 = curl_init();
$url = "https://graph.facebook.com/".$album_id."/photos";
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_HEADER, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch2, CURLOPT_POST, true);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
$op = curl_exec($ch2);
When I echo $token, I seem to be getting the token, but when I run the script, I get this error, {"error":{"type":"OAuthAccessTokenException","message":"An access token is required to request this resource."} , I have NO idea why it is doing this!
Basically what I am doing in that code is getting the access token with curl, and then, uploading the photo to my album also via curl, but I keep getting that error!
Any help would be appreciated, thank you!
Ok, got it working, here is the code, assuming that you have a valid session going.
$token = $session['access_token'];
//upload photo
$file= 'photo.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
This will upload the specified image to the session holders gallery, it will create a album if there is not one present, also you can access the token via the session array as demonstrated above.
Hope this helps someone out.
Probably your application doesn't have needed permissions.
To request permissions via OAuth, use
the scope argument in your
authorization request, and include a
comma separated list of all the
permissions you want to request.
http://developers.facebook.com/docs/authentication/permissions

Categories