如何使用cronjob生成Google访问令牌?

时间:2019-12-06 11:08:51

标签: php google-api cron google-oauth

我已使用此脚本生成了访问令牌

这里是代码

$OAuth = array(
    'oauth_uri' => 'https://accounts.google.com/o/oauth2/auth',
    'client_id' => '',
    'client_secret' => '',
    'access_type' => 'online',
    'redirect_uri' => '',   uri()
    'oauth_token_uri' => 'https://accounts.google.com/o/oauth2/token'
);
$token = array(
    'access_token' => '',
    'token_type' => '',
    'expires_in' => '',
    'refresh_token' => ''
);
$title = 'No Code';
$AuthCode = 'Null';

$error = _get_url_param($_SERVER['REQUEST_URI'], 'error');
if ($error != NULL)
{   $title = $error;
}
else
{   
    $AuthCode = _get_url_param($_SERVER['REQUEST_URI'], 'code');
    if ($AuthCode == NULL)
    {   
        $OAuth_request = _formatOAuthReq($OAuth, "https://www.googleapis.com/auth/indexing");
        header('Location: ' . $OAuth_request);
        exit; 
    }
    else
    {
        $title = 'Got Authorization Code';
        $token_response = _get_auth_token($OAuth, $AuthCode);
        $json_obj = json_decode($token_response);
        $token['access_token'] = $json_obj->access_token;
        $token['token_type'] = $json_obj->token_type;
        $token['expires_in'] = $json_obj->expires_in;
        $token['refresh_token'] = $json_obj->refresh_token;
        echo 'access_token = ' . $json_obj->access_token;
    }
}
function _get_auth_token($params, $code)
{
    $url = $params['oauth_token_uri'];
    $fields = array(
        'code' => $code,
        'client_id' => $params['client_id'],
        'client_secret' => $params['client_secret'],
        'redirect_uri' => $params['redirect_uri'],
        'grant_type' => 'authorization_code'
    );
    $response = _do_post($url, $fields);
    return $response;
}
function _formatOAuthReq($OAuthParams, $scope)
{
    $uri = $OAuthParams['oauth_uri'];
    $uri .= "?client_id=" . $OAuthParams['client_id'];
    $uri .= "&redirect_uri=" . $OAuthParams['redirect_uri'];
    $uri .= "&scope=" . $scope;
    $uri .= "&response_type=code";
    $uri .= "&access_type=offline";
    return $uri;
}

当我在Chrome浏览器中运行脚本时,它可以工作。

但是当我设置了cronjob却无法正常工作时,并且没有生成令牌

如何使用cronjob生成Google访问令牌?

希望大家能理解并能帮助我:)。

0 个答案:

没有答案