API отчетов Google Analytics с использованием Yii2 - PullRequest
0 голосов
/ 26 февраля 2020

Hello World!
На моем веб-сайте я хочу получить значения дохода от Ad -ense для определенных страниц, и я использую отчеты API Google Analytics для API, я соединил учетные записи «учетная запись adsense и аналитическая учетная запись», написал код, следуя инструкциям, но все же он не работает.
Если кто-нибудь может сказать мне, разрешено ли изменять имена функций при использовании api?

Модель AdsenseRequest. php

<code><?php

namespace app\models;


use DateTime;
use function floatval;

use Google_Client;
use Google_Service_AnalyticsReporting;
use Google_Service_AnalyticsReporting_DateRange;
use Google_Service_AnalyticsReporting_Dimension;
use Google_Service_AnalyticsReporting_GetReportsRequest;
use Google_Service_AnalyticsReporting_Metric;
use Google_Service_AnalyticsReporting_ReportData;
use Google_Service_AnalyticsReporting_ReportRequest;
use Google_Service_AnalyticsReporting_ReportRow;
use function var_export;
use Yii;
use yii\base\Model;

class AdsenseRequest extends Model
{

    public $analytics;
    public $VIEW_ID="********";


    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        // Use the developers console and download your service account
        // credentials in JSON format. Place them in this directory or
        // change the key file location if necessary.
//    $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
        $KEY_FILE_LOCATION = Yii::getAlias("@app/adsense/taj****ak-*********.json");



//        $this->includeFiles();
        // Create and configure a new client object.
        $client = new Google_Client();
        $client->setApplicationName("Hello Analytics Reporting");
        $client->setAuthConfig($KEY_FILE_LOCATION);
        $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
        $this->analytics = new Google_Service_AnalyticsReporting($client);
        // return $analytics
    }


    public function getStatistics() {
        // Create the DateRange object.
        $dateRange = new Google_Service_AnalyticsReporting_DateRange();
        $dateRange->setStartDate("today"); 
        $dateRange->setEndDate("today");


        $adsenseViewed = new Google_Service_AnalyticsReporting_Metric();
        $adsenseViewed->setExpression("ga:adsenseAdsViewed");
        $adsenseViewed->setAlias("adsenseAdsViewed");


        $adsenseRevenue = new Google_Service_AnalyticsReporting_Metric();
        $adsenseRevenue->setExpression("ga:adsenseRevenue");
        $adsenseRevenue->setAlias("adsenseRevenue");


        $page = new Google_Service_AnalyticsReporting_Dimension();
        $page->setName("ga:pagePath");


        $date = new Google_Service_AnalyticsReporting_Dimension();
        $date->setName("ga:date");

        // Create the ReportRequest object.
        $request = new Google_Service_AnalyticsReporting_ReportRequest();
        $request->setViewId($this->VIEW_ID);
        $request->setDateRanges($dateRange);
        $request->setDimensions(array($page,$date));
        $request->setMetrics(array($adsenseViewed, $adsenseRevenue));

        $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
        $body->setReportRequests( array( $request) );
        $response = $this->analytics->reports->batchGet( $body );
        /** @var Google_Service_AnalyticsReporting_ReportData $data*/
        $data = $response->reports[0]->data;
        return $data->getRows();
    }

