【问题标题】:Get last month's Adsense profits via PHP通过 PHP 获取上个月的 Adsense 利润
【发布时间】:2017-01-24 21:44:21
【问题描述】:

这个问题在这个网站上以各种形式(不太具体)被问到,我想建立一个一劳永逸的解决方案,试图克服很多令人困惑的步骤。

大声说:我需要提取上个月的总 AdSense 收入,用于我的网站。

  1. 我知道这需要 Adsense API
  2. 我知道我需要提供凭据

现有的很多关于这个问题的问答都参考了 Google AdSense 界面的早期版本。我想根据(截至)2017 年来执行此操作。

问题:

请有人提供准确、分步甚至过度解释的说明,说明如何使用哪些 API 及其配置来完成此操作?

我已经尝试过多次次,但我得到的只是一个错误提示“必须登录" 在 JSON 输出中。

我已经阅读了一些关于“解决方案”的信息,但不能完全确定它们是否不起作用或我启用的 API 不正确(或配置错误)。

【问题讨论】:

  • 我知道我的问题读起来很尖锐,但其他提出相同问题的人尚未收到 有效 解决方案 - 或 - 收到部分、不完整的信息,导致他们做出回应有了“想通了”,除此之外什么都没有。这是一个简单的目标。不需要消极回应。

标签: php api adsense


【解决方案1】:

您应该从

下载包含 AdSense php 示例的 Google APIs PHP 客户端库
https://developers.google.com/api-client-library/php/start/installation

点击 GitHub 链接,您将转到此页面

https://github.com/goog`le/google-api-php-client

您将获得一个名为“google-api-php-client-2.1.1”的文件夹,您必须将其上传到您的服务器。

点击绿色按钮“克隆或下载”。 然后从这里下载一些 AD-SENSE 示例

https://github.com/googleads/googleads-adsense-examples

查看文件googleads-adsense-examples-master/php-clientlib-1.x/v1.x/adsense-sample.php 在此文件上,将常量 STORE_ON_DISK 设置为 true。更好的是,您可以在下面查看我自己的 adsense-sample.php 的代码。

编辑文件googleads-adsense-examples-master/php-clientlib-1.x/v1.x/client_secrets.json 使用您可以从您的 Google AdSense 帐户获取的凭据 从

获取您的客户 ID
https://console.developers.google.com/apis/credentials

文件googleads-adsense-examples-master/php-clientlib-1.x/v1.x/client_secrets.json的内容应该是这样的

{
    "web":
    {
        "client_id":"youridblablabla.apps.googleusercontent.com",
        "project_id":"yournameproject",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
        "client_secret":"blablabla",
        "redirect_uris":["http://yourdomain.com/thepathtoyoursamplephpfile"],
        "javascript_origins":["http://yourdomain.com/","http://yourdomain.com/"]
    }
}

从此处https://www.google.com/adsense/ 获取您的发布商 ID,然后转到“设置/帐户信息”面板

--

这是我修改示例代码并使其工作的方式。 将 APIs 文件夹 google-api-php-client-2.1.1 放在包含此 php 文件的文件夹中(请参阅下面的 php 代码)。 在文件夹“google-api-php-client-2.1.1”中创建一个文件夹 AdSense_Report 复制所有示例文件(Collat​​eReportData.php、FillMissingDatesInReport.php、GenerateReport.php...) 在 AdSense_Report 文件夹中。因此,您可以通过这种方式包含示例文件:

require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAccounts.php';

重命名 my_project_client_secrets.json 并将其放在“AdSense_Report”文件夹中。 确保文件my_project_client_secrets.json 不能被其他人读取,而只能被这个 php.ini 读取。 这是我的 php 代码。我评论了一些不需要的功能。

function UserBannerRevenueReportGoogle()
{
    define('MAX_LIST_PAGE_SIZE', 50, true);
    define('MAX_REPORT_PAGE_SIZE', 50, true);

    define('STORE_ON_DISK', true, true);
    define('TOKEN_FILENAME', 'google-api-php-client-2.1.1/AdSense_Report/google_adsense_tokens.dat', true);
    define('CLIENT_SECRET_JSON_PATH', 'google-api-php-client-2.1.1/AdSense_Report/my_project_client_secrets.json', true);

    require_once 'google-api-php-client-2.1.1/vendor/autoload.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/templates/base.php';

    session_start();

    /*
    // In case of trouble, reset the token by activating these lines, call the script, then comment these lines back.
    unset($_SESSION['access_token']);
    @unlink(TOKEN_FILENAME);
    return;
    */

    $client = new Google_Client();
    $client->addScope('https://www.googleapis.com/auth/adsense.readonly');
    $client->setAccessType('offline');
    $client->setAuthConfig(CLIENT_SECRET_JSON_PATH);


    $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']);
        @unlink(TOKEN_FILENAME);
    }

    // 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'] ."?ta=54";
        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('AdSense Management API sample');
    echo '<div><div class="request">';
    if(isset($authUrl))
    {
        echo '<a class="login" href="' . $authUrl . '">Connect Me!</a>';
    }
    else
    {
        echo '<a class="logout" href="?ta=54&logout">Logout</a>';
    }
    echo '</div>';


    if($client->getAccessToken())
    {
        echo '<pre class="result">';
        // Now we're signed in, we can make our requests.
        UserBannerRevenueReportGoogleGet($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__);
}



