How to get the stream of a public Facebook fanpage in php? - php

I want to display my public fanpage feed onto my website via the Facebook API without requiring a login.
I'm doing this
require_once('../includes/classes/facebook-platform/php/facebook.php');
$fb = new Facebook($api_key, $secret);
$fb->api_client->stream_get('',$app_id,'0','0','','','','',''));
But I get this error
Fatal error: Uncaught exception 'FacebookRestClientException' with message 'user id parameter or session key required' in includes/classes/facebook-platform/php/facebookapi_php5_restlib.php:3065
Stack trace:
#0 includes/classes/facebook-platform/php/facebookapi_php5_restlib.php(1915): FacebookRestClient->call_method('facebook.stream...', Array)
#1 facebook/api.php(12): FacebookRestClient->stream_get('', 13156929019, '0', '0', 30, '', '', '', '')
#2 {main}
thrown in includes/classes/facebook-platform/php/facebookapi_php5_restlib.php on line 3065
Then I figured, because of 'user id parameter or session key required', to add my user id to the call
require_once('../includes/classes/facebook-platform/php/facebook.php');
$fb = new Facebook($api_key, $secret);
$fb->api_client->stream_get(502945616,13156929019,$app_id,'0','0','','','','',''));
But then I got this error
Fatal error: Uncaught exception 'FacebookRestClientException' with message 'Session key invalid or no longer valid'
I'm totally clueless :)

Here's what i did
1) Login to facebook.
2) Grant your application offline access to your account:
http://m.facebook.com/authorize.php?api_key=YOUR_API_KEY&v=1.0&ext_perm=offline_access
3) Add read stream permission
http://m.facebook.com/authorize.php?api_key=YOUR_API_KEY&v=1.0&ext_perm=read_stream
4) Generate a key code
http://www.facebook.com/code_gen.php?v=1.0&api_key=YOUR_API_KEY
5) Run this script once and copy the "session_key".
$facebook = new Facebook($api_key, $api_secret);
$infinite_key = $facebook->api_client->auth_getSession(YOUR_KEY_CODE);
print_r($infinite_key);
6) Plug and play!
$facebook->api_client->user = YOUR_FACEBOOK_USER_ID
$facebook->api_client->session_key = YOUR_INFINITE_KEY
$facebook->api_client->expires = 0;
$feed = $facebook->api_client->stream_get(YOUR_FACEBOOK_USER_ID, FAN_PAGE_ID);
So bascially, this will grab the feed from your "perspective" but filter it only to show items from the specified Fan page.
Disclaimer: This works, but I'm not sure whether this is a "supported" method for grabbing data, or even allowed at all.
References:
http://www.emcro.com/blog/2009/01/facebook-infinite-session-keys-no-more/
http://blog.jylin.com/2009/10/01/loading-wall-posts-using-facebookstream_get/

Ok, I tried many times, but it worked when I added QUOTES to code.
$infinite_key = $facebook->api_client->auth_getSession('YOUR_KEY_CODE');
Thanks for suggestion!

You need the Facebook library in your code and it is better to say APP_ID not API_KEY.
<?php
require_once('facebook.php');
$facebook = new Facebook('YOUR_APP_ID', 'YOUR_APP_SECRET');
$infinite_key = $facebook->api_client->auth_getSession('YOUR_KEY_CODE');
print_r($infinite_key);
?>

Related

Error on integrating php and google sheets api

