Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
googleapi访问令牌PHP_Php_Google Api_Google Analytics Api_Google Authentication - Fatal编程技术网

googleapi访问令牌PHP

googleapi访问令牌PHP,php,google-api,google-analytics-api,google-authentication,Php,Google Api,Google Analytics Api,Google Authentication,我正在验证Google Analytics帐户并成功检索数据。但是,我希望每周运行一次cronjob以从经过身份验证的帐户获取数据,但访问令牌无效 我读过一些关于刷新令牌的内容,但我不确定如何使用它们。我应该在数据库中存储哪些数据,以便随时访问经过身份验证的帐户?要获取您的访问令牌和刷新令牌,请首先创建一个包含以下代码的文件: <?php if (isset($_GET['code'])) { // try to get an access token $code = $

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


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

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

<?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);
}

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

您需要存储refreshtoken,然后在需要可能的副本时可以获得新的访问令牌
{
  "access_token" : YOUR_ACCESS_TOKEN,
  "token_type" : "Bearer",
  "expires_in" : 3600,
  "refresh_token" : YOUR_REFRESH_TOKEN
}