【问题标题】:Google API Access Token PHP谷歌 API 访问令牌 PHP
【发布时间】:2014-10-17 14:06:48
【问题描述】:

我正在验证 Google Analytics(分析)帐户并成功检索数据。但是,我想每周运行一次 cronjob 从经过身份验证的帐户中获取数据,但访问令牌无效。

我已经阅读了一些关于刷新令牌的内容,但我不确定如何使用它们。我应该将哪些数据存储在我的数据库中以便随时访问经过身份验证的帐户?

【问题讨论】:

标签: php google-api google-analytics-api google-authentication


【解决方案1】:

要获取您的访问令牌和刷新令牌,首先创建一个包含以下代码的文件:

<?php

if (isset($_GET['code'])) {
    // try to get an access token
    $code = $_GET['code'];
    $url = 'https://accounts.google.com/o/oauth2/token';
    $params = array(
        "code" => $code,
        "client_id" => YOUR_CLIENT_ID,
        "client_secret" => YOUR_CLIENT_SECRET,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
        "grant_type" => "authorization_code"
    );

    $ch = curl_init();
    curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
    curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
    curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
    $output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    if ($info['http_code'] === 200) {
        header('Content-Type: ' . $info['content_type']);
        return $output;
    } else {
        return 'An error happened';
    }
} else {

    $url = "https://accounts.google.com/o/oauth2/auth";

    $params = array(
        "response_type" => "code",
        "client_id" => YOUR_CLIENT_ID,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
        "scope" => "https://www.googleapis.com/auth/plus.me"
    );

    $request_to = $url . '?' . http_build_query($params);

    header("Location: " . $request_to);
}

然后,将 YOUR_CLIENT_IDYOUR_CLIENT_SECRET 替换为您的客户端 ID 和客户端密码。

确保您的范围正确。例如,如果您想访问 Analytics,则应该是 https://www.googleapis.com/auth/analytics

如果您运行此代码,您应该会看到 OAuth2 批准屏幕。现在,按Accept,您应该会得到如下所示的结果:

{
  "access_token" : YOUR_ACCESS_TOKEN,
  "token_type" : "Bearer",
  "expires_in" : 3600,
  "refresh_token" : YOUR_REFRESH_TOKEN
}

结果可能包含其他字段,具体取决于您申请的范围。

【讨论】:

    猜你喜欢
    • 2019-07-07
    • 2017-11-13
    • 2013-07-20
    • 2012-11-13
    • 1970-01-01
    • 2018-07-24
    • 2017-04-12
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多