Facebook Open Graph - post to all approved users feeds - php

I'm struggling to get to grips with posting a feed item to all the members of an approved application.
Within the application settings for the user it is stating that the application has permission to post to the wall but I can only achieve this if that user is currently logged in to facebook. Obviously I would like this to function so that any items I uploaded are posted to all the members of the application at any one time.
I am using the Facebook PHP SDK from http://github.com/facebook/php-sdk/ and currrently my code is as follows:
require 'src/facebook.php';
//Generates access token for this transaction
$accessToken = file_get_contents("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=MyAppId&client_secret=MySecret");
//Gets the full user details as an object
$contents = json_decode(file_get_contents("https://graph.facebook.com/SomeUserId?scope=publish_stream&" . $accessToken));
print_r($contents);
if ($facebook->api('/' . $contents->id . '/feed', 'POST',
array(
'title' => 'New and Improved, etc - 12/03/2010',
'link' => 'http://www.ib3.co.uk/news/2010/03/12/new-and-improved--etc',
'picture' => 'http://www.ib3.co.uk/userfiles/image/etc-booking.jpg',
'scope' => 'publish_stream'
)
)==TRUE) {
echo "message posted";
} else {
echo "message failed";
}
The output from $contents shows the expected user details but nothing relating to the permissions for my application. Am I missing a trick here?
Then using the $facebook->api() function I am receiving a
200 - Permissions error
. The application does not have permission to perform this action.
This is driving me a little potty as I suspect I'm missing something straightforward with the authorisation but what?
Many thanks in advance for an assistance offered.

I had the same problem yesterday. Finally I figured out that, although I had set checked the "permission to post to wall", I had to do this step also:
https://graph.facebook.com/oauth/authorize?client_id=XXXXXXX&scope=publish_stream&redirect=http://back.to.your.app/
There, the end-user will be served with the familiar Facebook "Allow this application to access your information?" dialog. After allowing, it will come back to your app, which then will have the proper permissions.
Hope this helps!

Related

Bigcommerce customer login api (single sign-on) invalid login issue