/*    public function var_export($var){
        echo "<pre>";
        var_export($var);
        echo "
"; die;} * / publi c функция writeValues ​​() {/ ** @ var Google_Service_AnalyticsReporting_ReportRow $ row * / $ row = $ this-> getStatistics (); foreach ($ row as $ row) {$ link = $ row-> sizes [0]; $ metrics = $ row-> getMetrics (); $ заработано = $ metrics [0] -> значения [1]; $ viewsAdsense = $ metrics [0] -> значения [0]; if ($ newLink = AdsenseStatistics :: getLink ($ link)) {if ($ review = Review :: findOne (["link" => $ newLink])) {$ userID = $ review-> user_id; if ($ statistics = AdsenseStatistics :: findOne (["pageID" => $ review-> id])) { $ userEarned = $ this-> getEarnedFormula ($ заработано); $ statistics-> заработано = $ статистика-> заработано + $ userEarned; $ statistics-> views = $ this-> getViewsFormula ($ statistics-> заработано);} else { $ userEarned = $ this-> getEarnedFormula (0, $ заработано); $ statistics = new AdsenseStatistics (); $ statistics-> заработано = $ userEarned; $ statistics-> userID = $ userID; $ statistics-> pageID = $ review- > id; $ statistics-> views = $ this-> getViewsFormula ($ statist ics-> заработал); } $ statistics-> save (false); $comeOperation = new AdsenseIncome (); $comeOperation-> userId = $ userID; $comeOperation-> reviewID = $ review-> id; $ доходаOperation-> доход = $ userEarned; $ date = новый DateTime ('- 1 дней'); $comeOperation-> time = $ date-> format ("U"); $ IncomeOperation-> сохранить (ложь); if ($ billing = Billing :: findOne (["user_id" => $ userID])) {$ billing-> value = $ billing-> value + $ this-> getEarnedFormula ($ заработано); } else {$ billing = new Billing (); $ billing-> user_id = $ userID; $ billing-> value = $ this-> getEarnedFormula ($ заработано); } $ billing-> save (false); }}}} / * * * * @param double $ incrementVal - * @return double * * / publi c function getEarnedFormula ($ incrementVal) {return round ($ incrementVal / 2,2); } / * * * * @param double $ заработано * @return double * * * / publi c функция getViewsFormula ($ заработано) {возвращение $ заработано / 0.9 * 1000; }}


Модель AdsenseStatistics. php

<?php

namespace app\models;

use Google_Client;
use Google_Service_AnalyticsReporting;
use Google_Service_AnalyticsReporting_DateRange;
use Google_Service_AnalyticsReporting_Dimension;
use Google_Service_AnalyticsReporting_GetReportsRequest;
use Google_Service_AnalyticsReporting_Metric;
use Google_Service_AnalyticsReporting_ReportData;
use Google_Service_AnalyticsReporting_ReportRequest;
use function preg_match;
use function str_replace;
use Yii;

/**
 * This is the model class for table "adsense_statistics".
 *
 * @property int $id
 * @property int $userID
 * @property double $earned
 * @property int $pageID
 * @property int $views
 * @property int $lastday
 */
class AdsenseStatistics extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'adsense_statistics';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userID', 'pageID', 'views'], 'integer'],
            [['earned'], 'number'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'userID' => 'User ID',
            'earned' => 'Earned',
            'pageID' => 'Page ID',
        ];
    }

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub

    }
    /*
     *
     * */
    public function setParams($userID, $earned){

    }


    /*
     * 
     *
     * @param string $linkInput -  URL API
     * @return string $returnLink -
     * @return bool false 
     * */
    public static function getLink($link){
        $pattern = "#\/review\/([a-z]|[0-9])*.*#";
        $patternLink = "#(\/(?!.*\/).*)#";

        if(preg_match($pattern, $link) and substr_count($link,"/")>=3){
            if(preg_match($patternLink,$link,$match)){
                $returnLink = str_replace("/","",$match[0]);
                return $returnLink;
            }
            return false;
        }return false;
    }
}


Просмотр отзыва. php

<?php
use app\widgets\menu\CabinetMenuWidget;
use yii\helpers\Url;
use yii\helpers\Html;
?>
<?php  if(count($data['reviews'])>0) { ?>
                            <?php foreach($data['reviews'] as $r) {?>
                       <h4><?=$r->adsenseStatistics->earned?$r->adsenseStatistics->earned."$":"0$"?></h4>


Чего мне не хватает, почему он не показывает никаких денег, хотя страницы зарабатывают деньги в AdSense и в аналитических отчетах
С уважением, Nsour.

...