mcg / google-auth-service
PHP 库,用于通过 Google 的 REST API 方便地实现向 Google 服务(如 Gmail、Google Drive)的认证。
Requires
- php: ^7.2
- google/apiclient: ^2.8
Requires (Dev)
- phpunit/phpunit: ^8.5
This package is not auto-updated.
Last update: 2024-09-25 12:07:25 UTC
README
Google 服务认证库
mcg/google-auth-service
PHP 库,用于通过 Google 的 REST API 方便地实现向 Google 服务(如 Gmail、Google Drive)的认证。
📝 目录
🧐 关于
这些类有助于简化获取 Google 服务客户端以及执行 Google 认证的过程。
🏁 要求
在使用此类之前,需要创建 Google OAuth 凭据,方法是下载 APIs 控制台的 json 文件。
更多信息请参阅以下链接
https://developers.google.com/identity/protocols/oauth2
下载我们的凭据文件后,将其添加到我们的项目中,可以是项目的根目录或任何所需的目录。默认情况下,库在项目根目录中查找 "./credentials.json" 文件。
以下示例假设凭据文件位于项目根目录中。
安装
安装使用 composer 进行
composer require mcg/google-auth-service
🔧 通过 API 认证到 GMail
假设凭据文件位于项目根目录中,且文件名为 "credentials.json",则需要为此应用添加权限并创建用于生成 OAuth 认证的 token 文件。
为了初始化此认证,需要调用 Google 页面,让用户授权此应用。
为此,我们可以从我们的控制台使用以下代码
$url=AuthGoogleMailService::getActivationURL();
print_r($url);
AuthGoogleMailService::setActivationCode(readline());
结果将在项目根目录中生成一个包含 Google 生成的 OAuth token 的 json 文件。
如果我们想配置凭据文件和 token 的路径,我们可以使用以下代码
$AuthGoogleMailService= new AuthGoogleMailService();
$AuthGoogleMailService->setCredentialsJsonPath("./credenciales/credentialsGmail.json");
$AuthGoogleMailService->setTokenPath("./tokens/tokenGmail.json");
$MailClient=$AuthGoogleMailService->getClient();
如果我们想配置更多属性,我们有以下选项
$AuthGoogleMailService= new AuthGoogleMailService();
$AuthGoogleMailService->setCredentialsJsonPath("./credenciales/credentialsGmail.json");
$AuthGoogleMailService->setTokenPath("./tokens/tokenGmail.json");
$AuthGoogleMailService->setClientName("Aplication or client name");
$AuthGoogleMailService->setScope(Google_Service_Gmail::GMAIL_READONLY);
$AuthGoogleMailService->setAccessType("offline");
$AuthGoogleMailService->setSetPrompt("select_account consent");
$MailClient=$AuthGoogleMailService->getClient();
通过 API 获取 Gmail 邮件
要使用 API 获取 GMAIL 邮件,请参考以下示例
//Obtenemos el servicio de gmail
$GoogleClient = (new AuthGoogleMailService())->getClient();
$Gmailservice = new Google_Service_Gmail($GoogleClient);
//parametros para la obtencion de los correos
$options = array('labelIds' => 'INBOX', 'maxResults' => 10, 'q' => 'is:unread');
//Obtiene los mensajes
$messages = $Gmailservice->users_messages->listUsersMessages('me', $options);
foreach ($messages as $message) {
//Obtiene lo escencial del mensaje
$Emailmessage = $Gmailservice->users_messages->get('me', $message['id'], ['format' => 'FULL']);
foreach($Emailmessage['payload']->getHeaders() as $header){
print_r($header->name." : ".$header->value . PHP_EOL);
}
}