I am new to the facebook graph API ,but I know the basics. Now I need help from you all about how to read user wall posts and others who posted on the wall of any user, with read_stream. But I don't know how to call it. I tried some way but I was able to read just the name and basic info. I need help in reading objects. Please help me!!!
<?php
define('FACEBOOK_APP_ID', 'xxxxxx');
define('FACEBOOK_SECRET', 'xxxxxx');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php
echo 'Your Facebook ID: '.$cookie;
if ($cookie) {
//cookie is set, user is logged in
$user = json_decode(file_get_contents('http://graph.facebook.com/'.$cookie['uid']));
//Display the facebook user ID, name, gender and Facebook URL in the web browser
echo '<br />';
echo 'Your Facebook ID: '.$user->{'id'};
echo '<br />';
echo 'Your name: '.$user->{'name'};
echo '<br />';
echo 'Your gender: '.$user->{'gender'};
echo '<br />';
echo 'Your Facebook URL: '.$user->{'link'};
echo '<br />';
echo '<img src="http://graph.facebook.com/'.$user->{'id.'/picture" alt="'.$user-> {'name'}.'"/>';
echo '<br />';
echo '<fb:login-button autologoutlink="true"></fb:login-button>';
}
else
{
//user is not logged in, display the Facebook login button
echo '<h2>Facebook Application Test page</h2>';
echo '<br />';
echo' message somethng';
</body>
</html>
First of all you must take permission from your users
$url = "https://graph.facebook.com/oauth/authorize?"
."client_id=".$app_id."&"
."redirect_uri=http://apps.facebook.com/".$app_name."/&scope=read_stream";
<script language="javascript">window.open('<?php echo $url ?>', '_parent', '');</script>
Then you can get user's wall. There is an example here.
if(isset($_GET["code"])){
if(isset($_REQUEST['state']) == isset($_SESSION['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . "http://apps.facebook.com/".$app_name."/"
. "&client_secret=" . $app_secret . "&code=" . $_GET["code"];
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/".$user_id."/feed/?access_token=".$params['access_token'];
$user = json_decode(file_get_contents($graph_url));
foreach($user as $feeds)
{
foreach($feeds as $feed)
{
if(isset($feed->link))
{
echo $feed->link."<br>";
}
}
}
}
}
Related
I have the following code and get the following error (it is in Dutch):
Graph returned an error: URL kan niet worden geladen: Het domein van deze URL is niet toegevoegd aan de domeinen van deze app. Voeg alle domeinen en subdomeinen van je app toe aan het veld Appdomeinen in de instellingen van je app om deze URL te kunnen laden.
What may be wrong?
ini_set('display_errors', true);
$host = "m.****.com"; // Your Sub domain
$host2 = "www.m.****.com"; // Your Sub domain
if ($_SERVER['HTTP_HOST'] == $host || $_SERVER['HTTP_HOST'] == $host2) {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
$root_doc = str_replace("/m","",$root_doc);
} else {
$root_doc = $_SERVER['DOCUMENT_ROOT'];
}
include_once("$root_doc/php-graph-sdk-5.x/src/Facebook/autoload.php");
//require_once __DIR__ . '/vendor/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => '*****',
'app_secret' => '****',
'default_graph_version' => 'v2.10',
//'default_access_token' => '{access-token}', // optional
]);
// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
// $helper = $fb->getRedirectLoginHelper();
// $helper = $fb->getJavaScriptHelper();
// $helper = $fb->getCanvasHelper();
// $helper = $fb->getPageTabHelper();
//BEGIN
$helper = $fb->getRedirectLoginHelper();
//$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
try {
$accessToken = $helper->getAccessToken();
} 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;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
//echo '<h3>Metadata</h3>';
//var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId("152670682069405");
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
//END
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('/me', '{access-token}');
} 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();
echo 'Logged in as ' . $me->getName();
I hope i will get an answer.
Regards,
Jeroen
Translated from Dutch to English:
URL can not be loaded: The domain of this URL has not been added to the domains of this app. Add all domains and subdomains of your app to the App domains field in your app's settings to load this URL.
On connecting to Quickbook within our app we are able to get access token and realmid but on trying to implement Get App Now we couldn't get any information after redirecting to our openid url. What I have tried so far is
define('OAUTH_CONSUMER_KEY', $consumerkey);
define('OAUTH_CONSUMER_SECRET', $consumersecret);
define('OAUTH_URL', 'https://oauth.intuit.com/');
define('APPCENTER_URL', 'https://appcenter.intuit.com/');
define('OAUTH_REQUEST_URL', OAUTH_URL . 'oauth/v1/get_request_token');
define('OAUTH_ACCESS_URL', OAUTH_URL . 'oauth/v1/get_access_token');
define('OAUTH_AUTHORISE_URL', APPCENTER_URL . 'Connect/Begin');
define('OAUTH_CURRENT_USER', APPCENTER_URL . 'api/v1/user/current');
try{
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$request_token = $oauth->getRequestToken(OAUTH_CURRENT_USER,CALLBACK_URL);
echo '<pre>';
print_r($_POST);
print_r($_GET);
print_r($_REQUEST);
print_r($_SESSION);
echo $request_token;
print_r($request_token);
echo '</pre>';
} catch(OAuthException $e) {
pr($e);
}
I can't get any valuable information on the above code, I maybe doing it wrong and expecting that there would be realmid and access token once the authorization is done and quickbooks redirect to our openid url. Any information would be appreciated.
Please note I really don't have knowledge about this as this is my first time using quickbooks api and related technologies.
Updated
<?php
require 'openid.php';
try {
# Change 'localhost' to your domain name.
$openid = new LightOpenID($_SERVER["HTTP_HOST"]);
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'https://openid.intuit.com/OpenId/Provider';//'https://www.google.com/accounts/o8/id';
$openid->required = array(
'contact/email',
'namePerson/first',
'namePerson/last'
);
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<button>Login with Google</button>
</form>
<?php
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . 'logged in.';
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
When the form above gets submitted it results into No OpenID Server found at https://openid.intuit.com/OpenId/Provider
I'd like to use this free form template but I want it to redirect me to a thank you page upon submission.
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "e-mail here";
$email_subject = "subject here";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
How can I add a code where I will be redirected to a page of my choice?
header("Location: http://page_of_your_choice.com");
Just insert this where you have the
<!-- include your own success html here -->
I'm beginner who try to create Facebook App. Here is the code:
<?php
$app_id = "xxx";
$canvas_page = "https://apps.facebook.com/xxx/";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&scope=user_birthday";
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("<p>Welcome. Your Facebook ID is " . $data["user_id"] . "</p>");
if (isset($_POST['salary'])) {
echo "<p>You wrote salary: " . $_POST['salary'] . "</p>";
}
else {
echo "<p>You didn't wrote salary.</p>";
};
echo "<form method='post' action='$canvas_page'>";
echo "<input type='text' name='salary'>";
echo "<input type='submit'>";
echo "</form>";
}
?>
Why the result always show "You didn't wrote salary".
That code does actually work on my canvas, so the problem must be with the auth url. Briefly:
if this condition:
if (empty($data["user_id"]))
gets to be true, what you will have will be the user redirected to the auth url and after that back to your canvas page.
You can check if this happens looking at the url: if there is a code=something attached to the end of the url it means that the user has been redirected, doing this obviously you lose the while _POST content.
You could just in case have a print_r or var_dump of $data to be sure that it is actually filled with something.
Bye =)
EDIT 14.10.11: Actually your code is right, there's nothing wrong in it, so the sample code is your own code
I am developing a facebook application using php-sdk. i want to take some extended permissions from user of my application. As this is application where user comes after login into facebook, so how can i take extended permission when user visit my page? We cannot place login button in which we can take permissions.I means when user first time comes to my application a pop up widow having a list of permission. How to display that at first visit of any user to my application. Any one can guide me how to take and where to place that code?
Thanks in advance.
Regards,
Awais Qarni
check this
`<?php
$app_id = "YOUR_APP_ID";
$app_sec = "APP_SEC";
$canvas_page = "APP_CANVAS_PAGE_URL";
$scope = "&scope=user_photos,email,publish_stream"; $auth_url"http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page).$scope;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
if (empty($data["user_id"])) {
echo(""); }
$access_token = $data["oauth_token"];
$user_id = $data["user_id"];
$user = json_decode(file_get_contents( "https://graph.facebook.com/me?access_token=" . $access_token));
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE["fbs" . $app_id], "\""), $args);
ksort($args);
$payload = "";
foreach ($args as $key => $value) {
if ($key != "sig") {
$payload .= $key . "=" . $value;
}
}
if (md5($payload . $application_secret) != $args["sig"]) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($app_id, $app_sec);
?>