2016-03-04 93 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