jeudi 12 novembre 2015

Retrieving google analytics data with single authorization and with a button click

I have created a custom plugin to retrieve google analytics data as I need only page view and page link, I do not want to use any available plugins.

For now I can retrieve the data but just after wp-login I need to authorize the plugin and get the data; I want to get the data on a button click on plugin setting page . The user will authenticate the plugin once and when ever he will visit the setting page he can see the page links and page view.

Please give some idea how I can achieve this.

main file

<?php
/**
* Plugin Name:  
* Plugin Author:  
* Plugin URI:  
*/
require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');

session_start();

class Analytica_Analytic
{
    /**
     * Holds the values to be used in the fields callbacks
     */
    private $options;

    /**
     * Start up
     */
    public function __construct()
    {
        add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );

        $client = new Google_Client();

        $client->setAuthConfigFile(plugin_dir_url( __FILE__ ) . '/client_secrets.json');
        $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

          // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);

            // Create an authorized analytics service object.
            $analytics = new Google_Service_Analytics($client);
            // Get the first view (profile) id for the authorized user.
            $profile = $this->getFirstProfileId($analytics);

            // Get the results from the Core Reporting API and print the results.
            $this->results = $this->getResults($analytics, $profile); 
        } else {


            $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/mysite/wp-content/plugins/myplugin/oauth2callback.php';
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

        }
    }

    /**
     * Add options page
     */
    public function add_plugin_page()
    {
        // This page will be under "Settings"
        add_utility_page(
            'Analytica', 
            'Analytica', 
            'manage_options', 
            'analytica-admin-settings', 
            array( $this, 'create_admin_page' ), 'dashicons-chart-area'
        );
    }

    /**
     * Options page callback
     */
    public function create_admin_page()
    {
        // Set class property
        $this->options = get_option( 'my_option_name' );
        ?>
        <div class="wrap">
            <h2>Analytica Reports</h2>           
            <form method="post" action="options.php">
            <?php
              submit_button( 'authorize', 'primary', 'authorize', false, '' ); // on clicking this I want to get the data
            ?>
            </form>
        </div>
        <div class="analytica-report">
            <?php
               $this->printDataTable($this->results); //here I am getting the data now
            ?>
        </div>
        <?php
    }

    /**
     * Register and add settings
     */


    public function getFirstprofileId(&$analytics) {
      // Get the user's first view (profile) ID.

      // Get the list of accounts for the authorized user.
      $accounts = $analytics->management_accounts->listManagementAccounts();

       if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[0]->getId();

        // Get the list of properties for the authorized user.
        $properties = $analytics->management_webproperties
            ->listManagementWebproperties($firstAccountId);

        if (count($properties->getItems()) > 0) {
          $items = $properties->getItems();
          $firstPropertyId = $items[0]->getId();

          // Get the list of views (profiles) for the authorized user.
          $profiles = $analytics->management_profiles
              ->listManagementProfiles($firstAccountId, $firstPropertyId);

          if (count($profiles->getItems()) > 0) {
            $items = $profiles->getItems();

            // Return the first view (profile) ID.
            return $items[0]->getId();

          } else {
            throw new Exception('No views (profiles) found for this user.');
          }
        } else {
          throw new Exception('No properties found for this user.');
        }
      } else {
        throw new Exception('No accounts found for this user.');
      }
    }

    public function getResults(&$analytics, $profileId) {
      // Calls the Core Reporting API and queries for the number of sessions
      // for the last seven days.
      return $analytics->data_ga->get(
          'ga:' . $profileId,
          '7daysAgo',
          'today',
          'ga:pageviews',

          array('dimensions' => 'ga:pagePath') );
    }

    public function printDataTable(&$results) {

      if (count($this->results->getRows()) > 0) {
        $table = '';
        $table .= '<table>';

        // Print headers.
        $table .= '<tr>';

        foreach ($this->results->getColumnHeaders() as $header) {
          $table .= '<th>' . $header->name . '</th>';
        }
        $table .= '</tr>';

        // Print table rows.
        foreach ($this->results->getRows() as $row) {
          $table .= '<tr>';
            foreach ($row as $cell) {
              $table .= '<td>'
                     . htmlspecialchars($cell, ENT_NOQUOTES)
                     . '</td>';
            }
          $table .= '</tr>';
        }
        $table .= '</table>';

      } else {
        $table .= '<p>No Results Found.</p>';
      }
      print $table;
    }
}

if( is_admin() ){
    $analytica = new Analytica_Analytic();
}

oauth2callback.php

<?php
require_once 'google-api-php-client/src/Google/autoload.php';

// Start a session to persist credentials.
session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/mysite/wp-content/myplugin/analytica/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/mysite/wp-admin/admin.php?page=analytica-admin-settings';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire