Я знаю, что на этом есть много заданий, но все, кажется, нужно, чтобы пользователь вошел в систему … Я использовал фрагменты кода из всех возможных уроков, но ни один из них не работает.
Вот сценарий: у меня есть фото сообщество, работающее на PHP, и у меня есть страница поклонника на Facebook. Когда изображение на главном сайте собирает определенное количество голосов, функция запускается, чтобы разместить ссылку на изображение на стене Facebook. Ссылка (сообщение) размещена как страница, а не как админ. Администратор, конечно, не будет в сети … Возможно ли это сделать в эти дни? У меня есть последний PHP SDK, и это функция, которую мне нужно, чтобы работать в автономном режиме, прежде чем вставлять на главный сайт.
ОК. Этот код отлично работает, если я зарегистрирован в Facebook, но если нет, он не опубликует … Приложение имеет все необходимые и ненужные разрешения для взаимодействия с моей страницей на моем (административном) имени. Любые идеи будут оценены.
<?php //facebook application $fbconfig['appid' ] = "1848740815xxxxx"; $fbconfig['secret'] = "a5aa62bb3a8ddcb98d5d9dbe4a3xxxxx"; $fbconfig['pageid'] = "121409594622865"; $user = null; //facebook user uid try{ include_once "facebook.php"; } catch(Exception $o){ error_log($o); } // Create our Application instance. $facebook = new Facebook(array( 'appId' => $fbconfig['appid'], 'secret' => $fbconfig['secret'] )); //Facebook Authentication part $user = $facebook->getUser(); $loginUrl = $facebook->getLoginUrl( array( 'scope' => 'offline_access,publish_stream' ) ); $logoutUrl = $facebook->getLogoutUrl(); $pageid = $fbconfig['pageid']; if ($user) { try { $page_info = $facebook->api("/$pageid?fields=access_token"); if( !empty($page_info['access_token']) ) { $args = array( 'access_token' => $page_info['access_token'], 'message' => 'This is a test feed message', 'link' => 'http://www.fotodvor.com', 'picture' => 'http://img.ruphp.com/php/1319971991.jpg', 'name' => 'Test Picture', 'description'=> 'Description of the test picture!' ); $post_id = $facebook->api("/$page_id/feed","post",$args); } } catch (FacebookApiException $e) { error_log($e); $user = null; } } ?>
заранее спасибо
здесь приведен модифицированный скрипт с пояснениями, скорректированными на изменения в API
<?php //facebook application $fbconfig['userid'] = "5332534xx"; $fbconfig['appid' ] = "184874081548xxx"; $fbconfig['secret'] = "a5aa62bb3a8xxxb98d5d9dbe4a368xxx"; $fbconfig['pageid'] = "121409594622xxx"; $fbconfig['token1'] = "AAACoJFn1eLABAKpL9W0nZBrw0e3zzdSNVsTg6FWDMhSnOUeinjid6yAQ2z9JDxxxxxxc1hMHBC3GG18KZBwppGDehWMEwLe56wagZDZD"; // step 1 - returned by loggin in. $fbconfig['token2'] = "AAACoJFn1eLABAC2Q8OLnqxjUSKzdn9CzaXhy8nsG61vzp2ufePr5iwHZA7TM7Ibxxxxxxyf868O04FeBxMrIo0RCumrNaB78hZAp2uRrbVlGVPXP"; // step 3 - this is a page access token as page $fbconfig['my_ulr'] = 'http://'.$_SERVER['SERVER_NAME']; include_once "facebook.php"; // Create our Application instance. $facebook = new Facebook(array( 'appId' => $fbconfig['appid'], 'secret' => $fbconfig['secret'], )); // 1. we need to get a user access_token first, (old approach with offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api) // run the file and see step 1 instructions. //offline_access has been deprecated in May 2012 and therefore excluded from the request below $token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,publish_stream&response_type=token"; echo "<h2>This little working example should give you a working non expiring token to use in your PHP script to enable it to post to your Facebook page as a page and not as a user</h2><br>"; echo "1 - Click on the link below (this redirects to uri with token attached). Log in as admin of the page you are trying to post to. Then copy the token you will get in the address bar to be used in the script in step 2.<br>"; echo "<a href='".$token_url1."' target='_blank'>$token_url1</a>"; //2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info. $token_url2 = "https://graph.facebook.com/me?access_token=".$fbconfig['token1']; $me = json_decode(file_get_contents($token_url2), true); //echo "<hr><br>this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE so this is just for the heck of it...<br>"; //echo "<a href='".$token_url2."' target='_blank'>$token_url2</a>"; //echo "<hr>this is a raw server reply<br>"; //echo d($me['id'])."<hr>"; //new changes to API - https://developers.facebook.com/roadmap/offline-access-removal/#extend_token $new_token_url2 = "https://graph.facebook.com/oauth/access_token?client_id=".$fbconfig['appid']."&client_secret=".$fbconfig['secret']."&grant_type=fb_exchange_token&fb_exchange_token=".$fbconfig['token1']; $new_token2 = file_get_contents($new_token_url2); $vars = explode('&', $new_token2); //d($vars); echo "2. We now obtain a long lasting token (based on <a href='https://developers.facebook.com/roadmap/offline-access-removal/#extend_token' target='_blank'>this</a>) <br><br>We send the request<br>'".$new_token_url2."'<br><br>and the reply is:<br>'".$new_token2."'<br><br>"; //http://developers.facebook.com/tools/explorer?method=GET&path=533253476&accounts&access_token=AAACoJFn1eLABAFZBftV0vtlBiHKA7ZAIrukrriyp2coWSavj3L4CbfJ9r3WY76IPi7pwUgt3wsubaI4iBbsr663PrbNyaLdZAhLxneOLAZDZD echo"So now open this page <a href='http://developers.facebook.com/tools/explorer' target='_blank'>http://developers.facebook.com/tools/explorer</a>, then put the token above to put into the 'Access Token: ' field and press enter... You will need to press 'accounts' link to the right from the response window. <br>you will see another response and copy your page access token from there. Automating this task into one query did not work... I tried many times.. the token returned IS NOT THE SAME as you would get following the instructions step by step... This approach does not work - <br>"; echo "http://developers.facebook.com/tools/explorer?method=GET&path=".$me['id']."%2Faccounts&".$vars[0]."<BR><BR><BR>"; echo "Please check it here <a href='http://developers.facebook.com/tools/debug' target='_blank'>https://developers.facebook.com/tools/debug</a> and make sure it never expires..."; $pageid = $fbconfig['pageid']; try { //Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above to check the functionality /* $page_info = $facebook->api("/$pageid?fields=access_token&".$new_token2); //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so echo "<hr>this is a page_info breakdown"; d($page_info); echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>"; echo $page_info['access_token']; */ $args = array( 'access_token' => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook 'message' => 'This is a test feed message', 'link' => 'http://www.test.com', 'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png', 'name' => 'Test Picture', 'description'=> 'Description of the test picture!' ); //uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent... //$post_id = $facebook->api("/$pageid/feed","post",$args); echo "<hr>This will show once the message is posted - post_id is: <br>"; d($post_id); } catch (FacebookApiException $e) { error_log($e); } function d($d){ echo '<pre>'; print_r($d); echo '</pre>'; } ?>
Кажется, я нашел ответ. После долгого времени тестирования это решение: относитесь к этому как к небольшому образцу / руководству для тех, кто не знаком с этим. Код и вывод имеют всю необходимую информацию:
<?php //facebook application $fbconfig['appid' ] = "184874081XXXXXX"; $fbconfig['secret'] = "a5aa62bb3a8ddcb98d5d9dbe4aXXXXXX"; $fbconfig['pageid'] = "121409594XXXXXX"; $fbconfig['token1'] = "AAACoJFn1eLABAHn92JsWIHZCESQWXmkXZBCedXXXXXXcyUG5vrCYZBXcgsNHN0IUvBj0Sec9vOxVsUgtMHflXXF2cbOF1oZD"; // step 1 - returned by loggin in. $fbconfig['token2'] = "AAACoJFn1eLABAAUAPthH5DaZCmasZCh5DGGSnZXXXXXXSDh8v1WYYUEWJYuFdua9E5EfJ63c03lfwXrVJbP4VQj35aVcztFgKRYZAheHPNfDeLfbkPys"; // step 3 - this is a page access token as page $fbconfig['my_ulr'] = 'http://'.$_SERVER['SERVER_NAME']; include_once "facebook.php"; // Create our Application instance. $facebook = new Facebook(array( 'appId' => $fbconfig['appid'], 'secret' => $fbconfig['secret'], )); // 1. we need to get a user access_token first, offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api) //run the file and see step 1 instructions. $token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,offline_access,publish_stream&response_type=token"; echo "1 - this redirects to uri with token attached. Copy and paste this line into your browser and log in as admin of the page you are trying to post to. Make sure you change redirect_uri to your own. Then copy the token you will get in the address bar to be used in the script in step 2.<br>"; echo $token_url1; //2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info. $token_url2 = "https://graph.facebook.com/me/accounts?access_token=".$fbconfig['token1']; $app_token2 = file_get_contents($token_url2); echo "<hr><br>2 - this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE<br>"; echo $token_url2; echo "<hr>2 - this is a raw server reply<br>"; d($app_token2); $pageid = $fbconfig['pageid']; try { //Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above $page_info = $facebook->api("/$pageid?fields=access_token"); //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so echo "this is a page_info breakdown"; d($page_info); echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>"; echo $page_info['access_token']; $args = array( 'access_token' => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook 'message' => 'This is a test feed message', 'link' => 'http://www.test.com', 'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png', 'name' => 'Test Picture', 'description'=> 'Description of the test picture!' ); //uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent... //$post_id = $facebook->api("/$pageid/feed","post",$args); echo "<hr>This will show once the message is posted - post_id is: <br>"; d($post_id); } catch (FacebookApiException $e) { error_log($e); } function d($d){ echo '<pre>'; print_r($d); echo '</pre>'; } ?>
Вы должны использовать токен доступа к странице, если я понимаю, что вы пытаетесь сделать правильно – это токен, который позволяет вашему приложению действовать как страница, а не как один из админов. Это доступно в конечной точке /me/accounts
когда у вас есть токен доступа пользователя с разрешением manage_pages
– если вы используете этот токен доступа для публикации в /{page id}/feed
(или фотографии и т. Д.), Он будет отображаться как страница