2015-01-12 5 views
0

Google 애드 센스 API를 조합하여 작동하는 수익을 얻었습니다. 그러나 로그인하지 않고 백그라운드에서 실행하고 싶습니다. 실행될 때마다 로그인하도록 요청합니다. 토큰을 저장할뿐만 아니라 오프라인으로 설정했습니다. 왜 내가 계속 로그인을 요구하는지 잘 모르겠다. GoDaddy에서 야간에 cron 작업을 실행하고있다. 코드는 다음과 같습니다.Google 애드 센스 API가 매번 로그인을 요청합니다.

<?php 
include('config.php'); 

require_once 'templates/base.php'; 
session_start(); 

set_include_path('/path/to/clientlib' . PATH_SEPARATOR . get_include_path()); 
set_include_path('/path/to/clientlib' . PATH_SEPARATOR . get_include_path()); 
require_once 'Google/Client.php'; 
require_once 'Google/Service/AdSense.php'; 
require_once 'Google/Service/AdSense.php'; 
// Autoload example classes. 

include 'examples/GetAllAccounts.php'; 
include 'examples/GetAccountTree.php'; 
include 'examples/GetAllAdClients.php'; 
include 'examples/GetAllAdUnits.php'; 
include 'examples/GetAllCustomChannelsForAdUnit.php'; 

include 'examples/GetAllCustomChannels.php'; 
include 'examples/GetAllAdUnitsForCustomChannel.php'; 
include 'examples/GetAllUrlChannels.php';//GetAllUrlChannels 
include 'examples/GenerateReport.php';//GenerateReport 
include 'examples/GenerateReportWithPaging.php';//GenerateReportWithPaging 
include 'examples/FillMissingDatesInReport.php';//FillMissingDatesInReport 
include 'examples/CollateReportData.php';//CollateReportData 
include 'examples/GetAllSavedReports.php';//GetAllSavedReports 
include 'examples/GenerateSavedReport.php';//GenerateSavedReport 
include 'examples/GetAllSavedAdStyles.php';//GetAllSavedAdStyles 
include 'examples/GetAllAlerts.php';//GetAllAlerts 
include 'examples/GetAllDimensions.php';//GetAllDimensions 
include 'examples/GetAllMetrics.php';//GetAllMetrics 
// Max results per page. 
define('MAX_LIST_PAGE_SIZE', 50, true); 
define('MAX_REPORT_PAGE_SIZE', 50, true); 
// Configure token storage on disk. 
// If you want to store refresh tokens in a local disk file, set this to true. 
define('STORE_ON_DISK', false, true); 
define('TOKEN_FILENAME', 'tokens.dat', true); 
// Set up authentication. 
$client = new Google_Client(); 
$client->addScope('https://www.googleapis.com/auth/adsense.readonly'); 
$client->setAccessType('offline'); 
// Be sure to replace the contents of client_secrets.json with your developer 
// credentials. 
$client->setAuthConfigFile('client_secrets.json'); 
// Create service. 
$service = new Google_Service_AdSense($client); 
// If we're logging out we just need to clear our local access token. 
// Note that this only logs you out of the session. If STORE_ON_DISK is 
// enabled and you want to remove stored data, delete the file. 