function UserBannerRevenueReportGoogleGet($service)
{
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAccounts.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAccountTree.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAdClients.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAdUnits.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllCustomChannelsForAdUnit.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllCustomChannels.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllUrlChannels.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GenerateReport.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GenerateReportWithPaging.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/FillMissingDatesInReport.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/CollateReportData.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllSavedReports.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GenerateSavedReport.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllSavedAdStyles.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllAlerts.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllDimensions.php';
    require_once 'google-api-php-client-2.1.1/AdSense_Report/GetAllMetrics.php';

    $accounts = new GetAllAccounts;

    print "\n";
    $accounts = GetAllAccounts::run($service, MAX_LIST_PAGE_SIZE);

    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);

        $bullets = str_repeat('#', 80) . "\n";
        if(isset($adClients) && !empty($adClients))
        {
            foreach($adClients as $exampleAdClient)
            {
                // Get an ad client ID (the last one), so we can run the rest of the samples.
                //$exampleAdClient = end($adClients); // to get the first ID use: $adClients[0];
                $exampleAdClientId = $exampleAdClient['id'];

                print $bullets;
                print "AdClient: ".$exampleAdClientId." - ".$exampleAdClient['productCode']."\n";
                print $bullets;

                $adUnits = GetAllAdUnits::run($service, $exampleAccountId, $exampleAdClientId, MAX_LIST_PAGE_SIZE);
                if(isset($adUnits) && !empty($adUnits))
                {
                    // Get an example ad unit ID, so we can run the following sample.
                    //$exampleAdUnitId = $adUnits[0]['id'];
                    //GetAllCustomChannelsForAdUnit::run($service, $exampleAccountId, $exampleAdClientId, $exampleAdUnitId, MAX_LIST_PAGE_SIZE);
                }
                else{
                    print 'No ad units found, unable to run dependant example.\n';
                }


                /*

                $customChannels = GetAllCustomChannels::run($service, $exampleAccountId, $exampleAdClientId, MAX_LIST_PAGE_SIZE);
                if(isset($customChannels) && !empty($customChannels))
                {
                    // Get an example ad unit ID, so we can run the following sample.
                    $exampleCustomChannelId = $customChannels[0]['id'];
                    GetAllAdUnitsForCustomChannel::run($service, $exampleAccountId, $exampleAdClientId, $exampleCustomChannelId, MAX_LIST_PAGE_SIZE);
                }
                else{
                    print 'No custom channels found, unable to run dependant example.\n';
                }
                */

                //GetAllUrlChannels::run($service, $exampleAccountId, $exampleAdClientId, MAX_LIST_PAGE_SIZE);
                GenerateReport::run($service, $exampleAccountId, $exampleAdClientId);
                //GenerateReportWithPaging::run($service, $exampleAccountId, $exampleAdClientId, MAX_REPORT_PAGE_SIZE);
                //FillMissingDatesInReport::run($service, $exampleAccountId, $exampleAdClientId);
                //CollateReportData::run($service, $exampleAccountId, $exampleAdClientId);
            }
        }
        else{
            print 'No ad clients found, unable to run dependant examples.\n';
        }

        print $bullets;
        print $bullets;
        $savedReports = GetAllSavedReports::run($service, $exampleAccountId, MAX_LIST_PAGE_SIZE);
        if(isset($savedReports) && !empty($savedReports))
        {
            // Get an example saved report ID, so we can run the following sample.
            $exampleSavedReportId = $savedReports[0]['id'];
            GenerateSavedReport::run($service, $exampleAccountId, $exampleSavedReportId);
        }
        else{
          print 'No saved reports found, unable to run dependant example.<br>';
        }

        //GetAllSavedAdStyles::run($service, $exampleAccountId, MAX_LIST_PAGE_SIZE);
        GetAllAlerts::run($service, $exampleAccountId);
    }
    else{
        print 'No accounts found, unable to run dependant examples.\n';
    }

    GetAllDimensions::run($service);
    GetAllMetrics::run($service);
}

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 1970-01-01
    • 2016-11-09
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多