I'm new to bigcommerce and jwt tokens. I'm trying to get the customer login api to work on a trail store. But have not been able to successfully login a customer automatically.
I got it to work once or twice, but now it doesn't work anymore, and an unable to figure out the odd behavior since nothing changed with the code. I've tried googling if anyone else has had issues with the customer login api but have found nothing.
I've gone thru the tutorial on https://developer.bigcommerce.com/api/v2/#customer-login-api and copied the example provided.
Is there something I'm missing with the code below?
I've gone to developer.bigcommerce.com and created a draft app.
I got the Client ID and Client Secret from the draft app.
I've gone into my trial store and successfully installed the draft app.
I've tested this page on SSL as well.
Could it be because it's a trail store and it will only work if it's a real store?
Thanks.
Here is the php code below:
include "vendor/autoload.php";
use Bigcommerce\Api\Client as Bigcommerce;
use Firebase\JWT\JWT;
function getCustomerLoginToken($id, $redirectUrl = '', $requestIp = '') {
/*
if (empty(self::$client_secret)) {
throw new Exception('Cannot sign customer login tokens without a client secret');
}
*/
$payload = array(
'iss' => '#MyApp1's Client ID#',
'iat' => time(),
'jti' => bin2hex(random_bytes(32)),
'operation' => 'customer_login',
'store_hash' => '#Store Hash#',
'customer_id' => $id
);
if (!empty($redirectUrl)) {
$payload['redirect_to'] = $redirectUrl;
}
if (!empty($requestIp)) {
$payload['request_ip'] = $requestIp;
}
return JWT::encode($payload, "#MyApp1's Client Secret#", "HS256");
}
$jwt = getCustomerLoginToken(1);
header("Location: " . 'https://store-#Store Hash#.mybigcommerce.com/login/token/' . $jwt);
exit();
There are a couple of constraints that can cause errors:
The app must be installed on the store (seems like you're all good here - you can also test with an API token created locally in the store - https://support.bigcommerce.com/articles/Public/Store-API-Accounts/)
The app must have the Login OAuth scope
The JWT URL must be visited within about 30 seconds, or it won't work.
The computer/server that's generating the JWT needs to have a clock that's synchronized, otherwise your IAT value will appear to have been created more than 30 seconds ago or even in the future which will fail.
The URL can only be visited exactly once - if anything runs a GET request against it other than the intended end user's browser, it won't work. For example, if you send the URL in a Slack message, slack will try to preview the link by visiting it and therefore invalidate it.
It's good to double-check that your JWT is valid at https://jwt.io/
BigCommerce support has access to logs which can shed more light on the situation if you've ruled out the above.
Hope this helps!
do not need app client_id and Secret code , you need to api's client_id and secret code

Create a Facebook App that can post to a page I am an admin of

As part of the website I am working on, I need to be able to post directly to the wall of my clients Facebook Page.
I have created an App and am successfully posting to my own dummy profile by simply using:
$request = new FacebookRequest(
$session, 'POST', '/me/feed', array(
'link' => 'my_url',
'message' => 'my_message'
);
Now I need to modify this to post to my clients page, im assuming I cant just change 'me' to by their page ID because that would be a massive security flaw so I need to get permission somehow to post to their page. I am an admin for the page, how can I do this? Or do I actually need to be logged in with the user account that created the page?
I have looked all around in the developer section at creating an app but there doesn't seem to be any way of creating an app for a different account.
Any advice would be greatly appreciated on this.
Many thanks
In order to post to a Facebook page, you need to go through a two steps process -
login as the user using the extended user token,
get the user's token for the page
post to the page using the page's token.
The following code should be able to post a message to your page. I HAVEN'T DEBUGGED IT since it is simplified from my own web site :-) Don't forget to include the Facebook SDK files:
function extract_access_token_of_facebook_page_by_id($array_of_all_user_pages,$page_id){
$num_of_pages=count($array_of_all_user_pages['data']);
$the_page_token="";
for ($i=0; $i<$num_of_pages; $i++){
if ($array_of_all_user_pages['data'][$i]['id']==$page_id){
$the_page_token=$array_of_all_user_pages['data'][$i]['access_token'];
}
}
return $the_page_token;
}
$facebook = new Facebook(array(
'appId' => $YOUR-APP-ID,
'secret' => $YOUR-APP-SECRET,
));
try
{
$facebook->setAccessToken($THE-USER-TOKEN);
$page_id = YOUR-PAGE-ID;
$fanpage_access_token=extract_access_token_of_facebook_page_by_id($facebook->api("/me/accounts"),$page_id);
$args = array();
$args['access_token'] = $fanpage_access_token;
$args['message'] = "THE TEXT YOU WANT TO POST";
$api_url="/".$page_id."/feed";
$api_response = $facebook->api($api_url, 'post', $args);
}
catch (FacebookApiException $e)
{
echo 'Error facebookservice'.$e;
}
Please look into Application developer section. It will help you. Create on developer account and you will be able to access page.
you code is for old sdk version i think, it not work for me : Fatal error: Class 'Facebook' not found

Facebook App Notifcations PHP

I've been reading through the facebook developer docs and i'm a little confused, I want to re-engage a load of users that have gone a little stale really by giving them a little nudge regarding their inactivity on our app...
What is the current "best practice/latest way" of doing this, it seems to be via the notifications API?
https://developers.facebook.com/docs/app_notifications/#imp
If i'm correct can someone give me a couple of pointers for a PHP implementation of this, essentially it would be a cron running once a month/every two weeks wizzing through users who haven't logged in for a while and prodding them.
Thanks
Marc
Well since nobody responded to this heres a simple working solution that I figured out from the docs. To notify a user they have to authorised your app.
$book = new Facebook((array(
'appId' => 'XXXXXX',
'secret' => 'XXXXXX',
'grant_type' => 'client_credentials')
));
$vars = array(
"access_token" => $book->getAppId().'|'.$book->getApiSecret(),
"href" => "index.php",
"template" => "Some text to send up to 180 characters",
"ref" => "This is what shows up in insights so you can track responses"
);
$post = $book->api('/' . $userid . '/notifications/', 'post', $vars);
You can insert user names into template by surrounding the facebook user id with {} ie:
"{12345} would like to play some game with you." . It will throw an exception though if the uid refers to a user that hasn't authed your app.
Href automatically gets your canvas url inserted infront of it so no need to full domain/path.
ref is used in the insights interface so you can see which notifications are generating traffic!
Thats it, very simple to re-engage those users who seem to have disappeared!
Cheers
Marc

Publish Stream from the application - for non logged in user, using Graph API, php SDK

Using graph api publish_stream permission: together with offline_access permission:
As described here and here. However for some reason one of the following two things are happening:
I am trying to post to a facebook user which is not currently logged in, following an action of a user which is curently logged in (e.g. telling user #1 that user #2 visited their farm in farmville, but user #1 is not logged in, while user #2 is. And they are not necessarily friends).
When I tried this using the following code, the post was not created when users #1 and #2 were not friends (first problem), and when they were friends, the post was being created, but seemed like user #2 was posting it on user #1's wall (second problem - this is NOT what I am trying to do, I want it to be anonymous).
See the first code I used:
$post_id = $facebook->api('/' . $user1_id . '/feed/', 'post', array(
'message' => 'Someone just visited your farm',
'link' => 'http://example.com',
'picture' => 'http://example.com/img/picture.jpg',
'caption' => 'Visit farms!'
));
So I tried to use the access token of user #1, which he gave me when he was logged in, and the application is supposed to be able to post on their wall even when they are offline (even without offline_access permission - see here facebook's documentation: "you can publish... without requiring offline_access". At any rate, when I am adding the access_token to the array as a parameter (see the code below), no post is being created at all:
$post_id = $facebook->api('/' . $user1_id . '/feed/', 'post', array(
'access_token' => $user1_access_token,
'message' => 'Someone just visited your farm',
'link' => 'http://example.com',
'picture' => 'http://example.com/img/picture.jpg',
'caption' => 'Visit farms!'
));
What should I do?
gain, I am simply trying to publish to user's wall that is NOT logged in, but who gave me the publish_stream permission, a post from the application, not any other user, telling this user that someone (anonymously) has "visited their farm" (or created some action associated with them).
Thanks everyone.
this is just a recommend & i'm not sure this be the answer
Destroy all of the sessions (or use your browser in private mode -for Firefox )
& then visit sender page Like this
example.com/postfarm.php
maybe when you visit the page normally the app gets your access_token & tries to post as you
PS:better way
use this code & you dont need to destroy sessions anymore
include_once ('src/facebook.php');/// include sdk
////// config The sdk
# $facebook = new Facebook(array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXXXXXXXX',
));
$facebook->destroySession();
try{
$post=$facebook->api('USER_ID/feed/','POST',array(
'message' => '$message',
'link'=>'http://apps.facebook.com/xxxxxxx/link.php?link=',
'picture'=> 'XXXXXXXXXX',
'name'=>'XXXXXX',
'description'=>'yes',
));
}
catch(FacebookApiException $e) {
echo $e->getType();
echo '<br />';
echo $e->getMessage();
}
For the "someone did something in a game and it's your turn", I believe what you're looking for is requests 2.0, specifically the "App to user" communication.
from: https://developers.facebook.com/docs/requests/
App to User Requests can be used to re-engage a user in your app and
can only be sent to users that have installed the app. For example,
notifying a user that something has changed since their last visit,
"10 of your friends are now online".
App to User Request are sent via the Graph API, for more information
see the apprequests docs. App to User Requests are only available for
Canvas apps, not websites, as accepting a request will direct the user
to the Canvas Page URL of the app that sent the Request.
from: https://developers.facebook.com/docs/guides/canvas/
App-generated requests: These requests can be initiated and sent only
to users who have authorized your app. You should use these requests
to update the bookmark count to encourage a user to re-engage in the
app (e.g., your friend finished her move in a game and it’s now your
turn).

Retrieving my Facebook fan page wall posts via PHP now gives "An access token is required to request this resource."

This is a rather infuriating problem. We had code that was working perfectly fine for months and now, all of the sudden, it doesn't. The code just used this url to grab the wall posts we were making on our fan page and showed them on our site. http://graph.facebook.com/[our number]/feed?limit=10
Now it doesn't work and I've spent a ridiculous number of hours sifting through search results on this issue. Unfortunately, everything I find seems to be referring to Facebook apps and not fan pages. I can't stop seeing how I need to authenticate it using my secret key, but I can't find anything that shows me what my fan page's secret key is or if one even exists. I can't, for the life of me, get this thing working and I can't figure out why it just randomly stopped working in the first place.
Here's the error we get:
{
"error": {
"type": "OAuthException",
"message": "An access token is required to request this resource."
}
}
EDIT: So thanks much to Frank Farmer for finding that post, the problem is needing an access token, which I can't find ANY solution to getting ANYWHERE.
The way that I was able to do this was by:
Creating a new facebook application
Logged into Facebook with the user that is an admin for the Facebook Page
Opened up a request for permissions for the application
https://www.facebook.com/dialog/oauth?client_id='the_application_id'&redirect_uri=http://your_redirect_uri/&scope=email,read_stream,user_birthday,user_about_me,user_likes,read_stream,user_education_history,user_work_history,user_groups,user_hometown,user_religion_politics,user_location,user_online_presence,user_relationships,user_status,user_website,read_friendlists,offline_access,manage_pages,ads_management,publish_stream
Your redirect URI MUST match what you have set into the application settings in your facebook application.
I basically granted access to everything for this application, the main thing you need to make sure of is 'manage_pages'
-After that you will need to copy the 'code=xxxxxx' portion of the link that you are forwarded onto after accepting the permissions request. You can THEN request an access_code for the user, once you have that, you can get the Facebook page posts that the user is an admin to.
https://graph.facebook.com/oauth/access_token?client_id='the_application_id'&redirect_uri=http://your_redirect_uri/&client_secret='the_code_from_above'
It will then respond with an access code!
https://graph.facebook.com/feed?access_token='your_access_token'
Below is some sample code you can use with the PHP facebook SDK:
define('APP_ID', 'your_app_id');
define('APP_API_KEY', 'your_app_api_key');
define('APP_SECRET', 'your_app_secret');
$fb = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => false
));
$fb_user_id = 'user_id_of_person_that_has_page_admin_rights';
$access_token = urlencode('your_access_token_you_received');
try {
$user = $fb->api('/'.$fb_user_id,'GET',array('access_token'=>$access_token));
$accounts = $fb->api('/'.$fb_user_id.'/accounts','GET',array('access_token'=>$access_token));
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
echo "<strong>User Details:</strong><br />";
foreach($user as $key => $value){
echo ucwords(str_replace("_"," ",$key)).": ".$value."<br />";
$fb->api('/feed','POST',array('access_token'=>$access_token,'id'=>$user_id,'message'=>'Add a post to the user's wall'));
}
echo "<br /><strong>Accounts Details:</strong><br />";
foreach($accounts['data'] as $account){
foreach($account as $key => $value){
echo ucwords(str_replace("_"," ",$key)).": ".$value."<br />";
}
try {
$posts = $fb->api('/'.$account['id'].'/posts','GET',array('access_token'=>$account['access_token']));
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
echo "<br /><strong>-- Posts for this account:</strong><br />";
foreach($posts['data'] as $post){
foreach($post as $key => $value){
echo ucwords(str_replace("_"," ",$key)).": ".$value."<br />";
}
echo "<br />";
}
}
Yeah, it requires a token now. They announced this via their blog.
http://developers.facebook.com/blog/post/509/
Breaking change: Graph API PROFILE_ID/feed and PROFILE_ID/posts requires access_token
The Graph API PROFILE_ID/feed/ for a Page, Application, User or Group and PROFILE_ID/posts for a Page or User will now require a vaild access_token to access the wall or posts of the corresponding object (where previously no access_token was required).
Looks like they only gave a week notice.
You should subscribe to the RSS feed for their dev blog. They pull stuff like this all the time, although usually they give a little more notice.
After you have your personal access token, run:
https://graph.facebook.com/me/accounts?access_token=token
where 'token' is your access token. This will show you all the access tokens for the pages you have access to. Now use that page access token to post to:
'/page_username_id/feed'
where page_username_id is either the page id or the url username.
Hope this helps.
Skye
The URL
https://graph.facebook.com/oauth/access_token?client_id='the_application_id'&redirect_uri=http://your_redirect_uri/&client_secret='the_code_from_above'
is not true. the Client Secret is your App Secret. You need a extra argument, for example:
https://graph.facebook.com/oauth/access_token?client_id=[YOUR-APP-ID]&redirect_uri=http://your-uri(like in the app config)/&client_secret=[your-app-secret]&code=[code-from-above]

Categories