"Как подключиться к Facebook, не имея страницы аутентификации, чтобы выполнить скрипт php, который извлекает данные?" - PullRequest
0 голосов
/ 15 мая 2019

мой scypt php подключается к facebbok для извлечения данных, Действительно, каждый раз, когда этот файл выполняется, он запрашивает у меня страницу аутентификации через логин и пароль, но мне нужно поместить этот файл на серверы OVH, чтобы автоматизировать его в соответствии с кронами.

Как заставить этот файл выполнять аутентификацию без запроса входа и пароля, чтобы сервер автоматически выполнял его?

Заранее спасибо

<code><?php

session_start();
require_once __DIR__ . '/src/Facebook/autoload.php'; // download official fb sdk for php @ https://github.com/facebook/php-graph-sdk

$fb = new Facebook\Facebook([
  'app_id' => 'xxxxxxxxxxxxxxx',
  'app_secret' => 'xxxxxxxxxxxxxx',
  'default_graph_version' => 'v3.2',
  ]);

$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];

$permissions = array('email','read_insights');

try {
    if (isset($_SESSION['facebook_access_token'])) 
      {
        $accessToken = $_SESSION['facebook_access_token'];
      } 
    else 
      {
          $accessToken = $helper->getAccessToken();
      }
  } 
catch(Facebook\Exceptions\FacebookResponseException $e) 
  {
      // When Graph returns an error
      echo 'Graph returned an error: ' . $e->getMessage();
      exit;
  } 
catch(Facebook\Exceptions\FacebookSDKException $e) 
  {
      // When validation fails or other local issues
      echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
  }

