Facebook like doesn't count each "story" individually - facebook

Description :
Ι have a laravel project which users can submit through a form a story. Each story has a title and a subject. After being approved by an admin panel the story can be seen at an "archive" page (which is also the index page) which shows all approved stories. Each story has a facebook like button so we can count how many likes each story has. I use the below code to check what it's returned for a specific url :
http://graph.facebook.com/?fields=og_object%7Blikes.summary(true).limit(0)%7D,share&id=MY_URL_HERE
MY_URL_HERE has a structure like domain.com/story/1 where "1" is the id of the specific story.
Using the url : domain.com/story/1 , info like the below can are returned :
{
"og_object": {
"likes": {
"data": [
],
"summary": {
"total_count": 1,
"can_like": false,
"has_liked": false
}
},
"id": "1702103726528488"
},
"share": {
"comment_count": 0,
"share_count": 1
},
"id": "http.domain.com/story/1"
}
We can see it the count of likes, shares etc. Also, for the story with the id "1" it has an id "id": "1702103726528488"
What i think it's the problem :
No matter what Story ID i put in the url it always returns the ID 1702103726528488, i guess that means that facebook doesn't recognize that it's a different url - so a different ID should be used.
What is interesting :
If i change my route name from :
domain.com/story/{id} to domain.com/{id} it works. Using that url every ID is different in the object returned by the graph facebook url provided above.
Any ideas?
Rest information :
The facebook like button for each story :
<div class="content-single-more">
READ THE STORY // it redirects to domain.com/story/id
</div>
Routing :
Route::get('/', [
'as' => 'index',
'uses' => 'StoriesController#getStories'
]);
Route::get('/index/{paginate}', [
'as' => 'index',
'uses' => 'StoriesController#paginateIndex'
]);
Route::get('story/{id}', [
'as' => 'story',
'uses' => 'StoriesController#getSingleStory',
]);
StoriesController
public function getStories(){
// css class to return
$body_class = "homepage";
$stories = DB::table('users_stories')->select('user_id', 'story_title', 'story')->where('state', '=', 'approved')->paginate(6);
// fgn first value
$fgn = 6;
return view('index', compact('stories', 'body_class', 'fgn'));
}
public function paginateIndex($paginate){
// css class to return
$body_class = "homepage";
$fgn = $paginate * 1;
$stories = DB::table('users_stories')->select('user_id', 'story_title', 'story')->where('state', '=', 'approved')->paginate($fgn);
return view('index', compact('stories', 'body_class', 'fgn'));
}
public function getSingleStory($id){
$single_stories = UserStoriesModel::where('state', '=', 'approved')->where('user_id', '=', $id)->get(['user_id', 'story_title', 'story']);
// dd($single_stories);
// css class to return
$body_class = "single-post";
// get the current user
$user = UserStoriesModel::find($id);
if(!$user){
return redirect()->route('index');
}
// get previous user id
$previous_story = UserStoriesModel::where('user_id', '<', $user->user_id)->where('state', '=', 'approved')->max('user_id');
// get next user id
$next_story = UserStoriesModel::where('user_id', '>', $user->user_id)->where('state', '=', 'approved')->min('user_id');
//dd($previous_story);
return view('story', compact('single_stories', 'body_class', 'next_story', 'previous_story'));
}

You need to make sure that Facebook fetches the content from the actual URL you are sharing.
If you have a canonical URL set, Facebook will take that as the “real” URL for this content. So either remove that, or specify the URL you want Facebook to consider the “real” one explicitly via an og:url meta tag.

Related

Yii2 Redirect to previous page after update

