While trying to post to a user's facebook wall using PHP, I am getting the error
{
"error": {
"type": "OAuthException",
"message":"(#100) http:\/\/spats.in\/nssc2 does not resolve to a valid user ID"
}
}
This is my code :
$apprequest_url = "https://graph.facebook.com/feed";
$mymessage="Hello World!";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . &id=".urlencode('http://spats.in/nssc2')."&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
What is the problem?
One reason for getting the (#100) <url> does not resolve to a valid user ID error is that the page has its Open Graph meta tags set incorrectly. You can use Facebook's Open Graph Debugger to see what might be wrong.
I figured it out myself. The request URL should have been http://graph.facebook.com/me/feeds/ and no id parameter was required.
Related
I'm trying to get this example to work: https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php#enable
The error I'm getting is "Error: redirect_uri_mismatch" .
In order to install the google api resources, I used composer with this command:
php composer.phar require google/apiclient:^2.0.0#RC
This installed the "vendor" folder in my root site folder. My index.php and oauth2callback.php files are located in the "public_html" folder.
Here's a screenshot of my error when going to my site:
The weird thing is that if I navigate to the link above that's included in the error message "Visit ...... to update the authorized..", I get this error message: " The OAuth Client Does Not Exist "
If I click on my only available Client ID, I can navigate to see the URI's which I'll screenshot below as well:
As you can see, under Authorized Javascript origins, I have http://localhost listed, and under authorized redirect URIs, I have my live site followed by the "oauthc2callback.php" file extension.
I don't understand how to get rid of the error I'm getting. I've tried replacing the URI's and putting in different JavaScript origins.
Also, for some reason on that last screenshot, it says that I don't have permission to edit this OAuth client, but I can make edits.
The code I have for index.php:
<?php
// Load the Google API PHP Client Library.
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
$results = getResults($analytics, $profile);
printResults($results);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getFirstprofileId(&$analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
}
The code I have for "oauth2callback.php":
<?php
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
All of this code was taken from the first website example, except with a few minor additions to make it match my system.
Anyone know how I can get rid of this error? What am I doing wrong?
Remember, as far as Google is concerned, "your" server is hostile until you name it "friendly", you must explicitly whitelist every possible source of an OAuth call TO Google.
Google is a clubbouncer, a big, ugly, unmovable bouncer with a a guest list saying to your application: "I will only deal with your request if your exact name OR id is on the list"
Have you tried including, not only localhost, but all other possible origins?
You must list every possible variation of url "root", including explicit IPs.
http://www.example.com
http://example.com
https://example.com
https://www.example.com
http://222.111.0.111
...
dont forget to include
https://accounts.google.com:443
The redirect Uri in the request MUST be exactly the same as one Uri you stored.
I see a / at the end of the stored one you missed in your request.
just copy the request URI on which error is occurring from error screen and paste it to OAuth credentials "Authorised redirect URIs"
now run the app.
this works for me. Hope I answered your query.
I'm actually having troubles with the graph API :
https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts&version=v2.2&
I've been generating an access token with the extended permission 'manage_pages' and i'm trying a request on the edge 'me/accounts'.
The result is always :
{
"data": [
]
}
But I wished to get a page access token instead.
Is this a normal behavior, or did I miss something?
I also tried with the php SDK 4.0 with a short-lived and a long-lived token and got the same result...
My code is here:
$app_id = '-hidden-'; //Facebook App ID
$app_secret = '-hidden-'; //Facebook App Secret
$long_lived_token = '-hidden-'; // tested at https://developers.facebook.com/tools/debug/
//and giving - Expires :1429438313 (in about 2 months)
FacebookSession::setDefaultApplication($app_id , $app_secret);
$session = new FacebookSession($long_lived_token);
if ($session) {
try {
$user_permissions = (new FacebookRequest($session, 'GET', '/me/permissions'))
->execute()->getGraphObject(GraphUser::className())->asArray();
$found_permission = false;
foreach($user_permissions as $key => $val){
if($val->permission == 'manage_pages'){
$found_permission = true;
}
}
// if we got manage_pages
if($found_permission){
$user_token = (new FacebookRequest($session, 'GET', '/me/accounts'))
->execute()->getGraphObject(GraphUser::className())->asArray();
var_dump($user_token); //array(0) { } - Why?? Is this normal??
} else {
echo "Manage pages not granted!";
}
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
Thanks for your help!
My user didn't have any pages to admin, this is why the array is empty.
I guessed page access token could be use to manage profile but I was wrong.
For anyone who had this problem and still couldn't solve, my problem is that I had generated a access_token before I was granted the admin privilege in the page I was looking for and because of that, I don't know why, I couldn't retrieve the page. I then deleted the access from my facebook page and when I generate a new token, it worked.
My app was doing well yesterday and posting custom stories with mention tagging but from today its not working and telling me : -
Received Facebook error response of type OAuthException: Unknown path components: /mynamespace:customaction
Error code : 2500
{
"error": {
"message": "Unknown path components: /namespace:customaction",
"type": "OAuthException",
"code": 2500
}
}
$response = $facebook->api(
'me/mynamespace:customaction',
'POST',
array(
'treat' => "http://www.mywebsite.com/12321425125"
)
);
I have not changed any configurations or anything and it has stopped working all of a sudden. Please help me identify the issue - maybe there is an issue at Facebook end.
I cannot exchange code for token using the following code:
extract($_GET);
$url=urlencode('http://'.DOMAIN.'/admin/');
$app_id=FB_APPID;
$fb_token=FB_TOKEN;
$secret=FB_SECRET;
if(SEND_NEWS_TO_FB){
if($code=='none'){
$state=rand(100000000,9999999999999999999);
$_SESSION['state']=$state;
$script="
<script type='text/javascript'>
var scope=encodeURI('publish_stream,user_status');
var app_id=$app_id;
var state=$state;
var url=$js_url;
window.location.href='https://www.facebook.com/dialog/oauth? client_id='+app_id+'&redirect_uri='+url+'&scope='+scope+'&state='+state;
</script>";
echo $script;
}
if($code!='none' && $_SESSION['state']==$state && $_SESSION['fb_token']!=1){
$_SESSION['fb_token']=1;
$token_url="https://graph.facebook.com/oauth/access_token?"
."client_id=" .$app_id
."&redirect_uri=" .$url
."&client_secret=" .$secret
."&code=" .$code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$token=$params['access_token'];
$qry="UPDATE `settings` SET `FB_token`='$token'";
$result=mysql_query($qry);
}
Placing the returned $token_url in my browser gives me a page with the token and expiration. Running the script returns a very vague "sorry, there was a problem" message. Almost all of the threads I have seen with problems doing this have been due to differences in the redirect uri's, but both the login and token request get the uri from the exact same place.
There was a whitespace between the app_id value and '&redirect_url'. FYI, your browser (at least chromium) will urlencode the whitespace automatically which is why the url will work fine in the browser. I still am not sure how the space is there, but urlencode() fixes it for now.
I retrieve an access Token via the javascript SDK and pass this to the server via a windows.location:
<script src='https://connect.facebook.net/en_US/all.js'></script>
<!-- Load javascript facebook connector -->
<script>
FB.init({
appId : '<?=$app_id;?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
<script type="text/javascript">
function getToken(){
FB.login(function(response) {
if (response.authResponse) {
var access_token = response.authResponse.accessToken;
window.location="<?=$_SERVER['PHP_SELF'];?>?accessToken="+access_token;
} else {
return false;
}
}, {scope:'user_likes,friends_likes'});
}
</script>
The PHP code:
<?php
$app_id = 'MY_APP_ID';
$app_secret = 'MY_APP_SECRET';
$page_id= 'MY_PAGE_ID';
if(isset($_GET['accessToken'])){
// Run fql query
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q=SELECT+uid+FROM+page_fan+WHERE+page_id='.$page_id.'+AND+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=me())&'.$_GET['accessToken'];
echo $fql_query_url;
$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);
//display results of fql query
foreach($fql_query_obj as $v1){
foreach($v1 as $v2){
$x++;
}
}
echo "You have ".$x." friends who 'like' us";
}
When I echo the $fql_query_url and past the url in the browser, facebook graph api answers
{
"error": {
"message": "An access token is required to request this resource.",
"type": "OAuthException",
"code": 104
}
}
What am I doing wrong? I DO get an access token but it seems not to be valid?
You missing access_token in the actual request since you just adding the access_token to the URL without actually naming that parameter. Add access_token= before adding $_GET['accessToken'] to URL.
It's really great to have your source readable to discover this kind of things:
$query = <<<FQL
SELECT uid FROM page_fan WHERE page_id = {$page_id} AND uid IN (
SELECT uid2 FROM friend WHERE uid1 = me()
)
FQL;
$fql_query_url = 'https://graph.facebook.com/fql?q=' . rawurlencode($query);
$fql_query_url .= '&access_token=' . rawurlencode($_GET['accessToken']);
BTW, it's a really bad maner to pass access_token via GET parameters, try to avoid this.