如何在laravel 5中为谷歌分析添加谷歌PHP API

时间:2022-09-07 15:13:56

So, I was wondering if the following code could actually be ported to laravel?

所以,我想知道下面的代码是否可以被移植到laravel?

<?php
require_once 'data.php';
require_once 'lib/google-api-php-client-master/src/Google/autoload.php';
session_start();

$client_id      = 'CLIENT_ID_HERE';
$client_secret  = 'CLIENT_SECRET_HERE';
$redirect_uri   = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$simple_api_key = 'API_KEY_HERE';

$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/analytics.readonly");
$client->setApprovalPrompt('force');
$client->setAccessType('offline');

if(isset($_SESSION['ga_token_time']) && (time() - $_SESSION['ga_token_time'] > 60)){
    unset($_SESSION['ga_token']);
    unset($_SESSION['ga_token_time']);
}

$result = mysqli_query($con,'SELECT token FROM user WHERE user_id='.$_SESSION['user_id']);
$row = $result->fetch_assoc();

if($row['token'] != '') {
    $client->refreshToken($row['token']);
    $_SESSION['ga_token']      = $client->getAccessToken();
    $_SESSION['ga_token_time'] = time();
} elseif (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['ga_token']      = $client->getAccessToken();
    $_SESSION['ga_token_time'] = time();
    $redirect                  = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['ga_token']) && trim($_SESSION['ga_token']) !== '') {
    $client->setAccessToken($_SESSION['ga_token']);
    $token = json_decode($_SESSION['ga_token']);
    if(isset($token->refresh_token)) {
        mysqli_query($con,'UPDATE user SET token="'.mysqli_real_escape_string($con, $token->refresh_token).'" WHERE user_id='.$_SESSION['user_id']);
    }
}

if ($client->getAccessToken()) {
    $analytics  = new Google_Service_Analytics($client);
    $accounts   = $analytics->management_accounts->listManagementAccounts();
    $properties = $analytics->management_webproperties->listManagementWebproperties('~all');
    $items      = $properties->getItems();
    $list = array();
    $i = 0;
    foreach ($items as $item) {
        $list[$i]['name']       = $item->getName();
        $list[$i]['nameurl']    = urlencode($name);
        $list[$i]['id']         = $item->getAccountId();
        $list[$i]['wpid']       = $item->getId();
        $list[$i]['linkurl']    = urlencode($item->getChildLink()->getHref());
        $i++;
    }
} else {
    $authUrl = $client->createAuthUrl();
    header('Location: '.$authUrl);
}

I already have started with this one

我已经从这个开始了

ConnectionsController.php

ConnectionsController.php

<?php
use App\helpers\Common;

class ConnectionsController extends BaseController{
public function getExistingLogins($id){
        $ga_user = DB::table('user')->select('*')->where('user_id', $id)->get();

        $client_id          = $ga_user[0]->client_id;
        $client_secret      = $ga_user[0]->client_secret;
        $token              = $ga_user[0]->token;
        $api_key            = 'API_KEY_HERE';
        $application_name   = 'APPLICATION_NAME';

        $return = new App\Services\GoogleAnalytics($client_id, $client_secret, $application_name, $api_key, $token);

        return $return->get();
    }
    return false;
}

App\Services\GoogleAnalytics.php

应用\ \ GoogleAnalytics.php服务

<?php
namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;

class GoogleAnalytics {

protected $client;
protected $service;
protected $url;

function __construct($client_id, $client_secret, $application_name, $api_key, $token) {
    $host = $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    $http = (isset($_SERVER['HTTP_SCHEMETYPE']) && $_SERVER['HTTP_SCHEMETYPE'] == 'https') ? 'https:' : 'http:';
    $this->url = $http . '//' . $host;

    /* Set config variables */
    $this->client = new \Google_Client();
    $this->client->setApplicationName($application_name);
    $this->client->setClientId($client_id);
    $this->client->setClientSecret($client_secret);
    $this->client->setRedirectUri($this->url);
    $this->client->addScope("https://www.googleapis.com/auth/analytics.readonly");
    $this->client->setApprovalPrompt('force');
    $this->client->setAccessType('offline');

    $this->client->refreshToken($token);

    $this->service = new \Google_Service_Analytics($this->client);
}

public function get(){        
    $accounts   = $this->service->management_accounts->listManagementAccounts();
    $properties = $this->service->management_webproperties->listManagementWebproperties('~all');
    $items      = $properties->getItems();
    $list = array();
    $i = 0;
    foreach ($items as $item) {
        $list[$i]['name']       = $item->getName();
        $list[$i]['nameurl']    = urlencode($name);
        $list[$i]['id']         = $item->getAccountId();
        $list[$i]['wpid']       = $item->getId();
        $list[$i]['linkurl']    = urlencode($item->getChildLink()->getHref());
        $i++;
    }
    return $list;
}

But I am having trouble with redirect. I am now stuck. How should I proceed? Any help is very much appreciated. Thanks.

但是我在重定向方面有问题。我现在被困住了。我该如何继续?非常感谢您的帮助。谢谢。

2 个解决方案

#1


1  

You can use

您可以使用

Google API PHP Client (Laravel Bundle)

谷歌API PHP客户端(Laravel Bundle)

Which is a much simpler way to integrate google-api.

这是集成google-api的更简单的方法。

#2


1  

There is a very versatile library available for google Analytics in laravel 5..

在laravel 5中有一个非常通用的谷歌分析库。

https://github.com/spatie/laravel-analytics

https://github.com/spatie/laravel-analytics

I have used this and it is working well for me..

我用过这个,它对我很有用。

#1


1  

You can use

您可以使用

Google API PHP Client (Laravel Bundle)

谷歌API PHP客户端(Laravel Bundle)

Which is a much simpler way to integrate google-api.

这是集成google-api的更简单的方法。

#2


1  

There is a very versatile library available for google Analytics in laravel 5..

在laravel 5中有一个非常通用的谷歌分析库。

https://github.com/spatie/laravel-analytics

https://github.com/spatie/laravel-analytics

I have used this and it is working well for me..

我用过这个,它对我很有用。