Facebook Page Tab - App - php

I created a Facebook page, added a new Tab with an application.
Now I want todo these steps:
See if User liked the page // Is Working
Ask for permissions to post a status // Isn't working
Finish.
This is the code which I use:
$permissions = array (
'email',
'user_status',
'publish_stream',
'status_update'
);
public function __construct($app_id, $secret, $perm)
{
$this->facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true
));
$this->perm = $perm;
}
public function checkPermissions()
{
$allPerm = true;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->perm as $value)
{
if(!array_key_exists($value, $permissions['data'][0]) ) {
$allPerm = false;
}
}
return $allPerm;
}
public function RequestPermissions()
{
header( "Location: " . $this->facebook->getLoginUrl($this->GenerateScope()) );
}
public function GenerateScope()
{
$scope = null;
$last_key = array_keys($this->perm);
$last_key = end($last_key);
foreach ($this->perm as $key => $value) {
if ($key == $last_key) {
$scope .= $value;
} else {
$scope .= $value . ',';
}
}
return array("scope" => $scope);
}
So, I check for the Permissions, if not all are set, I want to ask for them.
$this->facebook->getLoginUrl($this->GenerateScope()).
But when i display the link, or redirect to it, nothings (really nothing) happens?

Your tab application is operating within an iframe element on facebook.com. To redirect users to a different URL, you'll have to change the top most frame's location.
This is possible using JavaScript, so all you have to do is get your PHP code to echo out this JavaScript code -
$url = $facebook->getLoginUrl(...your_params...);
echo "<script language=javascript>";
echo "top.location.href ='".$url."';";
echo "</script>";
exit();
That will execute the redirect for your users.

Related

Facebook login php sdk - problem on mobile devices - empty headers [website app]

