问题遇到的现象和发生背景
公司需求调谷歌第三方登录,前端获取到授权码给服务器处理,用授权码获取token再获取用户信息
问题相关代码,请勿粘贴截图
public function goolelogin(Request $request)
{
$data = $request->post();
$code = $data['code'];
$client = new \Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend
$token = $client->fetchAccessTokenWithAuthCode($code);
var_dump($token);
}
运行结果及报错内容
cURL error 60: SSL certificate problem: self signed certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://oauth2.googleapis.com/token
我的解答思路和尝试过的方法
禁止ssl验证
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
代码改写为
public function executeCall($url, $data = null, array $options = array())
{
$header = isset($options['header']) && is_array($options['header']) ? $options['header'] : [];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$useheader = [
'Content-Type: application/x-www-form-urlencoded'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $useheader);
$result = curl_exec($ch);
error_log(curl_errno($ch) . " - " . curl_error($ch));
$decoded_response = json_decode($result, true);
if (!$decoded_response) {
error_log($result);
return strip_tags($result);
}
curl_close($ch);
return $decoded_response;
}
/**
* 谷歌登录
*
* @return void
* @author wj
* @date 2022-07-01
*/
public function goolelogin(Request $request)
{
$data = $request->post();
$code = $data['code'];
$CLIENT_ID = '**************apps.googleusercontent.com';
$ClIENT_SECRET = "GOCSPX-**************_pgEMjTl";
$url = "https://oauth2.googleapis.com/token";
$grant_type = "authorization_code";
$redirect_uri = "https://yoozi.txunda.com";
$postdata = [
'client_id' => $CLIENT_ID,
'client_secret' => $ClIENT_SECRET,
'code' => $code,
'grant_type' => $grant_type,
'redirect_uri' => $redirect_uri,
];
$result = $this->executeCall($url, $postdata);
var_dump($result);
}
运行结果
404 page not found
我想要达到的结果
$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();
原文链接:https://blog.csdn.net/TianYaLangZi_123/article/details/115402171