【问题标题】:Where do I get the Authorized Gmail API service instance?我从哪里获得授权的 Gmail API 服务实例?
【发布时间】:2018-04-04 18:38:15
【问题描述】:

我正在尝试使用 Gmail API 和 php 更新标签。

我已经查看了here 的问题,但它是关于 python 的,对我来说没有多大意义。

我指的是代码here

具体来说,这个:

    /**
 * Update an existing Label.
 *
 * @param  Google_Service_Gmail $service Authorized Gmail API instance.
 * @param  string $userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  string $labelId ID of Label to update.
 * @param  string $labelName Updated name.
 * @param  string $labelListVisibility Updated Label list visibility.
 * @param  string $messageListVisibility Updated Message list visibility.
 * @return Google_Service_Gmail_Label updated Label.
 */
function updateLabel($service, $userId, $labelId, $labelName,
  $labelListVisibility, $messageListVisibility) {
  $label = new Google_Service_Gmail_Label();
  $label->setName($labelName);
  $label->setLabelListVisibility($labelListVisibility);
  $label->setMessageListVisibility($messageListVisibility);
  try {
    $label = $service->users_labels->update($userId, $labelId, $label);
    print 'Label with ID: ' . $labelId . ' successfully updated.';
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }
  return $label;
}

我想我已经弄清楚了所有参数,但是它说的是哪里,

* @param  Google_Service_Gmail $service Authorized Gmail API instance.

我不知道“授权的 Gmail API 实例”指的是什么。

我已通过 API 连接并进行了身份验证(我可以列出标签),所以我猜它正在寻找对我的连接的一些参考。但我不知道在哪里可以找到或如何表达。

以下代码用于列出标签(gauth.php):

    <?php
session_start();

require_once('settings.php');
require_once('google-login-api.php');

// Google passes a parameter 'code' in the Redirect Url
if(isset($_GET['code'])) {
    try {
        $gapi = new GoogleLoginApi();

        // Get the access token 
        $data = $gapi->GetAccessToken(CLIENT_ID, CLIENT_REDIRECT_URL, CLIENT_SECRET, $_GET['code']);

        // Get user information
        $user_labels = $gapi->ListUserLabels($data['access_token']);

        $labels_array = $user_labels["labels"];

        $i = 0;

        while($i <= count($labels_array)) 
            {
            if($labels_array[$i]['type'] == "user")
                {
                echo $labels_array[$i]['name']." - ".$labels_array[$i]['id'];
                echo'<br />';
                }
            $i++;
            } 


        // Now that the user is logged in you may want to start some session variables
        $_SESSION['logged_in'] = 1;

        // You may now want to redirect the user to the home page of your website
        // header('Location: home.php');
    }
    catch(Exception $e) {
        echo $e->getMessage();
        exit();
    }
}

这里是 google-login-api.php:

class GoogleLoginApi
{
    public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {  
        $url = 'https://accounts.google.com/o/oauth2/token';            

        $curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
        $ch = curl_init();      
        curl_setopt($ch, CURLOPT_URL, $url);        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
        curl_setopt($ch, CURLOPT_POST, 1);      
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);    
        $data = json_decode(curl_exec($ch), true);
        $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);      
        if($http_code != 200) 
            throw new Exception('Error : Failed to receieve access token');

        return $data;
    }

    public function ListUserLabels($access_token) { 
        //$url = 'https://www.googleapis.com/plus/v1/people/me';    
        $url = 'https://www.googleapis.com/gmail/v1/users/me/labels';       

        $ch = curl_init();      
        curl_setopt($ch, CURLOPT_URL, $url);        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
        $data = json_decode(curl_exec($ch), true);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);     
        if($http_code != 200) 
            throw new Exception('Error : Failed to get user information');

        return $data;
    }
}

还有settings.php:

/* Google App Client Id */
define('CLIENT_ID', 'xxxxxxxxxxxxxxxx.apps.googleusercontent.com');

/* Google App Client Secret */
define('CLIENT_SECRET', 'xxxxxxxxxxxxxxxxxxx');

/* Google App Redirect Url */
define('CLIENT_REDIRECT_URL', 'http://localhost:8888/xxxxxxxx/gauth/gauth.php');

【问题讨论】:

    标签: php gmail gmail-api


    【解决方案1】:

    这也把我绊倒了!谷歌这些天似乎只是不关心 PHP,对吧?他们的文档真的和人们说的一样糟糕。

    $gmail = new Google_Service_Gmail($client);
    

    这就是我为克服这个障碍而做的事情。我认为他们的措辞的意思是您必须像上面那样创建一个特定的服务对象,而不仅仅是使用客户端对象本身?它可以更好地表达,或扩展。

    祝你好运! (你需要它!)

    【讨论】:

      【解决方案2】:

      每次只需使用有效凭据调用此函数即可获取访问令牌

      function GetRefreshedAccessToken($client_id, $refresh_token, $client_secret) {  
      
          $url_token = 'https://www.googleapis.com/oauth2/v4/token';          
      
          $curlPost = 'client_id=' . $client_id . '&client_secret=' . $client_secret . '&refresh_token='. $refresh_token . '&grant_type=refresh_token';
          $ch = curl_init();      
          curl_setopt($ch, CURLOPT_URL, $url_token);      
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
          curl_setopt($ch, CURLOPT_POST, 1);      
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);    
          $data = json_decode(curl_exec($ch), true);  //print_r($data);
          $http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);  
      
          if($http_code != 200) 
              throw new Exception('Error : Failed to refresh access token');
      
          return $data;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-22
        • 1970-01-01
        • 2014-11-02
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多