Get page_access_token - facebook-page

As I knew there is a way to get access token via https://developers.facebook.com/tools/explorer.
Is there other way to get page_access_token by API?
I want to post request to add app to facebook page but it require a page_access_token as below:
https://graph.facebook.com/myPageId/tabs/?app_id=myAppId&access_token=myPageAccessToken
Thanks.

Yes you can. The current user must be an administrator of this page;
extended permission needed - manage_pages
refer url: https://developers.facebook.com/docs/reference/api/page/
Try this:
$config = array(
'appId' => FB_APP_ID,
'secret' => FB_SECRET_KEY,
'cookie' => true // enable optional cookie support
);
$facebook = new Facebook($config);
// See if there is a user from a cookie
$user = $facebook->getUser();
$params = array(
'scope' => 'manage_pages',
'redirect_uri' => FB_APP_URL,
);
$loginUrl = $facebook->getLoginUrl($params);
<script> window.top.location.href = '<?php echo $loginUrl ?>'; </script>

Related

How to connect WordPress / WooCommerce to a REST API with PHP?

I am trying to write my first REST API with PHP. We want to send shipping data to the shipping company and get labels for printing in return. The shipping company has given me test api credentials.
So I started to write a plugin with this code inside:
$url = "https://mywebsite/endpoint/";
$username = "myusername";
$password = "mypassword";
$data = array(
'key1' => 'value1',
'key2' => 'value2'
);
$response = wp_remote_post( $url, array(
'body' => $data,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
),
)
);
var_dump($response); // not being called
When I run this code, I get a white screen with no error message, the last line with var_dump($response) is not being called. I am a bit stuck here because I se no success and no error...what could it be? Why this behaviour of the remote server? Does it mean "sorry, wrong credentials" or "data has the wrong format"? I have the feeling that the server doesn't even notice that I'm trying to contact him...
I tried a number of other variatons of the above code that I found somwehere online, and also outside of WordPress, but no success.
The shipping company gave me a documentation. It says:
HTTP Method: POST
Authentication Header: Basic Authentication (user name/ password)
so I thought I could do no wrong when trying that. Hm.
I found a solution, so I can share it here with you.
I installed the free Software Postman and created a simple POST query there. After entering $url, $username and $password I ran a query and it worked well. the good thing abort Postman is that it creates code snippets for you. "very_long_cryptic_string" is obviously created from $username and $password. The PHP for my case goes like this, and it works:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic very_long_cryptic_string'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Google Calendar API in production

Can I ask you if there is anybody who can answer me a question about Google Calendar API? I have generated credentials and on localhost it works pretty fine. I just want to return like 100 upcoming events ($service->events->listEvents($calendarId, $optParams) but this same code on production doesn`t works, it returns 500 Internal Server Error especially on this piece of code. Any advice how to continue?
this is the piece of code and it breaks on the first commented line
<?php
require './vendor/autoload.php';
$client = new Google_Client();
$gazza = new GuzzleHttp\Client([
'verify' => './cacert.pem'
]);
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('./credentials-calendar-old.json');
$client->setAccessType('offline');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 1000,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 1000,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
Thanks a lot,
Alex
Try to remove the code below, as far as I know this code is just for localhost, to force https.
$gazza = new GuzzleHttp\Client([
'verify' => './cacert.pem'
]);

PHP-SDK publish link not available for public

When publishing a new link, using php sdk, the link is only available for logged user, it's not publish as public.
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
setcookie('cod_eventos', $_POST['cod_eventos']);
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
setcookie('userlogin', 1);
echo ("<script>window.open('".$login_url."')</script>");
} else {
$page_id = $page_id;
try {
$access_token = $facebook->getAccessToken();
$attachment2 = array(
'access_token' => $access_token
);
$page = $facebook->api('/me/accounts', 'get', $attachment2);
} catch (FacebookApiException $e) {
echo 'Unable to get page access token';
}
$privacy = array(
'value' => 'EVERYONE',
);
$attachment = array(
'access_token' => $page['data'][0]['access_token'],
'name' => 'Test',
'link' => 'http://www.facebook.com/',
'description' =>'Facebook',
'privacy' => json_encode($privacy),
);
try {
$facebook->api('/' . $page_id . '/feed', 'POST', $attachment);
echo '<div class="gestor_ficheiros_tipo">Event publish Facebook</div>';
}
catch (FacebookApiException $e)
{
echo '<div class="gestor_ficheiros_tipo">'.$e->getMessage().'</div>';
}
After running this the content is publish, but not view-able by un-registered facebook users
Apparently, despite what the API documentation says, the privacy setting is 'privacy_type', not 'privacy'. I found that out here on SO I think, but closed the tab so I can't immediately share the link.
Check the settings on your app as well - I think it's the 'Visibility of app and posts' setting defaults to 'Friends' instead of 'Public'. Maybe that'll do it?
I found out what was the problem, I was using facebook app in sandbox mode... :(. Once I've changed it started working perfectly

Facebook page tab changing

I want to change tab name of a facebook page.
Here is the code I am using
<?php
session_start();
$pageId=$_SESSION['pageid'];
require('sdk/facebook.php');
$appId = 'My App Id';
$secret = 'My App Secret';
$pageId = $pageId;
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
));
$access_token=$facebook->getAccessToken();
if($facebook->setAccessToken($access_token))
{
$page_tabs=$facebook->api($pageId . '/tabs');
$name=$page_tabs['data']['0']['name'];
$tabid=$page_tabs['data']['0']['id'];
if($name=="MyTab")
{
$facebook->setAccessToken($access_token);
$facebook->api($tabid, 'POST', array(
'custom_name' => 'MyTab New Name',
'access_token'=>$_SESSION['token']
));
}
echo "OK";
}
?>
But I am getting error for Oauth Exception , it says you need to supply the accesstoken for this
Please Help
you need few changes
Instead of this
'access_token'=>$_SESSION['token']
use this
//get the user access token
$token = $facebook->getAccessToken();
echo "</br>" . 'User Access_Token:' . $atoken;

How to get the list of groups and pages of an user with graph api?

I'm using graph api but I can't list the pages and groups of an user.
First, for the permissiones, in the scope, I use:
'scope' => 'publish_stream,user_groups,user_about_me,user_interests,friends_groups,friends_interests,friends_about_me',
and then, when I try the next code, the value of $ct is 0
<?php
session_start();
require 'config.php';
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => $fb_app_id,
'secret' => $fb_secret,
'cookie' => true,
));
$user = $facebook->getUser();
$info = $facebook->api( '/me/groups', 'GET', array( 'access_token=' => $access_token ) );
$ct = count( $info['data'] );
echo $ct;
?>
This may be a silly question, but are you sure:
The user is actually in some groups (many users are not)
You definitely have the user_groups permission (check with a call to /me/permissions)

Resources