PHP使用OAuth2实现Google登录

后端开发PHP 2073

首先登陆Google Developers console获取开发者接口权限,如果你之前没有申请过你可能需要创建一个项目,然后根据提示申请到OAuth Client IDClient credentials > OAuth client ID ),最终拿到Client ID、Client Secret 这两个重要的认证参数,对了别忘记配置好Redirect URI,这是Google验证完成后跳转的URL。

下面正式进入主题

安装Google PHP SDK Client Library

先准备好composer,如果没有的话自行安装一下,这里注意如果是Windows环境中composer用不了的话(卡着不动)可以试试把composer,composer.bat,composer.phar这三个文件拷到项目目录中。

composer require google/apiclient:"^2.0"

最新版本可参考:official API page.

登录功能的实现

假设我们在上面google开发者控制台中申请OAuth Client ID的时候配置的跳转地址是http://localhost/redirect.php,那么现在我们在项目中创建redirect.php

<?php
require_once 'vendor/autoload.php';
 
// init configuration
$clientID = '<YOUR_CLIENT_ID>';
$clientSecret = '<YOUR_CLIENT_SECRET>';
$redirectUri = '<REDIRECT_URI>';
  
// create Client Request to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
 
// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  $client->setAccessToken($token['access_token']);
  
  // get profile info
  $google_oauth = new Google_Service_Oauth2($client);
  $google_account_info = $google_oauth->userinfo->get();
  $email =  $google_account_info->email;
  $name =  $google_account_info->name;
 
  // now you can use this profile info to create account in your website and make user logged in.
} else {
  echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
?>

一些说明:

Google SDK的入口文件

require_once'vendor/autoload.php';

初始化配置

// init configuration
$clientID = '<YOUR_CLIENT_ID>';
$clientSecret = '<YOUR_CLIENT_SECRET>';
$redirectUri = '<REDIRECT_URI>';

实例化Google_Client对象

// create Client Request to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);

获取用户信息

$client->addScope("email");
$client->addScope("profile");

最后是登录逻辑的处理

// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  $client->setAccessToken($token['access_token']);
  
  // get profile info
  $google_oauth = new Google_Service_Oauth2($client);
  $google_account_info = $google_oauth->userinfo->get();
  $email =  $google_account_info->email;
  $name =  $google_account_info->name;
 
  // now you can use this profile info to create account in your website and make user logged in.
} else {
  echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}

扩展资料:

Post Comment