2016-03-04 91 views
2

我从这里使用Yii和yi的谷歌API yii google api。我想获取与此API联系人列表但这引发错误代码已被兑换yii

stdClass的对象([错误] => invalid_grant [ERROR_DESCRIPTION] =>代码 已经兑现。)

我像这样使用

public function actionIndex() 
    { 
     $client = Yii::app()->GoogleApis->client; 
     $client -> setAccessType('online'); 
     $client -> setScopes('https://www.google.com/m8/feeds'); 
     $client->authenticate(); 

     if (isset($_GET['code'])) { 
      $auth_code = $_GET["code"]; 
      Yii::app()->session['auth_token']= $auth_code; 
      $this->redirect(array('/addcontacts/searchsuggesions')); 
     } 
     $this->render('index'); 
    } 

public function actionSearchsuggesions() 
    { 
     if(Yii::app()->session['auth_token']) 
     { 
      $auth_code = Yii::app()->session['auth_token']; 
      $max_results = 200; 
      $fields=array(
       'code'=> urlencode($auth_code), 
       'client_id'=> urlencode('**********'), 
       'client_secret'=> urlencode('**********'), 
       'redirect_uri'=> urlencode('http://localhost/addcontacts'), 
       'grant_type'=> urlencode('authorization_code') 
      ); 
      $post = ''; 
      foreach($fields as $key=>$value) 
      { 
       $post .= $key.'='.$value.'&'; 
      } 
      $post = rtrim($post,'&'); 
      $result = $this->curl('https://accounts.google.com/o/oauth2/token',$post); 
      $response = json_decode($result); 
      print_r($response);die; 
     } 
    } 

我不知道我在哪里错了。如果有人有线索请告诉我。

+1

也许这个链接可以帮助你。此人努力为您的问题寻求解决方案。 http://stackoverflow.com/questions/33754177/google-analytics-custom-plugin-getting-error-invalid-grant – izk

+0

但没有答案。:( – MKD

+0

该代码已被赎回错误意味着您正在尝试使用一个授权码已经被使用,一个授权码只能使用一次,当你提交OAuth请求来获取刷新令牌时,请确保你使用请求中传递的授权码到oauth2_callback – RK12

回答

1

我已经解决了这个问题。我只需要使用函数来获取访问令牌的功能$client->getAccessToken()

public function actionIndex() 
    { 
     $client = Yii::app()->GoogleApis->client; 
     $client -> setAccessType('online'); 
     $client -> setScopes('https://www.google.com/m8/feeds'); 
     $client->authenticate(); 

     if (isset($_GET['code'])) { 

      $accesstoken=json_decode($client->getAccessToken()); 
      $accesstoken=$accesstoken->access_token; 
      Yii::app()->session['accesstoken']=$accesstoken; 
      $this->redirect(array('/')); 
     } 
     $this->render('index'); 
    } 
+0

很好地完成了。我只提供了一个链接,所以没有做太多。快乐你解决它! – izk

+0

但这帮助我发现不需要再次获取访问令牌。再次感谢 :) – MKD