I am trying to integrate google sheets api with php so that I can capture html form data and append it to spreadsheet but I am facing a weird error.
Below is the php snippet:
$client = new \Google_Client();
$client->setApplicationName('WEBMONK_QUOTATION_REQUESTS');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig('../credentials.json');
$service = new Google_Service_Sheets($client);
$spreadsheets_id = '1S2LPDl5XmOEx4TQ3cR4yZ4SAALcxXRyxU5nFMU7RW0I';
$range = 'QUOTESHEET';
$sheet_rows = [
strval($datetime),
strval($name),
strval($email),
strval($url),
strval($extras)
];
$body = new Google_Service_Sheets_ValueRange(['values' => [$sheet_rows]]);
$params = ['valueInputOption' => 'RAW'];
$insert = ['insertDataOption' => 'INSERT_ROWS'];
$result = $service->spreadsheets_values->append(
$spreadsheets_id,
$range,
$body,
$params,
$insert
);
Here is the error I am getting:
<br />
<b>Fatal error</b>: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in C:\xampp\htdocs\webric.org\api\vendor\google\apiclient\src\Google\Service\Resource.php:291
Stack trace:
#0 C:\xampp\htdocs\webric.org\api\vendor\google\apiclient\src\Google\Service\Resource.php(291): implode(Array, '&')
#1 C:\xampp\htdocs\webric.org\api\vendor\google\apiclient\src\Google\Service\Resource.php(190): Google_Service_Resource->createRequestUri('v4/spreadsheets...', Array)
#2 C:\xampp\htdocs\webric.org\api\vendor\google\apiclient-services\src\Google\Service\Sheets\Resource\SpreadsheetsValues.php(64): Google_Service_Resource->call('append', Array, 'Google_Service_...')
#3 C:\xampp\htdocs\webric.org\api\post\insert.php(68): Google_Service_Sheets_Resource_SpreadsheetsValues->append('1S2LPDl5XmOEx4T...', 'QUOTESHEET', Object(Google_Service_Sheets_ValueRange), Array, Array)
#4 {main}
thrown in <b>C:\xampp\htdocs\webric.org\api\vendor\google\apiclient\src\Google\Service\Resource.php</b> on line <b>291</b><br />
So far, that I have understood, an implode() function in the Google lib is malfunctioning because of wrong argument type. But I couldn't find anything wrong with my above php code. I have gone through the google sheets and php integration procedures as mentioned here:
PHP with Google Sheets Quickstart
PHP version: 8.0.0,
Google API Client: 2.0
Please tell me where I am going wrong. Thanks in advance.
Just had the same issue after switching to PHP 8.0 (previously working fine with PHP 7.2).
The implode() function in PHP 8.0 has basically the two arguments switched compared to previous versions. I checked out the lastest version of the Resource.php file in the Google library, and you should see that the line 303 reflects those changes already.
I went to my Resource.php file and replaced
$requestUrl .= '?' . implode($queryVars, '&');
with
$requestUrl .= '?' . implode('&', $queryVars);
And it's working again. Hope it helped!
There must be a problem with your values
Verify it by modifying $body to
$body = new Google_Service_Sheets_ValueRange([
"values" => [[1, 2, 3]]
]);
If this request works for you - log [$sheet_rows] to compare the structure and see what is wrong.
PS: Apart from the Quickstart, there is aslo method specific documentation for PHP

PHP Connect to Sharepoint using Thybag\SharePointAPI

I have the following code
//$sp = new SharePointAPI('&&', '&&', 'https://&&.net/personal/zzz/_vti_bin/Lists.asmx?WSDL',);
//$sp = new SharePointAPI('&&', '&&', 'https://&&net/personal/zzz/_vti_bin/Lists.asmx?SDL', 'NTLM');
$sp = new SharePointAPI('&&', '&&', 'https://&&net/personal/zzz/_vti_bin/Lists.asmx?WSDL', 'SPONLINE');
$listContents = $sp->read('GetListCollection');
return $listContents;
Depending on which of the "new SharepointAPI" lines I execute, I get a different error.
Using "NTLM", I get the error: -
Uncaught exception 'Exception' with message 'Error'
in /home/shinksyc/public_html/sharepointUpload/src/Thybag/Auth/SoapClientAuth.php:129
Stack trace:
#0 [internal function]: Thybag\Auth\SoapClientAuth->__doRequest('<?xml
version="...', 'https://my.sp.m...', 'http://schemas....', 1, 0)
Using "SPONLINE", I get the error
'Error (Client) looks like we got no XML document'.
I am also slightly confused as to how to find out what the name of the lists may be that I get read.
Any help is much appreciated.
Thanks
Martin
The path to your xml must be local: in clear, log to your sharepoint, go to the url https://mySPsite/subsite/_vti_bin/Lists.asmx?WSDL
Download the XML and place it on your PHP server.
then
$sp = new SharePointAPI($login, $password, $localPathToWSDL, 'NTLM');

PHP, FACEBOOK, PAGES, RSS: Help turning page feed into RSS (getting errors)

Ok, so following some instructions I found in another post here on StackOverflow, I have constructed a script to get a fan pages feed and turn it into an RSS2 feed. However, the script required a few changes and Im not the best programmer in the world, so I need a little help.
Im getting this error:
Warning: Invalid argument supplied for foreach() in feed.php on line 48
Im not sure what the invalid argument is all about.
<?
// error reporting
echo '<pre>';
ini_set('display_errors', 'on');
error_reporting(E_ALL);
// require your facebook php sdk
require('./facebook/facebook.php');
// include the feed generator feedwriter file
include("./feed/FeedWriter.php");
// config secret key and appid
$config = array(
'appId' => '',
'secret'=> ''
);
// Initialize
$facebook = new Facebook($config);
// Set Apps Permissions Request
$permission_scope = "";
// get users access token
$access_token = $facebook->getAccessToken();
// get page post
$feed_url = 'https://www.facebook.com/Ritualdubstep/feed?access_token='.$access_token;
$feed_json = file_get_contents($feed_url);
$feed_data = json_decode($feed_json);
// create the feedwriter object
$feed = new FeedWriter(RSS2);
$feed->setTitle('Ritual Dubstep'); // set your feed title
$feed->setLink('https://www.facebook.com/Ritualdubstep'); // set the url to the feed page you're generating
$feed->setChannelElement('updated', date(DATE_RSS , time()));
$feed->setChannelElement('author', array('name'=>'Ritual Dubstep SF')); // set the author name
// iterate through the facebook response to add items to the feed
foreach($feed_data['data'] as $entry){
if(isset($entry["message"])){
$item = $feed->createNewItem();
$item->setTitle($entry["from"]["name"]);
$item->setDate($entry["updated_time"]);
$item->setDescription($entry["message"]);
if(isset($entry["link"]))
$item->setLink(htmlentities($entry["link"]));
$feed->addItem($item);
}
}
// generate feed
$feed->genarateFeed();
?>
Generally it means that the first argument in the foreach call (in this case $feed_data['data']) is not a valid array.
Make sure that $feed_data['data'] exists (isset($feed_data['data'])) and that it is an array (is_array($feed_data['data'])) before running entering the foreach loop.
And - as shapeshifter mentioned in the comments - you might want to start troubleshooting by var_dump($feed_data['data']) right before you start the foreach loop to see what's being generated.