if (isset($_REQUEST['logout'])) { 
    unset($_SESSION['access_token']); 
} 
// If we have a code back from the OAuth 2.0 flow, we need to exchange that 
// with the authenticate() function. We store the resultant access token 
// bundle in the session (and disk, if enabled), and redirect to this page. 
if (isset($_GET['code'])) { 
    $client->authenticate($_GET['code']); 
// Note that "getAccessToken" actually retrieves both the access and refresh 
// tokens, assuming both are available. 
    $_SESSION['access_token'] = $client->getAccessToken(); 
    if (STORE_ON_DISK) { 
     file_put_contents(TOKEN_FILENAME, $_SESSION['access_token']); 
    } 
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; 
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); 
    exit; 
} 
// If we have an access token, we can make requests, else we generate an 
// authentication URL. 
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
    $client->setAccessToken($_SESSION['access_token']); 
} else if (STORE_ON_DISK && file_exists(TOKEN_FILENAME) && 
    filesize(TOKEN_FILENAME) > 0) { 
// Note that "setAccessToken" actually sets both the access and refresh token, 
// assuming both were saved. 
    $client->setAccessToken(file_get_contents(TOKEN_FILENAME)); 
    $_SESSION['access_token'] = $client->getAccessToken(); 
} else { 
// If we're doing disk storage, generate a URL that forces user approval. 
// This is the only way to guarantee we get back a refresh token. 
    if (STORE_ON_DISK) { 
     $client->setApprovalPrompt('force'); 
    } 
    $authUrl = $client->createAuthUrl(); 
} 
//echo pageHeader('Get Final Report'); 
//echo "stre on disk = " . STORE_ON_DISK . "<br />"; 
echo '<div><div class="request">'; 
if (isset($authUrl)) { 
    echo '<a class="login" href="' . $authUrl . '">Login !</a>'; 
} else { 
    echo '<a class="logout" href="?logout">Logout</a>'; 
}; 
echo '</div>'; 
if ($client->getAccessToken()) { 
    echo '<pre class="result">'; 
// Now we're signed in, we can make our requests. 
    $adsense = makeRequests($service); 
    /* Note that we re-store the access_token bundle, just in case anything 
    changed during the request - the main thing that might happen here is the 
    access token itself is refreshed if the application has offline access. */ 
    $_SESSION['access_token'] = $client->getAccessToken(); 
    echo '</pre>'; 
} 
echo '</div>'; 
echo pageFooter(__FILE__); 
// Makes all the API requests. 
function makeRequests($service) { 
    print "\n"; 
    $accounts = GetAllAccounts::run($service, MAX_LIST_PAGE_SIZE); 
    echo '<div class="Account">Account No. '.$accounts[0]["id"].' Details</div>'; 

    if (isset($accounts) && !empty($accounts)) { 
// Get an example account ID, so we can run the following sample. 
     $exampleAccountId = $accounts[0]['id']; 
     GetAccountTree::run($service, $exampleAccountId); 
     $adClients = 
      GetAllAdClients::run($service, $exampleAccountId, MAX_LIST_PAGE_SIZE); 
     ; 

     ?> 
     <table id="myTable" class="tablesorter" border="1px solid"> 
      <thead> 
      <tr> 
       <th>AdClient ID</th> 
       <th>AdClient Code</th> 
      </tr> 
      </thead> 
      <tbody> 
      <?php 
      foreach($adClients as $adClients){ 

       ?> 
       <tr><td><?php echo $adClients['id']; ?></td><td><?php echo $adClients['productCode']; ?></td></tr> 

      <?php 
      } 
      ?> 
      </tbody> 
     </table> 
     <?php 

     if (isset($adClients) && !empty($adClients)) { 
// Get an ad client ID, so we can run the rest of the samples. 
      $exampleAdClient = end($adClients); 

      $exampleAdClientId = $adClients['id']; 

      $adUnits = GetAllAdUnits::run($service, $exampleAccountId, 
       $exampleAdClientId, MAX_LIST_PAGE_SIZE); 


      ?> 
      <table id="myTable_1" class="tablesorter" border="1px solid"> 
       <thead> 
       <tr> 
        <th>AdUnit name</th> 
        <th>AdUnit Code</th> 
        <th>AdUnit ID</th> 
        <th>Status</th> 
        <th>Detail</th> 

       </tr> 
       </thead> 
       <tbody> 
       <?php 
       foreach($adUnits as $adUnits){ 

        if($adUnits['status']=='ACTIVE' ||$adUnits['status']=='NEW'){ ?> 
         <tr> 
          <td><?php echo $adUnits['name']; ?></td> 
          <td><?php echo $adUnits['code']; ?></td> 
          <td><?php echo $adUnits['id']; ?></td> 
          <td><?php echo $adUnits['status']; ?></td> 
          <td class="link"><a href="<?php echo $redirect.'?ad_name='.$adUnits['name'];?>">Get detail</a></td> 
         </tr> 
        <?php 
        } 
       } 
       ?> 
       </tbody> 
      </table> 
      <?php 
      if (isset($_REQUEST['ad_name'])) { 
       //die('function shoul be calle dhere '); 

       $Get_reports=GenerateReport::run($service, $exampleAccountId, $exampleAdClientId,$_REQUEST['ad_name']); 
      } 
      else { 
       $Get_reports=GenerateReport::run($service, $exampleAccountId, $exampleAdClientId); 
      } 
      //print_r($Get_reports); 

      ?> 
      <table id="myTable_2" class="tablesorter" border="1px solid"> 
       <thead> 
       <tr> 
        <?php foreach($Get_reports['headers'] as $headers){ 
         ?> 
         <th><?php printf('%25s', $headers['name']); ?></th> 
        <?php 
        } 
        ?> 
       </tr> 
       </thead> 
       <?php 

       foreach($Get_reports['rows'] as $rows) { 
        ?> 
        <tr> 
         <?php 
         foreach($rows as $col) { 
          ?> 
          <td><?php echo $col; $adsense = $col; ?></td> 

         <?php 

         } ?> 
        </tr> 
       <?php 
       } 
       ?> 

      </table> 

      <table id="myTable_3" class="tablesorter" border="1px solid"> 
       <thead> 
       <tr> 
        <?php 
        foreach($Get_reports['headers'] as $headers){ 
         ?> 
         <th><?php echo 'Total '.$headers['name']; ?></th> 
        <?php 
        } 
        ?> 
       </tr> 
       </thead> 
       <tbody> 
       <tr> 
        <?php 
        foreach($Get_reports['totals'] as $totals){ 

         ?> 
         <td><?php echo $totals; ?></td> 
        <?php 
        } 
        ?> 
       </tr> 
       </tbody> 
      </table> 
      <?php 
      //die('Report Generated For Last 7 Days'); 


     } 
    } 
    //echo "adsense = " . $adsense . "<br />"; 
    return $adsense; 
} 
+0

안녕하세요, 올바르게 이해한다면 - 사용자가 방해하지 않고 데이터를 가져올 수있는 코드를 작성하려고하셨습니까? 의미 - 코드 내부의 데이터를 사용합니까? 왜냐하면 나는 똑같은 일을하려고하기 때문이다. - 보고서 데이터를 가져 와서 배경에서 사용한다 ... 그들을 조작하고 SQL 테이블에 삽입한다. 나에게 연락 할 수 있으면 감사하겠다. :) – Bramat

+0

나는 애드 센스 PHP API를 사용하면서 몇 가지 문제가 발생했습니다. 알고 싶습니다. '/ path/to/clientlib'및 'config.php'로 무엇을 참조하고 싶습니까? 제발 도와주세요! –

답변

2

수동으로 로그인하고 새로 고침 토큰을 저장하면 후속 인증 요청에서 해당 저장된 토큰을 사용하므로 다시 묻지 않습니다.

이 항목을 true로 변경 한 다음 올바른 계정을 사용하여 페이지를 한 번 치기 만하면됩니다.

// If you want to store refresh tokens in a local disk file, set this to true. 
define('STORE_ON_DISK', true, true); 
관련 문제