Клиент для PHP-клиента Google API и вложенные требования?

Я пытаюсь внедрить Google Analytics API в плагин панели управления WordPress.

Следуя простейшей реализации для использования Google API для PHP в первый раз, она не работает сразу практически на первом шаге.

Согласно учебнику README.md, мое приложение, расположенное рядом с папкой библиотеки, должно загружать библиотеку следующим образом:

require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';

$client = new Google_Client();

Теперь структура библиотеки в моем приложении (плагине):

myapp.php
/Google
/Google/Client.php
/Google/otherfolders/otherfiles.php

и мое приложение пытается загрузить библиотеку в соответствии с require_once выше. Но, конечно, Client.php имеет много вызовов require_once, таких как:

require_once 'Google/Auth/AssertionCredentials.php';

Которые, похоже, игнорируют свою позицию — уже внутри /Google.

Итак, я получаю ошибки:

PHP Warning: require_once(Google/Auth/AssertionCredentials.php) [<a href='function.require-once'>function.require-once</a>]: failed to open stream: No such file or directory in <wpengine host path removed>/wp-content/plugins/mmstats/Google/Client.php on line 18

и

PHP Fatal error: require_once() [<a href='function.require'>function.require</a>]: Failed opening required 'Google/Auth/AssertionCredentials.php' (include_path='.:/usr/share/php:/usr/share/pear') in <wpengine host path removed>/wp-content/plugins/mmstats/Google/Client.php on line 18

Этот PHP указан как «бета», но, конечно, я делаю что-то не так, а не проблема с Client.php.

Любая помощь приветствуется!


person AT Design    schedule 11.06.2014    source источник


Ответы (1)


Google Director должен находиться в том же каталоге, что и ваш файл. Если это не так, вам придется редактировать все required_once самостоятельно. Вот некоторый рабочий код для использования с Google Analytics API.

<?php         
require_once 'Google/Client.php';     
require_once 'Google/Service/Analytics.php';       
session_start();      
$client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $client->setDeveloperKey("{devkey}");  
    $client->setClientId('{clientid}.apps.googleusercontent.com');
    $client->setClientSecret('{clientsecret}');
    $client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
    $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));

    //For loging out.
    if ($_GET['logout'] == "1") {
    unset($_SESSION['token']);
       }   

    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {

        $client->authenticate($_GET['code']);  
        $_SESSION['token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    // Step 1:  The user has not authenticated we give them a link to login    
    if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
        $authUrl = $client->createAuthUrl();
        print "<a class='login' href='$authUrl'>Connect Me!</a>";
        }        

    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
        print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
        $client->setAccessToken($_SESSION['token']);
        $service = new Google_Service_Analytics($client);    

        // request user accounts
        $accounts = $service->management_accountSummaries->listManagementAccountSummaries();

       foreach ($accounts->getItems() as $item) {
        echo "Account: ",$item['name'], "  " , $item['id'], "<br /> \n";        
        foreach($item->getWebProperties() as $wp) {
            echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WebProperty: ' ,$wp['name'], "  " , $wp['id'], "<br /> \n";    

            $views = $wp->getProfiles();
            if (!is_null($views)) {
                foreach($wp->getProfiles() as $view) {
                //  echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;View: ' ,$view['name'], "  " , $view['id'], "<br /> \n";    
                }
            }
        }
    } // closes account summaries

    }
 print "<br><br><br>";
 print "Access from google: " . $_SESSION['token']; 
?>

Вы можете найти руководство по этому коду на странице Google Oauth2 PHP, там есть небольшой тест приложение внизу, где вы можете увидеть, как оно работает.

person DaImTo    schedule 11.06.2014