YouTube PHP API - Getting status of previously uploaded video?

Just started digging into the YouTube PHP API and got the browser-based Zend upload script working. However, I can't find any documentation on how to retrieve the status of the video after it's been uploaded. The main reason I would need this is for error handling - I need to be able to know whether the video was approved by YouTube, since someone could technically upload an image or a file too large. I need to know that the vid was approved so that I know what message to display the end user when they return to the site (ie 'Your video is live' or 'Video upload failed').
The YouTube PHP browser-based upload returns a URL parameter status of 200 even if the format or size is incorrect, which is of course not helpful. Any ideas on how else to get this info from the YT object?
All in all, when a user returns to the site, I want to be able to create a YT object based on their specific video ID, and want to be able to confirm that it was not rejected. I'm using ClientLogin to initiate the YouTube obj:
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser#gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
Any thoughts?
Whew, finally found the answer to this after searching around and piecing together code for the last few days. After you create the $yt object, use the following to check the status:
$yt->setMajorProtocolVersion(2);
$youtubeEntry = $yt->getVideoEntry('YOUR_YOUTUBE_VID_ID', null, true);
if ($youtubeEntry->getControl()){
$control = $youtubeEntry->getControl();
$state = $control->getState()->getName();
}
Echoing out $state displays the string 'failed' if the video was not approved for whatever reason. Otherwise it's empty, which means it was approved and is good to go (Guessing the other state names would be: processing, rejected, failed, restricted, as Mient-jan Stelling suggested above).
Crazy how tough this answer was to put together for first-time YouTube API'ers. Solved! (Pats self on back)
Do you have a CallToken if so its pretty easy.
For this example i use Zend_Gdata_Youtube with Zend AuthSub.
WHen uploading your video you had a CallToken, With this call token you can access the status of the video.
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser#gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$youtube = new Zend_Gdata_YouTube( $httpClient, '', NULL, YOUTUBE_DEVELOPER_KEY );
$youtubeEntry = $youtube->getFullVideoEntry( 'ID_OF_YOUTUBE_MOVIE' );
// its the 11 digit id all youtube video's have
in $youtubeEntry all your data about the video is present
$state = $youtubeEntry->getVideoState();
if state is null then your video is available else make of state a string like this.
(string) $state->getName();
There are about 4 important state names. ( processing, rejected, failed, restricted)

How can I fix this PHP XML parsing error?

This is my first question :).
Im writing a little twitter app in PHP that sends a DMs to all your followers. What im trying to do right now is to get the list of followers. So through twitter api and getting all usernames but for some reason this parsing error appear. Im new to php(but not so much to programming), I actually started learning it yesterday so please be easy on me ;).
Here is the code:
$t= new twitter();
$t->username= $_GET["username"];
$t->password= $_GET["password"];
$fi = $t->followers();
$xml[$page] = new SimpleXMLElement($fi[2]);
$user1count=0;
while(isset($xml[$page]->user[0])){
foreach ($xml[$page]->user as $user) {
$userdet[(string)$user->screen_name]=array( ’screen_name’=> (string)$user->screen_name, ‘location’=>(string)$user->location, ‘description’=>(string)$user-> description, ‘profile_image_url’=> (string)$user-> profile_image_url, ‘url’=>(string)$user-> url, ‘name’=>(string)$user->name );
$user1details[$user1count]= (string)$user->screen_name;
$user1count++;
}
$page++;
$fi=getfilecontents($friendsurl.$username1."xml?page".$page);
if($fi[0]===false){
echo ("Error :".$fi[1]);
$err=new SimpleXMLElement($fi[2]);
echo " ".$err->error." ";
// echo ““;
die();
}
$xml[$page] = new SimpleXMLElement($fi[2]);
}
And the error said:
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /Applications/XAMPP/xamppfiles/htdocs/scripts/dmsend.php:125 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/scripts/dmsend.php(125): SimpleXMLElement->__construct('') #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/scripts/dmsend.php on line 125
Thank you! :)
It looks like $fi[2] is not a valid xml string. I am not 100% familiar with the twitter API, but I would do a var_dump($fi) and evaluate what is begin returned. From there, you should be able to figure out what is happening.

Categories