Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 谷歌分析api的乐趣;令牌错误_Javascript_Php_Ajax_Api_Google Analytics - Fatal编程技术网

Javascript 谷歌分析api的乐趣;令牌错误

Javascript 谷歌分析api的乐趣;令牌错误,javascript,php,ajax,api,google-analytics,Javascript,Php,Ajax,Api,Google Analytics,更新:我已经为我的问题添加了一个答案,解决了我的问题(尽管它没有100%经过测试)-仍然需要等待令牌刷新发生。仍然希望听到其他人的意见。 我在使用Google analytics api for php时遇到了一个问题 我通过在构造函数中调用的函数启动api(可以找到完整的脚本;它是一个较旧的版本),在这里我设置并定义api需要的所有变量,然后检查以确保我有一个有效的令牌。我有一个AJAX控制器,它异步调用类中的4个函数,通过谷歌图表api向用户显示相关的分析统计数据。如果有错误,则在该特定图表

更新:我已经为我的问题添加了一个答案,解决了我的问题(尽管它没有100%经过测试)-仍然需要等待令牌刷新发生。仍然希望听到其他人的意见。

我在使用Google analytics api for php时遇到了一个问题

我通过在构造函数中调用的函数启动api(可以找到完整的脚本;它是一个较旧的版本),在这里我设置并定义api需要的所有变量,然后检查以确保我有一个有效的令牌。我有一个AJAX控制器,它异步调用类中的4个函数,通过谷歌图表api向用户显示相关的分析统计数据。如果有错误,则在该特定图表块中显示错误。如果我们有一个错误,那么100%的错误可能来自于我们是否建立了一个适当的令牌,因为从ga获取数据的语句已经准备好了

由于所有4个图表/显示对应于类中的不同函数,我们将运行4个对google analytics的查询。然而,有时其中一个图表会得到“令牌错误”响应,有时不止一个图表会。。。有时候根本就不会发生。我想这可能是因为在AJAX调用中,我以
new
的身份启动了我的类,而不是获取该类的实例,因此只有一个调用(例如,类的一个构造)来获取令牌。因此,我通过
$ga=Google\u Analytics\u Stats::getInstance($gaInfo)实现了一个单例类型的设计,一次调用这个类但问题仍然存在

有人知道是什么导致了这个间歇性令牌错误吗

为了清楚起见

Google\u Analytics\u Stats
initAnalytics($gaInfo)
中初始化
GoogleAnalyticsAPI
,其中
$gaInfo
是相关的帐户和电子邮件详细信息。php根据
Google\u Analytics\u Stats
中的类型在函数之间切换,该类型仅使用
$ga=Google\u Analytics\u Stats::getInstance($gaInfo)初始化一次

AJAX调用:

<?php
require ('../framework.php');
$login->protect(false);
if (!isAjax()) {
    redirect('index.php');
}
// dont forget these functions use date so user timezone effects it!!!
error_reporting(0);
$ga = Google_Analytics_Stats::getInstance($gaInfo);

switch (isset($_GET['type']) ? $_GET['type'] : '') {
    case 'map':
        if (isset($_GET['ga_length'])) {
            echo $ga->getVisitsByCountries($_GET['ga_length']);
        }
        else {
            $error = array(
                "status" => "error",
                "error"  => 'No length defined'
            );
            echo json_encode($error);
        }

        break;
    case 'bounceRate':
        echo $ga->displayBounceRate();
        break;
    case 'visitsToday':
        echo $ga->getVisitsToday();
        break;
    case 'momVisits':
        echo $ga->displayMonthOverMonthVisits();
        break;
    case 'newVsReturn':
        if (isset($_GET['ga_length'])) {
            echo $ga->getNewVsReturn($_GET['ga_length']);
        }
        else {
            $error = array(
                "status" => "error",
                "error"  => 'No length defined'
            );
            echo json_encode($error);
        }
        break;
    case 'visitsByDate':
        if (isset($_GET['ga_length'])) {
            echo $ga->getVisitsByDate($_GET['ga_length']);
        }
        else {
            $error = array(
                "status" => "error",
                "error"  => 'No length defined'
            );
            echo json_encode($error);
        }
        break;
}
?>

主要代码(仅为概念化所需的第一部分):