I have a application where after update user should be redirected to previous page from pagination.
let's say there is a gridview and user is at page 3. Then he update some record at that page. There should be a redirect to index page 3. What if, while user is updating record, before save, he opens another controller/action in new tab. Then ReturnUrl is now that new action and after save the record he is updating, he is redirected to that new url.
I've tried to set in every action "index" Url::remember(); and then in action "update" - return $this->goBack().
Also return $this->redirect(Yii::$app->request->referrer);, but it stays at same page.
There is a way to store every index URL in session, but in large project that means many sessions.
You could provide the returnUrl to the link, say:
Url::to(['update','id'=>$model->url,'returnUrl'=> Yii::$app->request->url]);
Then in your controller, use $this->request->queryParams['returnUrl'] to redirect to the previousUrl.
To take it one step further, to always provide the returnUrl, you could extend the Url Helper class:
namespace app\helpers;
use yii\helpers;
class Url extends yii\helpers\Url
public function toRouteAndReturn($route, array $params = [], $scheme = false) {
$params['returnUrl'] = Yii::$app->request->url;
return parent::toRoute($route,$params,$scheme);
}
You could provide in your main config:
'on afterAction' => function($event) {
if(!Yii::$app->getResponse()->isSent && !empty(Yii::$app->getRequest()->queryParams['returnUrl']) {
Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->queryParams['returnUrl']);
}
}
Then you could use app\helpers\Url::toRouteAndReturn() instead of yii\helpers\Url::toRoute() to have it return to the previous url.
You can try below Solution.
First in your index page, get current page url and encode it.
$current_url=base64_encode(\Yii::$app->request->getUrl());
Append this url with your update link as below.
'urlCreator' => function ($action, $model, $key, $index) use ($current_url) {
if ($action === 'update') {
$url = Yii::$app->request->baseUrl . '/controllerName/update?id=' . $model->id.'&prev='.$current_url;
return $url;
}
// ......
}
In Controller, in Update method decode url as below and use for redirection.
public function actionUpdate($id)
{
$model = $this->findModel($id);
$prev=base64_decode($_REQUEST['prev']);
// ......
return $this->redirect($prev); // you will redirect from where update method is called
// ......
}
Isn't it quite easy to pass page param into your update url (<model/update>) like <model>/update?id=<id>&page=<page>?
in your index.php view, edit your ActionColumn as follow:
[
'class' => 'yii\grid\ActionColumn',
'urlCreator' => function ($action, $model, $key, $index) {
return \yii\helpers\Url::to([$action, 'id' => $model->id, 'page' => Yii::$app->request->getQueryParam('page', null)]);
},
],
As you can see, I'm getting page param from request url and pass it to models' action buttons
And when you click to update model, the page that we entered from is stored/placed in url.
Controller:
public function actionUpdate($id, $page = null)
{
$model = $this->findModel($id);
...
if($model->save()) {
return $this->redirect(['index', 'page' => $page]);
}
...
}
Finally, after we successfully update the model, the action redirects us to previous index page.

Facebook Graph API not returning email