I have a little problem with my integration with Facebook PHP SDK on my website. On desktop everything works fine. When try to register account using fb-login button on mobile devices despite the successful redirection from the facebook website to my website, it receives an empty response.
I don't know where is the main problem, session, redirects policy, cookie problem?
The problem does not exist when accounts are merged and connected - so login function works on mobile, just creating account and connecting new ids.
I note that everything works fine on the desktop version
my config
Facebook PHP SDK: 5.6.2
Graph API: v14.0
$config = array_merge([
'app_id' => getenv(static::APP_ID_ENV_NAME),
'app_secret' => getenv(static::APP_SECRET_ENV_NAME),
'default_graph_version' => static::DEFAULT_GRAPH_VERSION,
'enable_beta_mode' => false,
'http_client_handler' => null,
'persistent_data_handler' => 'memory',
'pseudo_random_string_generator' => null,
'url_detection_handler' => null,
], $config);
You can see the code implementations below
public function _facebook_account($action = null){
$isLogged = $this->getCustomer()->isAuthenticated();
$fb = FacebookAPIHelper::getInstance()->getAPI($this->getContext());
$redirectUrl = null;
if (!empty($_POST['secret_code']))
{
$code = $_POST['secret_code'];
}
if (!$isLogged) {
if ($action == FacebookAPI::ACTION_LOGIN || $action == FacebookAPI::ACTION_REGISTER){
$redirectUrl = '/customer/login_with_facebook/' . $action;
}
}
else{
if ($action == FacebookAPI::ACTION_MERGE) {
$redirectUrl = '/customer/merge_with_facebook';
}
else {
$this->redirectTo('customer,profile');
}
}
if (!is_null($redirectUrl)) {
$url = $fb->getLoginUrl($this->getRouter()->getHost(null, true) . $redirectUrl, isset($code) ? $code : null);
header("Location: $url");
}
else {
$this->redirectTo('');
}
}
2
try {
$facebookProfileData = FacebookLoginHelper::getFacebookProfileData($this->getContext());
if ($facebookProfileData) {
$customer = FacebookLoginHelper::findOrCreateCustomerByFacebookProfileData($facebookProfileData);
} else {
$this->addMessageForNextRequest('`facebook_login.error_fetch_user_data`');
$this->redirectTo('customer,login');
}
if (is_null($customer)) {
$customer = CustomerBase::getCustomerFromFacebookProfileData($facebookProfileData);
if (Module::moduleInstalled('referer')) {
if ($this->hasCookie(RefererSettings::COOKIE_NAME)) {
$referer = $this->getCookie(RefererSettings::COOKIE_NAME);
$customer->referer = $referer;
}
}
$this->view->customer = $customer;
$this->renderAction('confirm_customer_data.tpl');
}
3
public function _login_with_facebook($action)
{
$customer = null;
$oldCustomer = $this->getCustomer();
$isLogged = $oldCustomer->isAuthenticated();
$facebookLoginNotInstalled = Module::moduleInstalled('facebook_login') == false;
if ($isLogged) {
$this->redirectTo('customer,profile');
return;
}
if ($facebookLoginNotInstalled) {
$this->redirectTo('customer,login');
return;
}
try {
$facebookProfileData = FacebookLoginHelper::getFacebookProfileData($this->getContext());
if ($facebookProfileData) {
$customer = FacebookLoginHelper::findOrCreateCustomerByFacebookProfileData($facebookProfileData);
} else {
$this->addMessageForNextRequest('`facebook_login.error_fetch_user_data`');
$this->redirectTo('customer,login');
}
if (is_null($customer)) {
$customer = CustomerBase::getCustomerFromFacebookProfileData($facebookProfileData);
if (Module::moduleInstalled('referer')) {
if ($this->hasCookie(RefererSettings::COOKIE_NAME)) {
$referer = $this->getCookie(RefererSettings::COOKIE_NAME);
$customer->referer = $referer;
}
}
$this->view->customer = $customer;
$this->renderAction('confirm_customer_data.tpl');

Google Sheets API - Insert a row with PHP

So I created a Spreadsheet class that is a combination of a few solutions I found online for accessing Google Sheets API with PHP. It works.
class Spreadsheet {
private $token;
private $spreadsheet;
private $worksheet;
private $spreadsheetid;
private $worksheetid;
private $client_id = '<client id>';
private $service_account_name = '<service_account>'; // email address
private $key_file_location = 'key.p12'; //key.p12
private $client;
private $service;
public function __construct() {
$this->client = new Google_Client();
$this->client->setApplicationName("Sheets API Testing");
$this->service = new Google_Service_Drive($this->client);
$this->authenticate();
}
public function authenticate()
{
if (isset($_SESSION['service_token'])) {
$this->client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($this->key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$this->service_account_name,
array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds'), $key
);
$this->client->setAssertionCredentials($cred);
if ($this->client->getAuth()->isAccessTokenExpired()) {
$this->client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $this->client->getAccessToken();
// Get access token for spreadsheets API calls
$resultArray = json_decode($_SESSION['service_token']);
$this->token = $resultArray->access_token;
}
public function setSpreadsheet($title) {
$this->spreadsheet = $title;
return $this;
}
public function setSpreadsheetId($id) {
$this->spreadsheetid = $id;
return $this;
}
public function setWorksheet($title) {
$this->worksheet = $title;
return $this;
}
public function insert() {
if (!empty($this->token)) {
$url = $this->getPostUrl();
} else {
echo "Authentication Failed";
}
}
public function add($data) {
if(!empty($this->token)) {
$url = $this->getPostUrl();
if(!empty($url)) {
$columnIDs = $this->getColumnIDs();
if($columnIDs) {
$fields = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
foreach($data as $key => $value) {
$key = $this->formatColumnID($key);
if(in_array($key, $columnIDs)) {
$fields .= "<gsx:$key><![CDATA[$value]]></gsx:$key>";
}
}
$fields .= '</entry>';
$headers = [
"Authorization" => "Bearer $this->token",
'Content-Type' => 'application/atom+xml'
];
$method = 'POST';
$req = new Google_Http_Request($url, $method, $headers, $fields);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
var_dump($results);
}
}
}
}
private function getColumnIDs() {
$url = "https://spreadsheets.google.com/feeds/cells/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full?max-row=1";
$headers = array(
"Authorization" => "Bearer $this->token",
"GData-Version: 3.0"
);
$method = "GET";
$req = new Google_Http_Request($url, $method, $headers);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
if($results[2] == 200) {
$columnIDs = array();
$xml = simplexml_load_string($results[0]);
if($xml->entry) {
$columnSize = sizeof($xml->entry);
for($c = 0; $c < $columnSize; ++$c) {
$columnIDs[] = $this->formatColumnID($xml->entry[$c]->content);
}
}
return $columnIDs;
}
return "";
}
private function getPostUrl() {
if (empty($this->spreadsheetid)){
#find the id based on the spreadsheet name
$url = "https://spreadsheets.google.com/feeds/spreadsheets/private/full?title=" . urlencode($this->spreadsheet);
$method = 'GET';
$headers = ["Authorization" => "Bearer $this->token"];
$req = new Google_Http_Request($url, $method, $headers);
$curl = new Google_IO_Curl($this->client);
$results = $curl->executeRequest($req);
if($results[2] == 200) {
$spreadsheetXml = simplexml_load_string($results[0]);
if($spreadsheetXml->entry) {
$this->spreadsheetid = basename(trim($spreadsheetXml->entry[0]->id));
$url = "https://spreadsheets.google.com/feeds/worksheets/" . $this->spreadsheetid . "/private/full";
if(!empty($this->worksheet)) {
$url .= "?title=" . $this->worksheet;
}
$req = new Google_Http_Request($url, $method, $headers);
$response = $curl->executeRequest($req);
if($response[2] == 200) {
$worksheetXml = simplexml_load_string($response[0]);
if($worksheetXml->entry) {
$this->worksheetid = basename(trim($worksheetXml->entry[0]->id));
}
}
}
}
}
if(!empty($this->spreadsheetid) && !empty($this->worksheetid)) {
return "https://spreadsheets.google.com/feeds/list/" . $this->spreadsheetid . "/" . $this->worksheetid . "/private/full";
}
return "";
}
private function formatColumnID($val) {
return preg_replace("/[^a-zA-Z0-9.-]/", "", strtolower($val));
}
}
I then use this test php file to add rows to to my spreadsheet:
$Spreadsheet = new Spreadsheet();
$Spreadsheet->
setSpreadsheet("test spreadsheet")->
setWorksheet("Sheet1")->
add(array("name" => "Cell 1", "email" => "Cell 2"));
With this I can delete a row / update a row and append a row. However, the MAIN reason I needed this was to INSERT a row. Has anyone figured out a way to do this? Any language is fine although id prefer a php solution.
You can call an Apps Script stand alone script from PHP using an HTTPS GET or POST request. PHP can make a GET or POST request, and Apps Script can obviously insert the row anywhere using SpreadsheetApp service. You'll probably want to use Content Service also inside of the Apps Script code to get a return confirmation back that the code completed.
You might want to use a POST request for better security. So, again, you can use Apps Script as an intermediary between your PHP and your spreadsheet. The doPost() in the Apps Script file will need an event handler, normally assigned to the letter "e":
doPost(e) {
//Get e and retrieve what the code should do
//Insert the row
};
Also, see this answer:
Stackoverflow - Call a custom GAS function from external URL

posting in group on behalf of user using facebook graph API

I am trying to post on behalf of user. I have used tutorial given on this page: http://25labs.com/updated-post-to-multiple-facebook-pages-or-groups-efficiently-v2-0/ .
I could successfully perform authentication but could not post on behalf.
Here is the source code : https://github.com/karimkhanp/fbPostOnBehalf
Testing can be done here: http://ec2-54-186-110-98.us-west-2.compute.amazonaws.com/fb/
Does any one experienced this?
I'm not familiar with the batch process that the tutorial is using but below is a code sample that posts to a Facebook group
<?php
# same this file as
# test.php
include_once "src/facebook.php";
$config = array(
'appId' => "YOURAPPID",
'secret' => "YOURAPPSECRET",
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
class PostToFacebook
{
private $facebook;
private $pages;
public function initialise($config){
$this->name = "Facebook";
// current necessary configs to set
// $config = array(
// 'appId' => FB_APP_ID,
// 'secret' => FB_APP_SECRET,
// 'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
// );
$this->facebook = new Facebook($config);
try{
// if user removes app authorization
$this->hasAccess = $this->has_permissions();
if($this->hasAccess){
$this->groups = $this->getGroupData();
}
}
catch(Exception $err){
}
}
public function postMessageToGroup($message, $groupid){
$messageResponse = array(
'STATUS' => 0
);
$fbMessageObj = array(
"message" => strip_tags($message),
);
try
{
$user_page_post = $this->facebook->api("/$groupid/feed", 'POST', $fbMessageObj);
if($user_page_post && !empty($user_page_post['id'])){
$messageResponse['STATUS'] = 200;
$messageData = array(
'id' => $user_page_post['id'],
'link' => 'http://facebook.com/' . $user_page_post['id'],
);
$messageResponse['data'] = $messageData;
}
else{
$messageResponse['STATUS'] = 302;
}
}
catch(Exception $err){
$messageResponse['STATUS'] = 500;
$messageResponse['data'] = array($err);
}
return $messageResponse;
}
// TODO: should read a template somewhere
function show_login() {
$login_url = $this->facebook->getLoginUrl( array( 'scope' => implode(",",$this->permissions()) ));
return 'Login to Facebook and Grant Necessary Permissions';
}
// TODO: should read a template somewhere
public function toString()
{
if($this->hasAccess){
if($this->groups){
$msg = "";
$msg .= '<select name="group_id"><option value=""></option>';
foreach($this->groups as $group) {
$msg .= '<option value="' .
'' . urlencode($group['id']) .
'">' .
$group['name'] .
'</option>' .
'';
}
$msg .= '</select>';
return $msg;
}
else
return "No Groups";
}
else{
return $this->show_login();
}
}
function getGroupData(){
$raw = $this->facebook->api('/me/groups', 'GET');
$data = array();
if (null != $raw && array_key_exists('data', $raw))
return $raw['data'];
return null;
}
// check if current instance has access to facebook
function has_permissions() {
$user_id = #$this->facebook->getUser();
#print_r($user_id);
if($user_id == null) return false;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->permissions() as $perm){
if( !array_key_exists($perm, $permissions['data'][0]) ) {
return false;
}
}
return true;
}
// permissins needed to post
function permissions(){
return array('manage_pages', 'user_groups');
}
}
$fb = new PostToFacebook();
$fb->initialise($config);
if(!$fb->has_permissions())
{
echo $fb->show_login();
}
else{
?>
<form method="post" action="test.php">
<textarea name='message'></textarea>
<?php echo $fb->toString(); ?>
<input type='submit'>
</form>
<?php
}
if(!empty($_POST)){
$response = $fb->postMessageToGroup($_POST['message'], $_POST['group_id']);
if($response['STATUS'] == 200)
print_r("<a href='" . $response['data']['link'] . "'>" . $response['data']['id'] ."</a>");
else
{
echo "ERROR!";
print_r($response);
}
}
?>

Facebook api PHP: Posting to another users page feed not working

I have been trying to post a message and image on a page feed. I keep getting the error message
(#1) An error occured while creating the share.
This only happens if someone else tries to post. If I, the owner of the page tries to post it is successful.
So my question is: Is it possible to post to another users page feed?
I have done a lot of research into this but I cant seem to find a plausible solution.
Here is the code I am using to post the message:
<?php
class Photo_contest_helper extends Facebook
{
private $_key = '***********';
private $_secret = '***************';
private $_page_id = '387228561388254';
public $fb_login_url;
public $fb_logout_url;
public $image_id;
public function init()
{
$this->connect();
$image_id = $this->save_image();
if( !!$image_id ) {
$this->image_id = $image_id;
$this->push_to_facebook( $image_id );
}
}
public function save_image()
{
$image_id = NULL;
if ( !!$_POST[ "image" ] || !!$_FILES ) {
$image_id = Image_helper::save_one( $_POST[ "image" ] );
}
return $image_id;
}
public function push_to_facebook( $image_id )
{
$access_token = $this->get_page_access_token();
$this->publish_photo( $access_token );
}
public function connect()
{
parent::__Construct( array( 'appId' => $this->_key, 'secret' => $this->_secret ) );
$user = $this->getUser();
if( !$user ) {
$this->fb_login_url = $this->getLoginUrl( array( 'scope' => 'manage_pages,publish_actions,publish_stream,status_update' ) );
}
else {
$this->fb_logout_url = $this->getLogoutUrl( array( 'next' => 'http://stormtest.co.uk/' . DIRECTORY . "home/logout" ) );
}
}
public function get_page_access_token()
{
$accounts = $this->api( '/me/accounts', 'get' );
$access_token = NULL;
foreach ( $accounts[ 'data' ] as $account ) {
if ( $account[ 'id' ] == $this->_page_id ) {
$access_token = $account[ 'access_token' ];
}
}
return $access_token;
}
public function publish_photo( $access_token = "" )
{
$params = array( 'message' => 'Competition entry',
'link' => 'http://stormtest.co.uk/' . DIRECTORY . '_admin/assets/uploads/images/' . $this->get_image(),
'caption' => 'This is my competition entry',
'picture' => 'http://stormtest.co.uk/' . DIRECTORY . '_admin/assets/uploads/images/' . $this->get_image() );
if( !!$access_token ) {
$params[ 'access_token' ] = $access_token;
}
try {
$this->api( '/' . $this->_page_id . '/feed', 'post', $params );
}
catch( FacebookApiException $e ) {
die( print_r( $e ) );
}
}
public function get_image()
{
$image_model = new Image_model();
$image_model->find( $this->image_id );
return $image_model->attributes[ 'imgname' ];
}
}
?>
Thanks in advance.
You should use the JavaScript SDK to share content to the page. Posting to others' walls via the API has been disabled:
FB.ui( {
method: 'feed',
to: '387228561388254',
name: "Facebook API: Tracking Shares using the JavaScript SDK",
link: "https://www.webniraj.com/2013/05/11/facebook-api-tracking-shares-using-the-javascript-sdk/",
picture: "https://stackexchange.com/users/flair/557969.png",
caption: "Tracking Facebook Shares on your website or application is a useful way of seeing how popular your articles are with your readers. In order to tracking Shares, you must used the Facebook JavaScript SDK."
}, callback );
Use the to field in the above code to set the page_id, and change the other attributes accordingly (but don't change method).

$facebook->getUser() returning 0 and showing exception

I am doing login and fetching albums from facebook:
1) Here, first of all the function $facebook->getUser() returning 0
2) If I commented the rest of code i.e. if/else conditions then it going into the catch block and showing exception like :
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
3) I found lots of posts on stackoverflow and google regarding to this and tried almost all but still its not working. Thats why I am sharing the code here.
4) Also I created the new app facebook and tried for it but still problem persist.
Following is my code :
public function facebookapiAction() {
require 'auth/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '3xxxxxxxxxxxxxxxxxxxx7',
'secret' => '6xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5',
'cookie' => true,
));
return $facebook;
}
public function facebookalbumAction() {
$session = new Zend_Session_Namespace('user');
$facebook = $this->facebookapiAction();
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
$albumid = $this->_getParam('albumid');
if ($user <> '0' && $user <> '') {
if ($albumid != "") {
$photos = $this->albumlistAction($albumid, $facebook);
} else {
try {
$albumArrInfo = array();
$user_profile = $facebook->api('/me/albums');
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
}
$session->fb_logout = $facebook->getLogoutUrl(array('next' => "http://{$_SERVER['HTTP_HOST']}/register/logout/id/Logout"));
$session->isfb = 1;
} else {
if (isset($_REQUEST['getfurl']) && !(isset($_REQUEST['state']))) {
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup','scope' => 'manage_pages,user_events,email,read_stream,user_photos,offline_access'));
echo $loginUrl;
exit;
}
}
}
public function albumlistAction($albumid, $facebook) {
$photos = $facebook->api("/{$albumid}/photos");
$albumArr = array();
$albumArrInfo = array();
foreach ($photos['data'] as $photo) {
$albumArr['id'] = $photo['id'];
$albumArr['name'] = $photo['name'];
}
return $albumArr;
}
Whats wrong with this code.
Need help.
Sounds like a similar problem I was facing. Bug report is here: http://developers.facebook.com/bugs/238039849657148
Try updating to the latest version of the PHP-SDK (3.2.2).
Try this:
$user = $facebook->getUser();
...
$user_profile = $facebook->api('/'.$user.'/albums');

Categories