class谷歌分析统计{
私人股本$ga;
//默认$len的数组
私人美元反弹率当前=“”;
私人每月$访客\当前='';
//舍入精度
私人$precision=1;
私人$len;
公共静态实例;
函数构造($gaInfo)
{
$this->initAnalytics($gaInfo);
$this->len=数组(
“开始日期”=>日期(日期格式,标准时间(“-1个月”),
“结束日期”=>日期(日期格式)
);
}
公共静态函数getInstance($gaInfo)
{
如果(!isset(self::$instance)){
self::$instance=新的谷歌分析统计数据($gaInfo);
}
返回self::$instance;
}
私有函数initAnalytics($gaInfo)
{
试一试{
$ga=新的谷歌分析API(“服务”);
$accountId=$gaInfo['account_id'];
$ga->auth->setClientId($gaInfo['client_id']);
$ga->auth->setEmail($gaInfo['email']);
$ga->auth->setPrivateKey($gaInfo['key\u src']);
$auth=$ga->auth->getAccessToken();
//尝试获取访问令牌
如果($auth['http_code']==200){
$accessToken=$auth['access_token'];
$tokenExpires=$auth['expires_in'];
$tokenCreated=time();
}
否则{
抛出新异常(“令牌错误”);
}
//设置令牌和帐户id
$ga->setAccessToken($accessToken);
$ga->setAccountId($accountId);
//设置默认值
/*
如果(设置($this->len)){
$ga->setDefaultQueryParams($this->len);
}
*/
$this->ga=$ga;
}
捕获(例外$e){
$error=array(
“状态”=>“错误”,
“错误”=>$e->getMessage()
);
//输出结果
echo json_编码($error);
}
}
公共函数getBounceRate($params='')
{
$defaults=array('metrics'=>'ga:bounceRate');
$\u params=array\u merge($defaults,$params);
$result=$this->ga->\u查询($\u参数);
返回$result['rows'][0][0];
}
公共函数getCurrent()
{
$params=数组(
“开始日期”=>日期(日期格式,标准时间(“-1个月”),
“结束日期”=>日期(日期格式)//现在
);
$result=$this->getBounceRate($params);
返回回合($result$this->precision);
}
公共职能部门(百分比)
{
如果($this->inRange($percentage,0,25.9)){
返回数组('display'=>'success','text'=>'Extremel low');
}
elseif($this->inRange($percentage,26,40.9)){
返回数组('display'=>'success','text'=>'低于平均值');
}
elseif($this->inRange($percentage,4155.9)){
返回数组('display'=>'warning','text'=>'Average');
}
elseif($this->inRange($percentage,56,70.9)){
返回数组('显示'=>'危险','文本'=>'高于平均值');
}
否则{
返回数组('display'=>'danger','text'=>'very high');
}
}
公共函数displayBounceRate()
{
//必须先调用,否则当前值将为空
$current=$this->getBounceRateCurrent();
$out=‘本月反弹率’;
$out.=''.$current'.%';
$changeWrapper=“评级:%s”;
$text=$this->bounceratetextical($current);
$out.=sprintf($changeWrapper,$text['display'],$text['text']);
退回$out;
}
Alrig
class Google_Analytics_Stats {

    private $ga;
    // array for default $len
    private $bounce_rate_current = '';
    private $monthly_visitors_current = '';
    // rounding precision
    private $precision = 1;
    private $len;
    public static $instance;

    function __construct($gaInfo)
    {
        $this->initAnalytics($gaInfo);
        $this->len = array(
            'start-date' => date(DATE_FORMAT, strtotime('-1 month')),
            'end-date'   => date(DATE_FORMAT)
        );
    }
    public static function getInstance($gaInfo)
    {
        if (!isset(self::$instance)) {
            self::$instance = new Google_Analytics_Stats($gaInfo);
        }
        return self::$instance;
    }
    private function initAnalytics($gaInfo)
    {
        try {
            $ga = new GoogleAnalyticsAPI('service');
            $accountId = $gaInfo['account_id'];
            $ga->auth->setClientId($gaInfo['client_id']);
            $ga->auth->setEmail($gaInfo['email']);
            $ga->auth->setPrivateKey($gaInfo['key_src']);
            $auth = $ga->auth->getAccessToken();
            // try and get access token
            if ($auth['http_code'] == 200) {
                $accessToken = $auth['access_token'];
                $tokenExpires = $auth['expires_in'];
                $tokenCreated = time();
            }
            else {
                throw new Exception('Token error');
            }
            // set token and account id
            $ga->setAccessToken($accessToken);
            $ga->setAccountId($accountId);
            // set defaults
            /*
              if (isset($this->len)) {
              $ga->setDefaultQueryParams($this->len);
              }
             */
            $this->ga = $ga;
        }
        catch (Exception $e) {
            $error = array(
                "status" => "error",
                "error"  => $e->getMessage()
            );
            //output result
            echo json_encode($error);
        }
    }

    public function getBounceRate($params = '')
    {
        $defaults = array('metrics' => 'ga:bounceRate');
        $_params = array_merge($defaults, $params);
        $result = $this->ga->_query($_params);
        return $result['rows'][0][0];
    }

    public function getBounceRateCurrent()
    {
        $params = array(
            'start-date' => date(DATE_FORMAT, strtotime('-1 month')),
            'end-date'   => date(DATE_FORMAT) //now
        );
        $result = $this->getBounceRate($params);
        return round($result, $this->precision);
    }

    public function bounceRateTextual($percentage)
    {
        if ($this->inRange($percentage, 0, 25.9)) {
            return array('display' => 'success', 'text' => 'Extremel low');
        }
        elseif ($this->inRange($percentage, 26, 40.9)) {
            return array('display' => 'success', 'text' => 'Below average');
        }
        elseif ($this->inRange($percentage, 41, 55.9)) {
            return array('display' => 'warning', 'text' => 'Average');
        }
        elseif ($this->inRange($percentage, 56, 70.9)) {
            return array('display' => 'danger', 'text' => 'Higher than average');
        }
        else {
            return array('display' => 'danger', 'text' => 'Extremely high');
        }
    }

    public function displayBounceRate()
    {
        // has to be called first or current will be empty
        $current = $this->getBounceRateCurrent();
        $out = '<h6 class="text-uppercase">Bounce Rate this month</h6>';
        $out .= '<h1>' . $current . '%</h1>';
        $changeWrapper = "<span class='text-muted mr-0-5'>Rating:</span><span class='label label-%s label-small'>%s</span>";
        $textual = $this->bounceRateTextual($current);
        $out .= sprintf($changeWrapper, $textual['display'], $textual['text']);
        return $out;
    }
private function initAnalytics($gaInfo)
    {
        try {
            $ga = new GoogleAnalyticsAPI('service');
            $accountId = $gaInfo['account_id'];
            $ga->auth->setClientId($gaInfo['client_id']);
            $ga->auth->setEmail($gaInfo['email']);
            $ga->auth->setPrivateKey($gaInfo['key_src']);
            // set ga to ga so getToken can use the vars we set above
            $this->ga = $ga;
            // attempt to get token; 1st attempt
            if($this->getToken() === false) {
                // 2nd attempt
                if($this->getToken() === false) {
                    throw new Exception ('Token Error. Refresh page.');
                }
            }
            // unset ga as we are going to set it again with the access token initialized 
            unset($this->ga);
            $ga->setAccessToken($_SESSION['ga_access_token']);
            $ga->setAccountId($accountId);  
            // set defaults
            /*
              if (isset($this->len)) {
              $ga->setDefaultQueryParams($this->len);
              }
             */
            $this->ga = $ga;

        }
        catch (Exception $e) {
            $error = array(
                "status" => "error",
                "error"  => $e->getMessage()
            );
            //output result
            echo json_encode($error);
        }
    }

    public function getToken() 
    {
        // check to see if we have a token
        if (isset($_SESSION['ga_token_created']) && isset($_SESSION['ga_token_expires']) && isset($_SESSION['ga_access_token'])) { 
            // check to see if the token is still valid, if not, refresh it
            if ((time() - $_SESSION['ga_token_created']) >= $_SESSION['ga_token_expires']) {
                $auth = $this->ga->auth->refreshAccessToken($refreshToken);
                if ($auth['http_code'] == 200) {
                    // now we can unset the old session vars ...
                    unset($_SESSION['ga_access_token']);
                    unset($_SESSION['ga_token_created']);
                    unset($_SESSION['ga_token_expires']);
                    // ... and add the new ones
                    $_SESSION['ga_access_token'] = $auth['access_token'];
                    $_SESSION['ga_token_expires'] = $auth['expires_in'];
                    $_SESSION['ga_token_created'] = time();
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        // nothing was set so we go the usual route
        } else {
            $auth = $this->ga->auth->getAccessToken();
            // try and get access token
            if ($auth['http_code'] == 200) {
                $_SESSION['ga_access_token'] = $auth['access_token'];
                $_SESSION['ga_token_expires'] = $auth['expires_in'];
                $_SESSION['ga_token_created'] = time();
                return true;
            } else {
                return false;
            }
        }
    }