使用API​​无同意屏幕通过PHP将文件上传到Google云端硬盘

时间:2017-02-07 20:28:41

标签: php oauth-2.0 google-drive-api google-oauth

按照本教程中的步骤,我可以通过API将文件上传到我的Google云端硬盘,优先级是在没有用户确认同意的情况下上传文件。

How do I authorise an app (web or installed) without user intervention? (canonical ?)

但是,我注意到刷新令牌每次都必须更新,因此我寻找另一种解决方案来发送文件,而不会将同意屏幕发送给用户。

http://ben.akrin.com/?p=2080

在最初的几个小时内一切顺利,但现在它不会返回TOKEN,因此不再进行上传。



<?php

function get_access_token( $force_refresh=false ) {
    global $client_id, $client_secret, $refresh_token, $verbose ;

    if( $verbose ) { echo "> retrieving access token<br />" ; }

    $token_filename = "/tmp/access_token_" . md5( $client_id . $client_secret . $refresh_token ) ;
    $access_token = "" ;

    if( !file_exists($token_filename) || $force_refresh===true ) {

	    // no previous access token, let's get one
	    if( $verbose ) { echo ">   getting new one<br />" ; }

	    $ch = curl_init();
	    curl_setopt( $ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token" ) ;
	    curl_setopt( $ch, CURLOPT_PORT , 443 ) ;
		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ) ;
	    curl_setopt( $ch, CURLOPT_POST, 1 ) ;	    
	    curl_setopt( $ch, CURLOPT_POSTFIELDS, "client_id={$client_id}&client_secret={$client_secret}&refresh_token={$refresh_token}&grant_type=refresh_token" ) ;
	    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ) ;
	    curl_setopt( $ch, CURLOPT_HEADER, true ) ;
	    curl_setopt( $ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded") ) ;
		
		echo "Curl error: " . curl_error($ch) . "<br />";

	    $response = curl_exec( $ch ) ;
	    $response = parse_response( $response ) ;

	    // todo: make sure that we got a valid response before retrieving the access token from it

	    $access_token = json_decode( $response["body"] ) ;
	    $access_token = $access_token->access_token ;
	    file_put_contents( $token_filename, $access_token ) ;
	} else {

		// we already have something cached, with some luck it's still valid
	    $access_token = file_get_contents( $token_filename ) ;
	    if( $verbose ) { echo ">   from cache<br />" ; }
	}

	if( $access_token=="" ) {
		echo "ERROR: problems getting an access token<br />" ;
		exit( 1 ) ;
	}

    return  $access_token ;
}

?>
&#13;
&#13;
&#13;

是否可以在没有同意屏幕的情况下将我的应用程序与Google云端硬盘集成,而无需始终续订此TOKEN?

1 个答案:

答案 0 :(得分:2)

我写了你提到的答案。

您误解了刷新令牌是什么。获得刷新令牌后,您应该安全地存储它并在需要访问令牌时重复使用它。刷新令牌不会过期 - 通常不会,见下文。所以,当你说“我注意到刷新令牌必须每次都更新”时,情况并非如此。

您通常只会在第一次请求时获得刷新令牌。后续请求将返回null。用户需要撤销授权并重新授权以获取另一个令牌。但同样,您应该存储您获得的第一个刷新令牌并无限期地重复使用。

即将到期的刷新令牌...... 虽然刷新令牌的使用寿命很长,但Google有时会过期。一种情况(我相信传闻)是如果用户更改密码,令牌可能会过期。这是有意义的,因为存储的刷新令牌大致类似于存储的用户名/密码。我也看到令牌没有明显的原因,在创建后6个月左右到期。