1

我正在尝试在 PHP 中获取某些 Google Analytics 帐户的所有配置文件。我正在使用 PEAR 中的 HTTP_Request2 类(使用 cURL 适配器,但我也尝试使用 Socket),当我尝试从https://www.google获取数据时,我不断收到“目标提要是只读的”错误。 com/analytics/feeds/accounts/default

我正在使用 ClientLogin 身份验证方法,据我所知,每个 API 请求都会发送正确的授权标头(我使用观察者类来测试正在发送的标头)。

这是我使用的代码(精简版,测试版):

require 'HTTP/Request2.php';


class GA {

    protected $email;
    protected $passwd;
    protected $auth_code;

    public function __construct($email = '', $passwd = '') {
        $this->email = $email;
        $this->passwd = $passwd;
    }

    public function authorize($email = '', $password = '', $force = false) {

        if (!$force and !empty($this->auth_code) and $email == $this->email and $password == $this->passwd) {
            return true;
        }

        unset($this->auth_code);

        !empty($email) or $email = $this->email;
        !empty($password) or $password = $this->passwd;

        if (empty($email) or empty($password)) {
            return false;
        }

        try {

            $response = $this->post(
                'https://www.google.com/accounts/ClientLogin',
                array(
                    'accountType' => 'GOOGLE',
                    'Email' => $this->email = $email,
                    'Passwd' => $this->passwd = $password,
                    'service' => 'analytics'
                )
            );

            if ($response->getStatus() == 200 and preg_match('/(?:^|[\n\r])Auth=(.*?)(?:[\n\r]|$)/', $response->getBody(), $match)) {

                $this->auth_code = $match[1];
                                    echo $this->auth_code;
                return true;
            }

        } catch (HTTP_Request2_Exception $e) {
            return false;
        }
    }

    public function call($url, array $params = array(), array $headers = array()) {

        if (!$this->auth_code && !$this->authorize($this->email, $this->passwd, true)) {
            return false;
        }

        $headers['Authorization'] = 'GoogleLogin auth=' . $this->auth_code;

        return $this->post($url, $params, $headers);
    }

    protected function post($url, array $params = array(), array $headers = array()) {

        $headers['GData-Version'] = '2';

        $request = new HTTP_Request2($url);
        $request->setAdapter('curl');
        $request->setConfig('ssl_verify_peer', false);
        $request->setHeader($headers);
        $request->setMethod(HTTP_Request2::METHOD_POST);
        $request->addPostParameter($params);

        return $request->send();
    }
}

$ga = new GA('*********@gmail.com', '*********');

var_dump($ga->call('https://www.google.com/analytics/feeds/accounts/default'));

提前致谢!

4

1 回答 1

1

回答我自己的问题:必须通过GET方法访问https://www.google.com/analytics/feeds/accounts/default 。 我的代码一直在使用POST

于 2010-01-22T14:45:26.277 回答