I'm trying to read ratings from a Facebook page to display externally, using the PHP SDK. I already have a long live access token, and have been able to use it to pull in the main page data, but when I try access the /ratings endpoint, I just receive back an empty Array ( )
class FacebookReviews
{
protected $session;
protected $page;
protected $ratings;
protected $appId;
protected $appSecret;
function __construct($appId = null, $appSecret = null)
{
session_start();
$this->appId = '123456789123456';
$this->appSecret = '1234567890abcdefghijklmnopqrstuv';
Facebook\FacebookSession::setDefaultApplication($this->appId, $this->appSecret);
$this->session = new Facebook\FacebookSession('LONG LIVE ACCESS TOKEN I GENERATED ON THE GRAPH API');
try {
$this->session->validate();
} catch (Facebook\FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
try {
$this->page = (new Facebook\FacebookRequest($this->session, 'GET', '/123456789123456/ratings'))->execute()->getGraphObject()->asArray();
} catch(Facebook\FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
public function result()
{
return $this->page;
}
}
$reviews = new FacebookReviews();
print_r($reviews->result());
If I remove /ratings from the request uri, it returns the data fine, but as I mentioned with it in there it doesn't work.
I generated the long live access token from my own account, which has admin access to the page
Related
I'm using this code and it's returning me URL and it looks fine and it creating the folder in public/sre_reports/
But after the URL I don't see what to do :
public function generatePublicReport()
{
try {
$report = new ReportOptions(Constants::SRE_PUBLIC_REPORT);
$report->select_tables(array("users"))
->set_grouping(array("id"))
->select_all_fields();
$engine = new CustomEngine($report);
$report_path = $engine->create_report();
return "Your report URL:" . $report_path;
} catch (Exception $ex) {
echo "Caught exception message:". $ex->getMessage();
}
}
OutPut: Your report URL:https://domainname.com/var/www/html/folder/public/sre_reports/rep1592553829503324/rep1592553829503324.php
I want to create copy of excel sheet of google doc using PHP API.I can see java code but no PHP code at all :(
Actually I already have a excel sheet on google drive I want to show it on website, I am already successed in it but problem is The same file is visible to everyone and if one user is changing file and at the same time same user can see that changes as it is synced to google drive.
So I thought solution is if I can create a copy of the sheet and shows different-2 copies to each user via PHP API.
===============
Edited Code
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
$arr['convert'] = false;
$arr['visibility'] = 'default';
return $service->files->copy($originFileId, $copiedFile,$arr);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
function insertPermission($service, $fileId, $value, $type, $role) {
$newPermission = new Google_Permission();
$newPermission->setValue($value);
$newPermission->setType($type);
$newPermission->setRole($role);
try {
return $service->permissions->insert($fileId, $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
function updateRevision($service, $fileId, $revisionId) {
try {
// First retrieve the revision from the API.
$revisions = $service->revisions;
$revision = $revisions->get($fileId, $revisionId);
echo '<pre>';print_r($revision);
$revision->setPinned(true);
return $revisions->update($fileId, $revisionId, $revision);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
function updateRevision1($service, $fileId, $revisionId) {
$patchedRevision = new Google_Revision();
$patchedRevision->setPublished(true);
$patchedRevision->setPublishAuto(true);
$patchedRevision->setPublishedOutsideDomain(true);
try {
return $service->revisions->patch($fileId, $revisionId, $patchedRevision);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('clientid');
$client->setClientSecret('secret');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setRedirectUri('redirecturi');
$service = new Google_DriveService($client);
if(!isset($_GET['code']) ) {
$authUrl = $client->createAuthUrl();
header('location: '.$authUrl );
die;
}
else{
$authCode = $_GET['code'];
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
$new_file = copyFile($service,'fileid','Baby Schema');
echo 'file=<pre>';print_r($new_file);
$permission = insertPermission($service,$new_file['id'],'me','anyone','writer');
echo 'permission=<pre>';print_r($permission);
$revision = updateRevision1($service, $new_file['id'], '1');
echo 'pub=<pre>';print_r($revision);
}
Code is working absolutely perfect but it is not doing what I want.
The above code is doing these tasks
1) I have one spreadsheet on bhuvneshgupta333#gmail.com
2) I am creating copy when bhuvnesh.gupta#witslog.com login to my abc.com website.
3) I am setting copy to be public on web.
4) Making copy to be published on web.
Now I am having issue.
1) In the spreadsheet there are 5 sheets out of them 2 are editable and rest 3 are protected so no one can see my formulas.
2) When copy is created by bhuvnesh.gupta#witslog.com then he becomes the owner of file while file is on bhuvneshgupta333#gmail.com while I want Owner to be bhuvneshgupta not bhuvnesh.gupta because I don't want to show formulas to any one not even bhuvnesh.gupta when file is opened on web.
3) I want to protect 3 sheets of spreadsheet to everyone.
I am using this way to call spreadhseet on web.
<iframe width="100%" height="600" src="https://docs.google.com/spreadsheets/d/fileid/edit?usp=sharing;&rm=minimal"></iframe>
Please help me guys.It's last point of my project.
Please help me guys.
Thanks in advance!
The google drive API reference does include PhP code for file copying.
/**
* Copy an existing file.
*
* #param Google_DriveService $service Drive API service instance.
* #param String $originFileId ID of the origin file to copy.
* #param String $copyTitle Title of the copy.
* #return DriveFile The copied file. NULL is returned if an API error occurred.
*/
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
It is here: https://developers.google.com/drive/v2/reference/files/copy#try-it
The situation: I have a finished Facebook canvas app (PHP/CodeIgniter), I just need to add the Facebook-related options such as sharing and inviting friends.
Current task: getting the list of invitable friends from the PHP SDK.
Relevant documentation: https://developers.facebook.com/docs/games/invitable-friends/v2.0
The code: in my Facebook library, I have created the following function.
/**
* Returns the current user's invitable friends
*/
public function get_invitable_friends() {
if ( $this->session ) {
$request = ( new FacebookRequest( $this->session, 'GET', '/me/invitable_friends' ) )->execute();
$graphObject = $request->getGraphObject();
return $graphObject;
}
return false;
}
The condition if($this->session) is because it doesn't make sense to try anything if there's no Facebook session in the first place. This will come into play later.
I've tried calling this function in two ways. The first way works and the second doesn't. I'm gonna present both, and then somebody will hopefully explain to me why the second way doesn't work and how to fix it, as I'd much prefer to use that.
First (working) way:
Call the function from the main controller's index() method, as the page loads. The function correctly returns a list of my friends.
Second (non-working) way:
Create this function in the controller:
//load list of friends we can invite to play the game
public function load_invitable_friends()
{
$this->load->library('facebook');
$list = $this->facebook->get_invitable_friends();
var_dump($list);
}
Then call it through AJAX, like:
function loadInvites(){
$.post(base+"main/load_invitable_friends/",function(resp){
$('#slide_6_inner').html(resp);
});
}
After this call, the content of the slide_6_inner div should contain the list of friends, as dumped by var_dump. However, the content is bool(false), indicating that the Facebook session is no longer present.
If I remove the condition if( $this->session ) from the get_invitable_friends() method, then this error happens:
A PHP Error was encountered
Severity: 4096
Message: Argument 1 passed to Facebook\FacebookRequest::__construct() must be an instance of Facebook\FacebookSession, null given, called in /home/lights/public_html/appname/application/libraries/facebook/Facebook.php on line 125 and defined
Filename: Facebook/FacebookRequest.php
Line Number: 182
The session in Facebook.php is initially created with the following code.
$this->ci =& get_instance();
// Initialize the SDK
FacebookSession::setDefaultApplication( $api_id, $api_secret) );
$this->helper = new FacebookCanvasLoginHelper();
$this->session = $this->helper->getSession();
To sum up - why is this problem occurring and how do I fix it?
In order to retrieve the session from the server side, you will need to first create a session using the FacebookCanvasLoginHelper. This class takes a signed request from Facebook supplied in a POST request, and exchanges it for a FacebookSession object. This should only really be done one when a user logs into your application:
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Store this in your PHP session somewhere:
$token = $session->getToken();
}
Thereafter, you should use the token to initialize the session:
$token = //GET THIS FROM SESSION
use Facebook\FacebookSession;
FacebookSession::setDefaultApplication('app-id', 'app-secret');
// If you already have a valid access token:
$session = new FacebookSession($token);
// To validate the session:
try {
$session->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
Well, it seems you are not doing anything if session does not exists, just returning false. The problem is occuring because the session is expired/or does not exists, so you have to validate the fbToken and set the session again or create a new one.
You can create a function that checks if user is logged in, like:
function CheckFbUser() {
// Check if existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
// Create new session from saved access_token
$session = new FacebookSession($_SESSION['fb_token']);
// Validate token
try {
if (!$session->validate()) {
$session = null;
}
} catch (Exception $e) {
// Catch any exceptions
$session = null;
}
} else {
// No session
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $e) {
// handle it for facebook exceptions
} catch(Exception $e) {
// handle your php exceptions
}
}
// Check if a session exists
if ( isset( $session ) ) {
// Save the session
$_SESSION['fb_token'] = $session->getToken();
// Create session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// USUALLY, here, people show the Logout Button, or anything alike, but you could it
// to return true, and then continue to run your code.
} else {
// No session
// USUALLY, here, people show the Login Button, or anything alike, you could
// use it to return false, or redirect user to login first.
$helper->getLoginUrl();
}
}
That is just an simple code, to check if user is logged in or not before you run the requests.
I am trying to create a subscribe method for my laravel app that uses the mailchimp api to subscribe a user to a given list. The method works fine when the email address is not already on the lsit. when it is already subscribed the mailchimp api throws the following error
Mailchimp_List_AlreadySubscribed blah#blah.co is already subscribed to
list Tc App Test List. Click here to update your profile.
with the following code being shown
public function castError($result) {
if($result['status'] !== 'error' || !$result['name']) throw new Mailchimp_Error('We received an unexpected error: ' . json_encode($result));
$class = (isset(self::$error_map[$result['name']])) ? self::$error_map[$result['name']] : 'Mailchimp_Error';
return new $class($result['error'], $result['code']);
}
I have attempted a try catch block to catch the error but it is still being returned to the browser, here is what I tried and were it says MailChimp_Error I tried with Exception as well.
public function subscribe($id, $email, $merge_vars)
{
try {
$this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (MailChimp_Error $e) {
$response = 'an error has occured';
}
return $response;
}
Ultimately I want to be able to run the method and then either return either a success message or a message describing the issue to the user. the 3 possible mailchimp method errors are Email_notexists, list_alreadysubscribed and list does not exist although tihs last one should not occur as I am providing the list in the source code.
edit 1; after being in touch with mailchimp api support they suggested this code but the error still gets returned to the browser in its entirety
try {
$results = $this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (Mailchimp_Error $e) {
if ($e->getMessage()) {
$error = 'Code:'.$e->getCode().': '.$e->getMessage();
}
}
echo $error;
You can do
try
{
$response = $this->mailchimp->lists->addListMember($list_id, [
"email_address" => $email,
"status" => "subscribed",
]);
}
catch (\EXCEPTION $e) {
return $e->getMessage();
}
The \EXCEPTION handles a sort of error for stripe
Subscribe is in a namespace Acme\Emails\Subscribe so catch(Mailchimp_Error $e) looks for Mailchimp_Error in this namespace.
Changing it to catch(\Mailchimp_Error $e) makes it look in the root namespace and then it works as intended
I need to check if the given Facebook app id is valid. Also, I need to check which domain and site configurations are set for this app id. It doesn't matter if it's done through PHP or Javascript.
I checked everywhere but couldn't find any information about this. Any ideas?
You can validate the ID by going to http://graph.facebook.com/<APP_ID> and seeing if it loads what you expect. For the app information, try using admin.getAppProperties, using properties from this list.
Use the Graph API. Simply request:
https://graph.facebook.com/<appid>
It should return you a JSON object that looks like this:
{
id: "<appid>",
name: "<appname>",
category: "<app category>",
subcategory: "<app subcategory>",
link: "<applink>",
type: "application",
}
So, to validate if the specified app_id is indeed the id of an application, look for the type property and check if it says application. If the id is not found at all, it will just return false.
More info: https://developers.facebook.com/docs/reference/api/application/
For example:
<?php
$app_id = 246554168145;
$object = json_decode(file_get_contents('https://graph.facebook.com/'.$app_id));
// the object is supposed to have a type property (according to the FB docs)
// but doesn't, so checking on the link as well. If that gets fixed
// then check on isset($object->type) && $object->type == 'application'
if ($object && isset($object->link) && strstr($object->link, 'http://www.facebook.com/apps/application.php')) {
print "The name of this app is: {$object->name}";
} else {
throw new InvalidArgumentException('This is not the id of an application');
}
?>
Use the Graph API:
$fb = new Facebook\Facebook(/* . . . */);
// Send the request to Graph
try {
$response = $fb->get('/me');
} 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;
}
var_dump($response);
// class Facebook\FacebookResponse . . .
More info:FacebookResponse for the Facebook SDK for PHP