I have the following code:
$fb = new Facebook([
'app_id' => $appId,
'app_secret' => $appSecret,
'default_graph_version' => 'v2.9',
]);
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetaData = $oAuth2Client->debugToken($accessToken);
dump($tokenMetaData);
$graphUser = $fb->get('/me?fields=first_name,last_name,email', $accessToken)->getGraphUser()->asArray();
dump($graphUser);
The output for the above is the following:
$metaData:
[
"app_id" => "..."
"application" => "My App Name"
"expires_at" => "2017-07-01 11:40:09.000000"
"is_valid" => true
"issued_at" => "2017-05-02 11:40:09.000000"
"metadata" => array:2 [
"auth_type" => "rerequest"
"sso" => "ios"
]
"scopes" => array:2 [
0 => "email"
1 => "public_profile"
]
"user_id" => "102..."
]
}
$graphUser:
array:3 [
"first_name" => "John"
"last_name" => "Smith"
"id" => "102...",
]
As you can see, the scopes in $metaData clearly has email so it isn't a permission issue. Despite this, the graph user sometimes does not have the email (although in some cases it does).
Why is this and how can I solve this issue?
Add the fields you need to the URL of your request:
https://graph.facebook.com/me?fields=email,name
First check if your access token gets the user's permission for the email
https://graph.facebook.com/me/permissions?
access_token=(access-token)
&debug=all
if in the answer, this content does not appear:
{
"data": [
{
"permission": "email",
"status": "granted"
},
{
"permission": "public_profile",
"status": "granted"
}
]
}
Maybe in obtaining your access token I do not request mail ownership: Add scope=email to the request
https://www.facebook.com/v2.10/dialog/oauth?
client_id=(app-id)
&redirect_uri=(redirect-uri)
&scope=email
One possibility which i came across today is, if i am registering a account where i am not logging in using my email ID, may be using mobile number to login, and even in my profile primary email is not set or set to a mobile number, in this case facebook returns null for email.
I have updated the account and added email to primary email field under settings in facebook page, then i was able to get the email id from facebook.
Hope this helps someone.
Happy coding...
You have to check these steps.
check if your access token gets the user's permission for the email . for that login to your developer account of your app, then tools->graph api explorer then enable user's permission for the email.
check the facebook version, use the latest version.
add email scope in face book login script as below
app.get(
'/auth/facebook',
passport.authenticate('facebook', {
scope: ['user_location', 'email', 'user_friends']
})
);
or
FB.login(function(response) {
// your ajax script
},{
scope: 'email',
return_scopes: true
});
Goto your app > App review > Permissions and Features
Request Advanced access for email which should turn Standard Access into Advanced Access
I solved this issue by specifying the graph api version.
My requested fields first_name,last_name,email,picture
To url: https://graph.facebook.com/me
Did NOT return email.
To url: https://graph.facebook.com/v2.9/me
Did return email.
Hope this helps.

Check Is User liked or not of some specific facebook page

I tried to get whether user liked or not for some specific fan page by using following three techniques. But, all of them didn't work and gives false value or empty array as a results.
Facebook SDK is well configured and work properly. So, I have no idea what the issue on this. Please can anyone give me some suggestion for this or how can I check Is user liked or not on some specific fan page on facebook.
1.
$likes = $facebook->api("/me/likes/<page_id>");
if( !empty($likes['data']) ) {
`$page_like_status = "I like!";`
} else {
`$page_like_status = "not a fan!";`
}
2.
$isFan = $facebook->api(array(
"method" => "pages.isFan",
"page_id" => <page_id>,
"uid" => <fb_user_id>
));
if($isFan === TRUE) $tt = "I'm a fan!";
3.
if($me) {
$youlikeit = $facebook->api(array(
"method" => "fql.query",
"query" => "select uid from page_fan where uid=me() and page_id=<page_id>"
));
}
$youlikeit = sizeof($youlikeit) == 1 ? true : false;

Register Achievement ok, Create Achievement Returns false