if (isset($accessToken)) {
  if (isset($_SESSION['facebook_access_token']))
    {
      $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    } 
  else 
    {
        // getting short-lived access token
        $_SESSION['facebook_access_token'] = (string) $accessToken;
          // OAuth 2.0 client handler
        $oAuth2Client = $fb->getOAuth2Client();
        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);

        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        // setting default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

  // redirect the user back to the same page if it has "code" GET variable
  if (isset($_GET['code'])){
        header('Location: ./');}


  // getting basic info about user
  try {
    // GET LIST OF TOKEN PAGES
     // $token = array("EAASb1xN23i4BALzzOUYKWdNAhZAJtubpfiWESFXh1zZBZAGuMEHG49OLZA0QDFBrYsMx3FtRomWeSWrfDnbXsIXhrizpmYCfWHcBqqCrHV5t4NfJXkaPPMR0WpVIJJKLJpN7dZB2CRhCTZC3aQUtAq5UqzxV6VVL6sGXbknTWvhgZDZD");

     $token = array("xxxxxxxx","xxxxxxxxx","xxxxxxxxx" ); 

        // GET LISTS OG PAGE IN MY ACCOUNTS
        $profile_request = $fb->get('/me/accounts?fields=id&limit=50'); 
    $profile = $profile_request->getGraphList();
    // print_r('<br>'.$profile); 
        print_r('<br>');
        // create new array of id to eliminate id unwanted
       $colors = array("yyyy","yyyy","yyyy");

    // get  all id 
      $data3 = array();
      foreach ($profile as $row3) {$data3[]=$row3['id']; }
    // differences id wanted
    $result= array_diff($data3,$colors);




$tabjfh[][] = array();
$longeurMinus= count($result) ;
$longeurToken= count($token);
// print_r('tableau des id :'.$longeurMinus ."<br>");
// print_r('tableau des token:'.$longeurToken."<br>////////////////// <br>");


$i=0 ;
foreach ($result as $row4)
{ 
$tabjfh[$i][0]=$row4 ;
// print_r(" id[".$i."] :".$row4."<br/>");
$i=$i+1   ;
} 

// remplissage  de token
for ($i=0; $i < $longeurToken; $i++) 
{ 
$tabjfh[$i][1]=$token[$i] ;
// print_r("Token : [".$i."] : ".$tabjfh[$i][1]."<br/>");
}


$tabclik=  array();
$tablik=  array();
$tabpositive=  array();
$tabinteraction=  array();
$tabengagement=  array();

// print_r(" <br/> liste token id <br/> ");
// print_r(" <br/>  longueur : ".$longeurMinus) ;
// print_r("<br/>") ; 

for ($i=0; $i <$longeurMinus ; $i++) 
{ 
     $aujourdui= date('Y-m-d');


    // echo "fffffffffffffffff" .$aujourdui;
        // print_r(" <br/>****    token :".$tabjfh[$i][1]." id  ".$tabjfh[$i][0]."<br/>");

      // *************************** Les statistiques disponibles table facebook ****************************



// multiples values : page-id/insights/?metric=page_fan_adds_unique,page_fan_adds
// 150425421686227/insights/?fields=period=day,values&metric=page_fan_adds_unique,page_fan_adds
//EXEMPLE: Le nombre de fans sur toutes les pages
// $response = $fb->get("/".$tabjfh[$i][0]."/insights/page_fans/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);


// nombre de fans
$like = $fb->get("/".$tabjfh[$i][0]."/insights/page_fans/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]); 

        $likerep = $like->getGraphList();
        $likerep =json_decode($likerep);
        $tablik[]= $likerep ;



//Le nombre de clics sur les coordonnées de votre Page et le bouton call-to-action.
$clik = $fb->get("/".$tabjfh[$i][0]."/insights/page_total_actions/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);

        $clikrep = $clik->getGraphList();
        $clikrep =json_decode($clikrep);
        $tabclik[]= $clikrep ; 




// Nombre de fois où les personnes ont réagi de manière positive, en fonction du type d’action: other, like... il faut faire la somme avent de reuperer la valeur
$positive = $fb->get("/".$tabjfh[$i][0]."/insights/page_positive_feedback_by_type/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);  

        $posrep = $positive->getGraphList();
        $posrep =json_decode($posrep);
        $tabpositive[]= $posrep ;

// Le nombre de fois où des personnes ont cliqué sur un de vos contenus:interaction sur la page
$interaction = $fb->get("/".$tabjfh[$i][0]."/insights/page_consumptions/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]);  

        $posint = $interaction->getGraphList();
        $posint =json_decode($posint);
        $tabinteraction[]= $posint ;


// Nombre de fois où les personnes ont interagi avec vos publications à travers des mentions J’aime, des commentaires, des partages et autres:engagement
$engagement = $fb->get("/".$tabjfh[$i][0]."/insights/page_post_engagements/day?since=".$aujourdui."&until=".$aujourdui,$tabjfh[$i][1]); 


        $poseng = $engagement->getGraphList();
        $poseng =json_decode($poseng);
        $tabengagement[]= $poseng ;

        // $connect=mysql_connect('localhost','root','')or die(mysql_erreur());
        //   mysql_select_db('stat2018',$connect)or die(mysql_erreur());
        //   $req2="INSERT INTO `sessions`(`id`, `date`, `session`, `id_client`) values  ('','$a','$b','".$VIEW_ID."')";
        //   mysql_query($req2);


}

       // $tabe =$tabclik[0]->values ;
       // print_r( "ffffffffffffffffff".$tabe[0]->end_time->date);



  } 
  catch(Facebook\Exceptions\FacebookResponseException $e)
   {
          // When Graph returns an error
          echo 'Graph returned an error: ' . $e->getMessage();
          session_destroy();
          // redirecting user back to app login page
          header("Location: ./");
          exit;
   } 
  catch(Facebook\Exceptions\FacebookSDKException $e)
    {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit; 
    }

 echo('<br> <pre>')  ;

// declaration d'un tableau pour faire le remplissage
// $tao =;




// **************** tableau de clik
foreach ($tabclik as $value) 
{    
         //  affichage de tt les valeur détaillées:
     print_r($value[0]);
    // nom de la stat
         print_r($value[0]->name."<br>");

         // peiode
         print_r($value[0]->period."<br>"); 
         $tabe =  $value[0]->values ;

         // valeur 
         print_r($tabe[0]->value."<br>"); 

         // date

         $date = $tabe[0]->end_time->date;
         $date = strstr($date, ' ', true);
         print_r($date."<br>"); 


     // affichage de id  
         $id=$value[0]->id;
         $id = strstr($id, '/', true);
          // 2eme methode: $id = explode("/", $id) ;
     print_r($id."<br>");

     // il faut terminer laccès à tt les varaibles    
         // convertion de type date puis extraction de de year/month/dy
     // $u=$tabe[0]->end_time->date;
     // $date= strstr($u, ' ', true);
     // $new_date = $u->format("Y-m-d "); 
     // print_r($date."<br>");

}  

echo('
'); // ******************** таблица поклонников эхо ('


')  ;
foreach ($tablik as $v) 
{ 
    // nom de la stat
         print_r($v[0]->name."<br>");

         // peiode
         print_r($v[0]->period."<br>"); 


         // valeur 
          $tabe =  $v[0]->values ; 
         print_r($tabe[0]->value."<br>"); 

         // date

         $date = $tabe[0]->end_time->date;
         $date = strstr($date, ' ', true);
         print_r($date."<br>"); 


     // affichage de id  
         $id=$v[0]->id;
         $id = strstr($id, '/', true);
          // 2eme methode: $id = explode("/", $id) ;
     print_r($id."<br>");



} 
echo('
'); // ******************** Таблица положительных эхо ('
')  ;
foreach ($tabpositive as $pos) 
{       
     // print_r($pos[0]);

    // nom de la stat
         print_r($pos[0]->name."<br>");

         // // peiode
         // print_r($pos[0]->period."<br>"); 
         // $tabe =  $pos[0]->values ; 

         // valeur 
        $answer=$tabe[0]->value->answer;
        $claim=$tabe[0]->value->claim;
        $comment=$tabe[0]->value->comment;

        $like=$tabe[0]->value->like;
        $link=$tabe[0]->value->link;
        $other=$tabe[0]->value->other;
        $rsvp=$tabe[0]->value->rsvp;

  if (empty($answer)) {
        $answer=0;
        }
  if (empty($claim)) {
        $claim=0;
        }
  if (empty($like)) {
        $like=0;
        }
  if (empty($like)) {
        $x=0;
        }
  if (empty($link)) {
        $link=0;
        }
  if (empty($other)) {
        $other=0;
        }


  if (empty($comment)) {
        $comment=0;
        }

if (empty($rsvp)) {
        $rsvp=0;
        }

$s= $rsvp + $other + $link + $like + $claim +$answer +$comment;
 print_r($s."<br>"); 

         // date

         // $date = $tabe[0]->end_time->date;
         // $date = strstr($date, ' ', true);
         // print_r($date."<br>"); 


     // affichage de id  
         $id=$pos[0]->id;
         $id = strstr($id, '/', true);
          // 2eme methode: $id = explode("/", $id) ;
     print_r($id."<br>");
         } 
echo('
'); // ******************** таблица взаимодействий эхо ('
')  ;
foreach ($tabinteraction as $valu) 
{ 

  // print_r($valu[0]);
  // nom de la stat
    print_r($valu[0]->name."<br>");
  // valeur 
   $tabe =  $valu[0]->values ; 
   print_r($tabe[0]->value."<br>"); 

  // affichage de id  
  $id=$valu[0]->id;
  $id = strstr($id, '/', true);
  print_r($id."<br>");

} 
echo('
'); // ******************** таблица заданий эхо ('
')  ;
foreach ($tabengagement as $vv) 
{ 
  // print_r($vv[0]);
    // nom de la stat
  print_r($vv[0]->name."<br>");
  // valeur 
    $tabe =  $vv[0]->values ; 
    print_r($tabe[0]->value."<br>"); 

  // affichage de id  
  $id=$vv[0]->id;
  $id = strstr($id, '/', true);
  print_r($id."<br>");

} 
echo('
'); $ tabAll = array (); / ************************************************* ************************************************** ************ / $ i = -1; foreach ($ tabclik как $ value) { $ i ++; // Афиша Тетя Лесных Деталей: // print_r ($ value [0]); // ном де ла стат // print_r ($ value [0] -> name. "
"); // пейод print_r ($ значение [0] -> период "
".); $ tabe = $ value [0] -> values; // Валер // print_r ($ tabe [0] -> value. "
"); // Дата $ date = $ tabe [0] -> end_time-> date; $ date = strstr ($ date, '', true); // print_r ($ date. "
"); // Афиша $ ID = $ значение [0] -> ID; $ id = strstr ($ id, '/', true); // print_r ($ id. "
"); // *********** помолвка $ tab32 = $ tabengagement [$ i]; $ tabe = $ tab32 [0] -> значения; // print_r ($ tabe [0] -> value. "okkkkkk
"); // ************* таблица клик $ Tab29 = $ tabclik [$ я]; $ tab = $ tab29 [0] -> значения; // ************ таблица, как $ tab33 = $ tablik [$ i]; $ t = $ tab33 [0] -> значения; // ************** таблица взаимодействия $ Tab31 = $ tabinteraction [$ я]; $ ta = $ tab31 [0] -> значения; // ************** таблица комм позитив $ Tab30 = $ tabpositive [$ я]; $ Ответ = $ tab30 [0] -> значение-> ответить; $ П = $ tab30 [0] -> значение-> претензии; $ Коментарий = $ tab30 [0] -> значение-> комментарии; $ Как = $ tab30 [0] -> значение-> нравится; $ Ссылка = $ tab30 [0] -> значение-> ссылка; $ Другое = $ tab30 [0] -> значение-> другой; $ RSVP = $ tab30 [0] -> значение-> Rsvp; if (пусто ($ answer)) { $ Ответ = 0; } if (пусто ($ претензия)) { $ Претензии = 0; } if (пусто (как в $)) { $ Как = 0; } if (пусто (как в $)) { $ Х = 0; } if (пусто ($ link)) { $ Ссылка = 0; } if (empty ($ other)) { $ Другое = 0; } if (empty ($ comment)) { $ Коментарий = 0; } if (empty ($ rsvp)) { $ RSVP = 0; } $ s = $ rsvp + $ other + $ link + $ like + $ request + $ answer + $ comment; $ TabAll [] = массив (дата $, $ ID, $ Т [0] -> значение, $ Вкладка [0] -> значение, $ С, $ Таб [0] -> значение, $ Та [0] -> значение ); // il faut terminer laccès à tt les varaibles // преобразование типа даты извлечение года / месяца / года // $ u = $ tabe [0] -> end_time-> date; // $ date = strstr ($ u, '', true); // $ new_date = $ u-> format ("Y-m-d"); // print_r ($ date. "
"); } foreach ($ tabAll as $ valuooe) { $ connect = new mysqli ('server', 'users', 'psw', 'bdd'); print_r ("date". $ valuooe [0]. "
ID:
". $ valuooe [1]. "
like". $ valuooe [2]. "
clik". $ valuooe [3]. "
положительные комментарии". $ valuooe [4]. "
engagement". $ valuooe [5]. "
взаимодействие". $ valuooe [6]. "
«); $ req2 = "INSERT INTO` facebook` (`id`,` date`, `id_client`,` jaime`, `clics`,` potsitiveact`, `engagement`,` взаимодействия`) VALUES ('', '". $ Valuooe [0]."', '$ Valuooe [1]', ". $ Valuooe [2].", ". $ Valuooe [3].", ". $ Valuooe [ 4] "" $ valuooe [5] "" $ valuooe [6] ")".....; mysqli_query ($ подключения, $ req2); mysql_close (); } эхо ( ''); / ***************************************************** ************************************************** ******** / } еще { // заменить URL вашего сайта так же, как он добавлен в developers.facebook.com/apps, например. если вы использовали http вместо https и использовали версию вашего сайта без www или www, то вы должны добавить то же самое здесь $ loginUrl = $ helper-> getLoginUrl ('https://www.mondomain.com', $ permissions); // echo ' Войти через Facebook! '; заголовок ('Location:'. $ loginUrl); // echo 'getLoginUrl() . '"> Login '; } пытаться { // Возвращает объект `FacebookFacebookResponse` } catch (FacebookExceptionsFacebookResponseException $ e) { echo 'Graph вернул ошибку:'. $ E-> GetMessage (); выход; } catch (FacebookExceptionsFacebookSDKException $ e) { echo 'Facebook SDK вернул ошибку:'. $ E-> GetMessage (); выход; } // функция get token автоматическая // функция generate_token ($ args) { // $ r = json_decode (file_get_contents ("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // получаем долгоживущий токен // $ longtoken = $ r-> access_token; // $ r = json_decode (file_get_contents ("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // получить идентификатор пользователя // $ userid = $ r-> id; // $ r = json_decode (file_get_contents ("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // получить постоянный токен // foreach ($ r-> data as $ d) // if ($ d-> id == $ args ['pageid']) // return $ d-> access_token; //} ``
...