facebook publish stream - php

i have problem... I did follow this site... Im not good at facebook API.. sorry im really noobs with API..
my code:
<?php
define('FB_APIKEY', '***************************');
define('FB_SECRET', '***************************');
define('FB_SESSION', '***************************');
require_once 'facebook-platform/php/facebook.php';
echo "post on wall";
echo "<br/>";
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
$message = 'testasdfsadf';
$attachment = array(
'name' => $_POST["name"],
'href' => $_POST["href"],
'description' => $_POST["description"],
'media' => array(array('type' => 'image',
'src' => $_POST["src"],
'href' => $_POST["href"])));
$action_links = array( array('text' => 'TITLE', 'href' => 'http://www.mysite.com'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
$target_id = "2410160********";
$session_key = FB_SESSION;
if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id)) {
echo "Added on FB Wall";
}
} catch(Exception $e) {
echo $e . "<br />";
}
?>
I got error:
post on wall
exception 'FacebookRestClientException' with message 'The user hasn't authorized the application to perform this action' in /Users/*****/Sites/FacebookTEST/facebook-platform/php/facebookapi_php5_restlib.php:3025 Stack trace: #0 /Users/******/Sites/FacebookTEST/facebook-platform/php/facebookapi_php5_restlib.php(916): FacebookRestClient->call_method('facebook.stream...', Array) #1 /Users/******/Sites/FacebookTEST/index.php(46): FacebookRestClient->stream_publish('testasdfsadf', '{"name":null,"h...', '[{"text":"TITLE...', NULL, '2410160********') #2 {main}

I found answer:
here solution:
http://www.facebook.com/connect/prompt_permissions.php?api_key=YOUR_API_KEY&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=page&ext_perm=publish_stream,offline_access&enable_profile_selector=1&profile_selector_ids=ID_OF_YOUR_PAGE
Insert your API Key and Page ID in BOLD text..

Related

How to use the Facebook API per Page rather than as one app

I'm building an app that populates the database with Facebook posts, based on People that are in the database with a facebook page ID. If a facebook page ID is found it pulls in their posts, and saves the posts that use a particular hashtag to the database.
My problem is, the Facebook API keeps timing out, and i've only got 4 or 5 people listed at the moment. I see that you can get 250 requests per user, but i'm not sure i'm using the API in the correct way to get the posts per page.
Do I have to have the person login and personally give approval to do it this way? That doesn't really work for what i'm trying to do.
I've been using the PHP SDK found on Github, below is my code. I've been following it using the Graph Explorer, but one thing i'm not sure on is how to generate a token per page.
I'm currently using a manual token because i've no idea how to generate them per page, i've tried looking at the docs for both the Git PHP SDK, and also the Facebook API - and it's just not going in my brain, so i'm hoping somebody here might be able to spell it out to me a little better.
Thankyou for your help in advance, i'm a total newb to the Facebook API.
$apitoken = 'EAAF4azHPHh0BABSb7ZCPVv2U4pbBsZAfOMjA0tiTcKJoKKIsgfe0ZBZBf8ZAo5lZCHVh51WQzd1lvdOreA8Q4vU9F3ZCP9B1si1NWKZA7tiXxX1V06hNmQhT2tTZA8N27kinhiUDG0gDbYqLLZBZBRkGlAGuGdNZC3hdI6yJXLqd8QoPGWoi2LiLVmlqex2znHlbuqPzx0aq7YCVBQZDZD';
if( have_rows('social_networks') ):
while( have_rows('social_networks') ): the_row();
if( have_rows('facebook_group') ):
while( have_rows('facebook_group') ): the_row();
if(get_sub_field('facebook_username')){
require_once __DIR__ . '/vendor/autoload.php'; // change path as needed
require_once 'src/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '413876769201693',
'app_secret' => '1517da72a5c8ccaf5524d95a02d8481a',
'default_graph_version' => 'v3.3',
//'default_access_token' => '{access-token}', // optional
]);
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$username = $facebook_username;
$response = $fb->get("/$username?fields=fan_count,id,name,instagram_business_account,feed", "$apitoken");
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$me = $response->getGraphUser();
//print_r($me);
////////////////////////////////////////////////////////
//////////////////// FACEBOOK///////////////////
//////////////////////////////////////////////////////
$facebook_likes = $me['fan_count'];
$facebook_posts = $me['feed'];
} endwhile; endif; endwhile; endif;
////////////////////////////////////////////////////////
//////////////////// FACEBOOK POSTS ///////////////////
//////////////////////////////////////////////////////
foreach($facebook_posts as $facebook_post){
$facebook_post_id = $facebook_post['id'];
try {
// Get the \Facebook\GraphNodes\GraphUser object for the current user.
// If you provided a 'default_access_token', the '{access-token}' is optional.
$response = $fb->get("/$facebook_post_id?fields=likes.limit(0).summary(true),comments.limit(0).summary(true),shares,reactions.limit(0).summary(true),message", "$apitoken");
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$facebook_post_details = $response->getGraphUser();
$facebook_post_message = $facebook_post_details['message'];
$facebook_post_likes = $facebook_post_details['likes']['summary']['total_count'];
$facebook_post_comments = $facebook_post_details['comments'];
$facebook_post_shares = $facebook_post_details['shares'];
$post_id_fb = get_the_ID();
$args_fb = array(
'post_type' => 'campaigns',
);
$the_query_fb = new WP_Query( $args_fb );
if ( $the_query_fb->have_posts() ) : while ( $the_query_fb->have_posts() ) : $the_query_fb->the_post();
$campaign_id = get_the_ID();
$hashtag_fb = get_field('hashtag');
$post_title_fb = get_the_title(get_the_ID());
if (strpos($facebook_post_message, $hashtag_fb) !== false) {
if (get_page_by_title($facebook_post_message, OBJECT, 'campaign-posts')) {
wp_update_post(array(
'post_title'=> ' '.$facebook_post_message.' :facebook',
'post_type'=>'campaign-posts',
'post_content'=> $facebook_post_message,
'status' => 'published',
'meta_input' => array(
'likes' => $facebook_post_likes,
// 'shares' => $facebook_post_shares,
// 'reactions' => $facebook_post_reactions,
'influencer' => $post_id_fb,
'hashtag' => $hashtag_fb,
'platform'=> 'facebook',
'link' => $facebook_username,
)
));
wp_update_post(array(
'post_title'=> $post_title_fb,
'post_type'=> 'campaigns',
'post_content'=> get_the_content($campaign_id),
'status' => 'published',
'meta_input' => array(
'hashtag' => $hashtag_fb,
)
));
}else{
wp_insert_post(array(
'post_title'=> ' '.$facebook_post_message.' :facebook',
'post_type'=>'campaign-posts',
'post_content'=> $facebook_post_message,
'status' => 'published',
'meta_input' => array(
'likes' => $facebook_post_likes,
// 'shares' => $facebook_post_shares,
// 'reactions' => $facebook_post_reactions,
'influencer' => $post_id_fb,
'hashtag' => $hashtag_fb,
'platform'=> 'facebook',
'link' => $facebook_username,
)
));
wp_update_post(array(
'post_title'=> $post_title_fb,
'post_type'=> 'campaigns',
'post_content'=> get_the_content($campaign_id),
'status' => 'published',
'meta_input' => array(
'hashtag' => $hashtag_fb,
)
));
}
}
endwhile;
endif;
}

Invalid parameter Facebook video ad creative in Facebook Marketing API

I am getting the same error while creating Ad Creative via Facebook Marketing API. I followed their guide but doesn't work. Facebook video ad creative reference
$config = Config::get('facebook');
$data['account_id'] = 'act_'.$config['ad_account_id'];
$data['page_id'] = $config['page_id'];
// Init facebook
$api = Api::init($config['app_id'], $config['app_secret'], $config['access_token']);
// Create product catalog
$product_catalog = new ProductCatalog(null, $config['business_id']);
$product_catalog->setData(array(
ProductCatalogFields::NAME => "Catalog",
));
$product_catalog->create();
$product_catalog_id = $product_catalog->id;
// Setup Feed
$product_feed = new ProductFeed(null, $product_catalog_id);
$product_feed->setData(array(
ProductFeedFields::NAME => 'Campaign Feed',
ProductFeedFields::SCHEDULE => array(
ProductFeedScheduleFields::INTERVAL => 'DAILY',
ProductFeedScheduleFields::URL => 'http://example.com/facebook/dpa_product_catalog_sample_feed.csv',
ProductFeedScheduleFields::HOUR => 22,
),
));
$product_feed = $product_feed->create();
// Create Product Set
$product_set = new ProductSet(null, $product_catalog_id);
$product_set->setData(array(
ProductFeedFields::NAME => 'All Product',
));
$product_set->create();
$data['product_set_id'] = $product_set->id;
$video = new Advideo(null, $data['account_id']);
$video->{AdVideoFields::SOURCE} = public_path().'/facebook/video-demo.mp4';
$video->create();
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_URL => 'http://example.com/facebook/resize-image.jpg',
AdCreativeVideoDataFields::VIDEO_ID => $video->id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => $data['page_id'],
),
),
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $data['page_id'],
AdCreativeObjectStorySpecFields::VIDEO_DATA => $video_data,
));
Above these code working and return response but when I call ad creative, the API return "Invalid parameter"
$creative = new AdCreative(null, $data['account_id']);
$creative->setData(array(
AdCreativeFields::NAME => 'Video Ad Template Creative Sample',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
AdCreativeFields::PRODUCT_SET_ID => $data['product_set_id'],
));
$creative->create();
Might be your issue is in creating AdCreativeVideoData.
search for line
AdCreativeVideoDataFields::IMAGE_URL => public_path().'/facebook/resize-image.jpg',
Here IMAGE_URL requires url path like http://example.com/myimage.jpg. You are giving directory path that might cause problem.
If your image is not directly accessible from URL then you should create IMAGE_HASH. For this see below.
try {
$image = new AdImage(null, $data['account_id']);
$image->{AdImageFields::FILENAME} = public_path().'/facebook/resize-image.jpg';
$image->create();
// Image_hash = $image->hash
} catch (Exception $e) {
echo 'Error message: ' . $e->getMessage() . "\n" . "<br/>";
echo 'Error Code: ' . $e->getCode() . "<br/>";
}
And replace IMAGE_URL to IMAGE_HASH in your AdCreativeVideoData like this
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_HASH => $image->hash,
AdCreativeVideoDataFields::VIDEO_ID => $video->id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => $data['page_id'],
),
),
));