I've just started implementing FB Achievements for my Game. I'm using the PHP SDK for my app.
I've successfully registered an Achievement using the following code from my class which subclasses the PHP SDK class:
$URL = 'apps.facebook.com/<app_name>/ach1.html';
$AppID = $this->getAppId();
$Params = array('achievement' => $URL);
$res = $this->api($AppID.'/achievements', 'POST', $Params);
I can confirm this has been created via the Graph API Explorer:
{
"data": [
{
"url": "http://apps.facebook.com/<app_name>/ach1.html",
"type": "game.achievement",
"title": "Tutorial",
"image": [
{
"url": "<app_img_url>/1-ach.jpg"
}
],
"description": "Tutorial Completed",
"site_name": "<app_name>",
"data": {
"points": 1
},
"updated_time": "2012-07-13T16:05:44+0000",
"id": "<id>",
"application": {
"id": "<app_id>",
"name": "<app_name>",
"url": "https://www.facebook.com/apps/application.php?id=<app_id>"
},
"context": {
"display_order": 0
}
}
]
}
However when I try to create an achievement for myself it returns false:
$URL = 'apps.facebook.com/<app_name>/ach1.html';
$UserID = 100000466230867;
$AccessToken = $this->getApplicationAccessToken();
$Params = array('access_token' => $AccessToken,
'method' => 'post',
'achievement' => $URL);
$res = $this->api($UserID.'/achievements', 'POST', $Params);
The result is "boolean false". No error code is returned. Am I doing something obviously or fundamentally wrong here? I've tried providing a 'display_order' of value 1 and 0 aswell.
I can confirm I've granted the publish_actions permission aswell.
permissions:Array ( [data] => Array ( [0] => Array ( [installed] => 1 [email] => 1 [publish_actions] => 1 [bookmarked] => 1 ) ) )
My app is correctly configured as a game aswell.
Any help greatly appreciated!!
Cheers
If the app is in sandbox mode, take it out.
Ensure the user has authorised & hasn't removed the app
'false' usually means 'Person or page whose access token you're using can't see the data you're asking for',
This happens most often for blocked users, apps in sandbox mode, deleted content, etc
In this case, i suspect the app can't see / interact with the user (if this a test user created via the app settings interface or API this is especially likely as test users have some strange privacy quirks)

facebook fan pages and related open graph objects

If exist a facebook fan page like this:
https://www.facebook.com/HuffingtonPost
I suppose to get likes count calling graph API:
https://graph.facebook.com/https://www.facebook.com/HuffingtonPost
Infact here I get:
{
"id": "https://www.facebook.com/HuffingtonPost",
"shares": 435839
}
On the other hand if I call
https://graph.facebook.com/HuffingtonPost
I get a more verbose output:
{
"id": "18468761129",
"name": "The Huffington Post",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-ash2/188072_18468761129_6398033_s.jpg",
"link": "http://www.facebook.com/HuffingtonPost",
"likes": 435832,
"category": "Website",
"website": "http://www.facebook.com/HuffingtonPost",
"username": "HuffingtonPost",
"company_overview": "The Internet Newspaper\nNews | Blogs | Video | Community",
"description": "The Huffington Post - The Internet Newspaper. - Company Overview: The Internet Newspaper News | Blogs | Video | Community | Facebook",
[... omissis ...]
}
Can anybody tell me what's difference between these two opengraph objects?
There is also a slight difference between number of shares and likes. Why?
Update:
During last days graph api returned also object type, so I realized that:
First API call returns an link_stat type object.
Second API call returns a page type object.
In first case shares count should represent sum of:
number of likes of this URL
number of shares of this URL (this includes copy/pasting a link back to Facebook)
number of likes and comments on stories on Facebook about this URL
number of inbox messages containing this URL as an attachment.
In second case like count represents only itself
May somebody confirm me shares count correctness?
For the breakdown between likes, shares and comments (which are added up and used as the "likes" number on the likes button, you're better off using FQL.
If you use OG, something like http://graph.facebook.com/http://example.com will show you:
{
"id": "http://example.com",
"shares": 3
}
... as you've noted above. If you use FQL, you can get the breakdown of each.
<?php
// require the php sdk
require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true,
));
$external_result = $facebook->api(array(
'method' => 'fql.query',
'query' => 'SELECT share_count, like_count, comment_count, total_count, click_count FROM link_stat WHERE url="http://example.com";'
));
echo '<li>'.number_format($external_result[0]['like_count']).' likes, '.number_format($external_result[0]['share_count']).' shares';
echo '<pre>';
print_r($external_result);
echo '</pre>';
?>
This will display something on-screen like:
* 1 likes, 2 shares
Array
(
[0] => Array
(
[share_count] => 2
[like_count] => 1
[comment_count] => 0
[total_count] => 3
[click_count] => 0
)
)
Also, SA now has a Facebook-specific site that may be helpful to you. :) facebook.stackoverflow.com
First one is something that tells you how many likes selected url have.
Using second one you will get information about Page Object through page identifier