Facebook login: url cannot be loaded - facebook

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.

Related

facebook insight (page-insights) HTTP status code: 200

using this code but showing "HTTP status 200" I checked Facebook documentation but issue didn't resolve kindly help me out there
$requestPageInsights = $fb->request('GET', '/Page-ID/insights/post_storytellers?, $accessToken');
//Make a batch request
$batch = ['page-insights' => $requestPageInsights];
try {
$responses = $fb->sendBatchRequest($batch);
} 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;
}
foreach ($responses as $key => $response) {
if ($response->isError()) {
$e = $response->getThrownException();
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
echo '<p>Graph Said: ' . "\n\n";
var_dump($e->getResponse());
} else {
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
echo "Response: " . $response->getBody() . "</p>\n\n";
echo "<hr />\n\n";
}
}
and Output is:
(page-insights) HTTP status code: 200
Response: {"data":[],"paging":{"previous":"https://graph.facebook.com/v2.9/1**********1/insights?
I think its a paging issue, but don't know how to resolve it.

Requesting page insight for Facebook getting error "Graph returned an error: An unknown error has occurred. "

$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','manage_pages','pages_manage_cta','publish_pages','publish_actions'];
giving permissions.
$loginUrl = $helper->getLoginUrl('http://localhost/Facebook/insight.php', $permissions);
echo 'Log in with Facebook!';
facebook Insight code.
$fb->setDefaultAccessToken($accessToken);
Get user groups detail
$requestPageInsights = $fb->request('GET', '/1364467436924381/insights/, $accessToken');
//Make a batch request
$batch = ['page-insights' => $requestPageInsights];
try {
$responses = $fb->sendBatchRequest($batch);
} 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;
}
Graph returned an error: An unknown error has occurred.
Just experienced the same issue.
The error seems to be with batched requests - The solution for us was to change the code to do the requests individually.

Retrieve users/company information

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

Code to access Facebook Graph API with PHP SDK not working when reloading page

I'm writing some code to get the Facebook pages administered by a Facebook user, using Facebook Graph API. My code asks for authorization of the user and gets a token that enables it to get this information, which is then stored in a session. The problem is that if I reload the page, the stored token is unset and I will not be able to get the Facebook pages administered by the Facebook user.
The token is apparently revoked via the 'validateExpiration()' function when the page is reloaded.
What am I missing?
Here is my code:
session_start();
// Load the Facebook PHP SDK
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
define('APP_ID', 'xxxxxxxxxxxxxxxx');
define('APP_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$fb = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.7'
]);
if(isset($_SESSION['fb_access_token'])) {
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
// Create a new AccessToken object from its string code. Needed?
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
$expirationDate = $accessToken->getExpiresAt();
echo 'Token expires at: ' . var_dump($expirationDate) . '<br>'; // Returns null!
// verifies the validity and expiration of the token
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
try {
echo 'Validating token<br>';
$tokenMetadata->validateAppId(APP_ID);
$tokenMetadata->validateExpiration(); // This apparently throws an exception
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
if(!isset($accessToken)){
echo 'Token not set!';
exit;
}
// Check permissions
if (isset($accessToken)) {
$response = $fb->get('/me/permissions', $accessToken);
$permissions = $response->getDecodedBody();
echo 'Permissions: ';
print_r($permissions);
$permissions_list = [];
foreach($permissions['data'] as $perm) {
if($perm['status'] == 'granted') {
$permissions_list[] = $perm['permission'];
}
}
echo 'Permissions list: ';
print_r($permissions_list);
if(!in_array('pages_show_list', $permissions_list)) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
}
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if(isset($accessToken)) {
// Logged in!
// Save the string code of the AccessToken to re-create it later
$_SESSION['fb_access_token'] = (string) $accessToken;
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
try {
$response = $fb->get('/me/accounts', $accessToken);
$data = $response->getDecodedBody();
echo '<pre>';
print_r($data);
echo '</pre>';
exit;
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile','pages_show_list']; // Optional permissions
$redirect_url = "https://www.example.com/this_file.php";
$loginUrl = $helper->getLoginUrl($redirect_url, $permissions);
echo 'Log in with Facebook!';
}
I finally got it!
The problem is that the Facebook AccessToken is an object with two properties: a string code, and a datetime PHP object with the expiration time - see the code in:
Github repository of Facebook's PHP SDK. The first time I get a fresh token, its expiration time is set and everything works fine. But when I store its code in a session and try to recreate it with
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
I'm not setting the expiration time, which the object defaults to the UNIX time 0 (i.e. January 1, 1970). Since after I invoke the function validateExpiration(), this will return that the access token has expired (it just looks at the expiration time in the AccessToken object) and will fire an exception.
Solution: Do not re-validate the stored token. The validateAppId(APP_ID) continues to be valid. For the expiration time, either store it (for example in a session) and use it when recreating the AccessToken object, or make a call to the Graph API. If this call returns an error (probably because of a token which was expired or a permission which was revoked by the user), ask the user for a new token via Facebook Login.

facebook php sdk 4 version, unable to fetch user albums

I am developing a facebook application via php sdk 4 version.
My code is as follows:
try {
$session = $helper->getSession();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
if ($session) {
try {
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$me = $response->getGraphObject();
$user_id = $me->getProperty('id');
echo $user_id;
$accessToken = $session->getAccessToken();
echo $accessToken;
echo "<br>".$user_id;
$request = new FacebookRequest($session, 'GET', '/me/albums');
$response = $request->execute();
$userAlbums = $response->getGraphObject();
echo $userAlbums['data'][0]['id'];
} catch(FacebookRequestException $e) {
echo $e->getMessage();
}
} else {
$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/lykebook/');
$auth_url = $helper->getLoginUrl(array('user_friends', 'publish_actions', 'user_photos', 'user_status', 'friends_photos','friends_status','publish_stream'));
echo "<script>window.top.location.href='".$auth_url."'</script>";
}
But the problem is I am not getting any album data. I don't know what the problem is? The earlier request i.e: /me is working fine. I checked that by printing $user_id. But the next request for getting albums is not working i.e /me/albums. Help me in correcting this.
Try using the getGraphObjectList() method since you are expecting more than one object. Then the result will be an array of GraphObject objects, see here.
From here, you need to access these as objects and not arrays with the helper methods available (e.g. getProperty()).
Otherwise, you can retrieve the array backing this object with asArray().
You could use getGraphEdge, here below the code:
$fb->setDefaultAccessToken($accessToken);
try {
$response = $fb->get('/me/albums');
$albums = $response->getGraphEdge();
} 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;
}
foreach ($albums as &$value) {
echo $value;
}