PHP 对接google第三方登录

1、获取ID+秘钥 https://console.developers.google.com/

首先需要先新增一个凭据:

创建凭据 -> OAuth 客户端 ID -> 网页应用,之后输入 JavaScript 来源、重定向 URI

2、下载SDK
https://github.com/googleapis/google-api-php-client/releases

3、创建登录链接

public function loginGoogle(){     require '../lib/internal/google-api-php-client--PHP7.0/vendor/autoload.php';  $params = $this->getRequest()->getParams();$googleConfig = $this->snsaccount->googleAccount();$clientID = $googleConfig['Client_ID'];$clientSecret = $googleConfig['Client_Secret'];$redirectUri = $googleConfig['callBack'];  //Google console 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 Flowif (isset($params['code'])) {$token = $client->fetchAccessTokenWithAuthCode($params['code']);$client->setAccessToken($token['access_token']);// get profile info$google_oauth = new \Google_Service_Oauth2($client);$google_account_info = $google_oauth->userinfo->get();//next...} else {$loginUrl = $client->createAuthUrl();header('location:'.$loginUrl);    }}

4、回调方法

public function loginGoogleRedirect(){require '../lib/internal/google-api-php-client--PHP7.0/vendor/autoload.php';  $params = $this->getRequest()->getParams();$googleConfig = $this->snsaccount->googleAccount();$clientID = $googleConfig['Client_ID'];$clientSecret = $googleConfig['Client_Secret'];$redirectUri = $googleConfig['callBack'];// 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 Flowif (isset($params['code'])) {$token = $client->authenticate($params['code']);$client->setAccessToken($token['access_token']);$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$token['access_token'];$json = $this->httpGet($q);$userInfoArray = json_decode($json,true);// print_r($userInfoArray);$type = 'google';$client_id = $userInfoArray['id'];$client_name = $userInfoArray['name'];$client_picture = $userInfoArray['picture'];$client_email = $userInfoArray['email'];//next...}}
private function httpGet($url) {$curl = curl_init();curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);curl_setopt($curl, CURLOPT_TIMEOUT, 500);curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);curl_setopt($curl, CURLOPT_URL, $url);$res = curl_exec($curl);curl_close($curl);return $res;}

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部