Error "Requires upload file thrown in" from Facebook Graph API

I'm trying to make a script to automatically post a picture to my three fan pages.
Here is the script:
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'fileUpload' => true,
));
if($_GET["postType"] == "picture"){$type = "picture";}
else {$type = "link";}
// Download the picture, if $type == picture.
if($type == "picture")
{
$tempFileName = $_SERVER['DOCUMENT_ROOT'].'/TemporaryFiles/';
$tempFileName .= uniqid().'_'.basename($_GET["pictureUrl"]);
// Check if content retrieval is successful :D
if($imgContent = #file_get_contents($_GET["pictureUrl"]))
{
#file_put_contents($tempFileName,$imgContent);
}
}
foreach($pageIDs as $index=>$item)
{
$fbconfig['pageid'] = $item;
$facebook->setFileUploadSupport(true);
if($type == "picture")
{
$args = array(
'access_token' => $pageAccessTokens[$index],
'message' => $_GET["message"],
'source' => '#' . realpath($tempFileName),
);
$post_id = $facebook->api("/" . $albumIDs[$index] . "/photos","post",$args); // Post made :)
}
else if($type == "link")
{
$args = array(
'access_token' => $pageAccessTokens[$index],
'message' => $_GET["message"],
'link' => $_GET["linkUrl"],
'picture' => "",
);
$post_id = $facebook->api("/$pageid/feed","post",$args); // Post made :)
}
}
if($type == "picture")
{
unlink($tempFileName);
}
It's throwing out the following error:
Uncaught OAuthException: (#324) Requires upload file thrown in
I've tried to debug it and have no clue what's wrong with it. If anyone could help, would be grateful.
You need to add photo_upload to your requested scopes to upload images.
array('scope' => 'user_status,publish_stream,user_photos','photo_upload')
put this in your code after the $ facebook-> api ('/ me');
$this->facebook->setFileUploadSupport(true);

Upload image from facebook app

I'm trying to upload image from a Facebook app. I get the following error: Fatal error: Uncaught CurlException: 26: failed creating formpost data thrown in /storage/content/00/103300/gjutveckling.se/public_html/fb/src/base_facebook.php on line 886
This is my code. The strange thing is that i got it to work, but then all if the sudden it stopped working. Can this be a SSL related problem, I just got a new one? Any suggestions must appreciated!
<?php
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'fileUpload' => true,
'cookie' => true,));
$facebook->setFileUploadSupport(true);
$FILE_PATH = 'imdage_' . $user_id . '.jpg';
$args = array('message' => 'message');
$args['image'] = '#' . realpath($FILE_PATH);
$data = $facebook->api('/me/photos', 'post', $args);
?>
I tried this aswell, it doesn't give me an error, but no photo is uploaded.
<?php
function upload_to_facebook($image_data, $access_token)
{
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
$facebook->setFileUploadSupport(true);
$albums = $facebook->api('/me/albums', 'get', array('access_token' => $access_token));
foreach ($albums[data] as $album)
{
if ($album['name'] == $image_data['album_name'])
{
$album_id = $album['id'];
}
}
if (!$album_id)
{
//Create an album
$album_details = array(
'message' => 'Album by FB APP',
'access_token' => $access_token,
'name' => $image_data['album_name']
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
//Get album ID of the album you’ve just created
$album_id = $create_album['id'];
}
//Upload a photo to album of ID…
$photo_details = array(
'message' => 'test image',
'access_token' => $access_token,
);
$photo_details['skrivreglerny.png'] = '#' . realpath($image_data['file']);
$upload_photo = $facebook->api('/'.$album_id.'/photos', 'post', $photo_details);
return $upload_photo;
}
?>
Try this please
$photo_details = array(
'message' => 'message',
'access_token' => 'USER ACCESS TOKEN',
);
$photo_details['image'] = '#'.realpath($image_data['file']);
$upload_photo = $facebook->api(('/me/photos', 'post', $photo_details);
see this link
http://pramodsivadas.co.in/2011/11/upload-an-image-to-a-facebook-album-facebook-php-sdk/

How to add profile image to event using the new php graph api

Using the php graph api I want to add picture to an event. So I m looking for some examples for the new graph api !
I'm sorry if the question is a bit unclear. Creating an event facebook use standard pictures of 31
calendar icon of facebook
http://i.stack.imgur.com/w7tMp.png in monocolor and color
I ( and many other person ) want to replace this picture using php as you can do it via the facebook page.
All descriptions in the internet fail.
I use the following code
$name= $parameter['betreff'];
$beschreibung=$parameter['thema'];
start_time = $parameter['anfangsdatum'] . " " . $parameter['anfangszeit'];
$ort="" . $parameter['ort'];
$picture='http://www.tvwehen.de/facebook/facebook_plan_event/news.png';
$privacy="CLOSED";
$event_param = array(
'access_token' => $access_token,
'page_id' =>$fanPageId,
'name' => $name,
'start_time' => $start_time,
'description' => $beschreibung,
'location' => $ort,
'pic_big' => $picture,
'pic_small' => $picture,
'logo.png' => $picture,
'privacy' => $privacy
);
$event_id = $facebook->api($fanPageId . "/events", "POST", $event_param);
The event is created on the fanpage but without any picture ! Why ?
Your question is a bit unclear, but assuming I've understood you correctly, you simply want a users profile picture? That can be found here:
http://graph.facebook.com/username/picture
So mine would be at http://graph.facebook.com/filip.soderholm/picture
You may also use the userId instead of the username if you have that.
You can get help from this address: https://gist.github.com/1178154
<?php
/**
* Implementation of hook_nodeapi
*/
function hps_the_hook_nodeapi (&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($node->type == 'event') {
if ($op == 'insert') {
dpm($node);
//require_once(drupal_get_path('module', 'hps_the_hook') . '/lib/facebook-php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => '193560340711521',
'secret' => 'secret',
'fileUpload' => true,
));
$page_id = "161330440592966";
$location = $node->field_location[0]['value'];
$from_date = $node->field_date[0]['value'];
$to_date = $node->field_date[0]['value2'];
$image_path = $node->field_image[0]['filepath'];
$event_param = array(
"access_token" => 'access_token',
"name" => $node->title,
"start_time" => strtotime($from_date),
"end_time" => strtotime($to_date),
"location" => $location,
"page_id" => $page_id,
"picture" => "#".realpath($image_path),
"source" => "#".realpath($image_path),
);
$facebook->setFileUploadSupport(true);
try {
dpm($event_param);
$event_id = $facebook->api("/161330440592966/events", "POST", $event_param);
dpm($event_id);
}
catch (Exception $ex) {
dpm($ex);
}
}
}
}
?>

Categories