문제 설명
새로 고침 토큰을 사용하여 백그라운드에서 인증을 받고 액세스 토큰을 얻는 방법은 무엇입니까? (How to use refresh token to get authorized in background and getting access token?)
refreshToken을 사용하여 accessToken을 얻으려고 합니다. 아래에 제 코드를 게시했습니다. 누군가 안내해 주세요.
이는 내가 개발 중인 WordPress 플러그인에서 가져온 것이므로 pageViews 및 pagePath만 검색하면 되므로 그렇지 않습니다. 사용 가능한 플러그인 사용을 선호합니다.
OAuth 갱신 토큰을 사용하여 새 액세스 토큰 얻기 ‑ Google API
if( isset( $this‑>options['authenication_code'] ) ){ //plugin setting page settings
global $wpdb;
$resultset = $wpdb‑>get_row( 'SELECT `refreshToken` FROM ' . $wpdb‑>prefix . 'analyticaAnalytics WHERE authenication_code ="' . $this‑>options["authenication_code"] . '"', ARRAY_A );
var_dump( $resultset['refreshToken'] ); //retrieved refreshToken from database
if ($client‑>isAccessTokenExpired()) { //boolean true
$client‑>refreshToken( $resultset['refreshToken'] );
var_dump( $client );//getting blank
}
}
../google‑api‑php‑client/src/Google/Auth/ oauth2.php
private function refreshTokenRequest($params)
{
if (isset($params['assertion'])) {
$this‑>client‑>getLogger()‑>info(
'OAuth2 access token refresh with Signed JWT assertion grants.'
);
} else {
$this‑>client‑>getLogger()‑>info('OAuth2 access token refresh');
}
$http = new Google_Http_Request(
self::OAUTH2_TOKEN_URI,
'POST',
array(),
$params
);
$http‑>disableGzip();
$request = $this‑>client‑>getIo()‑>makeRequest($http);
//var_dump( $request );exit;//response 400, invalid grant
$code = $request‑>getResponseHttpCode();
$body = $request‑>getResponseBody();
if (200 == $code) {
$token = json_decode($body, true);
if ($token == null) {
throw new Google_Auth_Exception("Could not json decode the access token");
}
if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
throw new Google_Auth_Exception("Invalid token format");
}
if (isset($token['id_token'])) {
$this‑>token['id_token'] = $token['id_token'];
}
$this‑>token['access_token'] = $token['access_token'];
$this‑>token['expires_in'] = $token['expires_in'];
$this‑>token['created'] = time();
} else {
throw new Google_Auth_Exception("Error refreshing the OAuth2 token, message: '$body'", $code);
}
}
많은 시간을 보낸 후 $request = $this‑>client‑>getIo()‑>에 대한 응답 코드 400 오류가 발생했습니다. makeRequest($http);
이는 잘못된 권한입니다.
참조 솔루션
방법 1:
This is how , I solved the problem, We need to store the refreshToken in our database and using that refreshToken, We can get another accessToken .which can be used to get the result and it does not need another authentication .
<?php
$client = new Google_Client();
$client‑>setAuthConfigFile(plugin_dir_url( __FILE__ ) . '/client_secrets.json');
$client‑>setRedirectUri( site_url() . '/wp‑admin/admin.php?page=analytica‑admin‑settings');
$client‑>addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client‑>setIncludeGrantedScopes(true);
$client‑>setAccessType('offline');
if ( isset( $_GET['code'] )) {
if($client‑>isAccessTokenExpired()){
$client‑>authenticate($_GET['code']);
$accessToken = $client‑>getAccessToken();
$refreshToken = $client‑>getRefreshToken();
$analytica_tokens = json_encode( array( 'time' => current_time( 'mysql' ),'accessToken' => $accessToken, 'refreshToken' => $refreshToken ) );
update_option( 'analytica_tokens', $analytica_tokens );
}
} else {
$resultset = json_decode(get_option('analytica_tokens'));
if ($client‑>isAccessTokenExpired()) {
if( isset( $resultset ) ){
$refreshToken = $resultset‑>refreshToken;
$client‑>refreshToken( $refreshToken );
$accessToken = $client‑>getAccessToken();
$analytica_tokens = json_encode( array( 'time' => current_time( 'mysql' ), 'accessToken' => $accessToken, 'refreshToken' => $refreshToken ) );
update_option( 'analytica_tokens', $analytica_tokens );
} else {
echo 'You need to reauthorize the application to get the analytics report.';
}
}
}
$auth_url = $client‑>createAuthUrl();
?>
<a class="connect‑to‑google‑analytics" href='<?php echo $auth_url; ?>' id="loginText">Connect To Your Google Analytics Account </a>
<?php
if( isset($accessToken) ){
$_SESSION['access_token'] = $accessToken ? $accessToken : $refreshToken;
$client‑>setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
$profile = $this‑>getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
$this‑>results = $this‑>getResults($analytics, $profile);
}
?>
(by Prafulla Kumar Sahu、Prafulla Kumar Sahu)