2023最新使用百度账号php授权登录第三方网站

示例地址:https://www.goodtools.xyz/login/login_index.php

使用chatgpt推荐的file_get_contents()函数始终报错,因此多次调试后换用curl成功,源代码如下,网上各种各样的百度php登录代码都试了一遍,都不行,分享出来给需要的人

if (isset($_GET['code'])) {// 获取code$code = $_GET['code'];echo 'code为' . $code;$client_id = '你的id';$client_secret = '你的secret';$redirect_uri = '百度工程里的回调地址';$url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=$code&client_id=$client_id&client_secret=$client_secret&redirect_uri=$redirect_uri";// echo "<br/>"; //调试用// echo $url; //调试用//使用curl获取百度返回的json;$ch = curl_init($url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);$response = curl_exec($ch);if ($response === false) {$error = error_get_last();echo "<br/>" . "错误说明:";var_dump($error); // 输出错误消息的详细信息$error = curl_error($ch);echo "cURL Error: " . $error;} else {$data = json_decode($response, true);// echo "<br/>"; //调试用// echo 'response=' . $response;//调试用// echo "<br/>";//调试用// echo 'data=';//调试用// print_r($data); // 调试用,输出数组// 使用访问令牌获取用户信息$access_token = $data['access_token'];echo 'access_token'.$access_token;// 调试用,输出数组$urlt = "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?access_token=$access_token";$cht = curl_init($urlt);curl_setopt($cht, CURLOPT_RETURNTRANSFER, true);curl_setopt($cht, CURLOPT_SSL_VERIFYHOST, false);curl_setopt($cht, CURLOPT_SSL_VERIFYPEER, false);$responset = curl_exec($cht);if ($responset === false) {$error = error_get_last();echo "<br/>" . "错误说明:";var_dump($error); // 输出错误消息的详细信息}$user_info = json_decode($responset, true);// 获取用户信息$uname = $user_info['uname'];$portrait = $user_info['portrait'];// 显示用户信息echo '<h1>欢迎您,' . $uname . '</h1>';
}

本文链接:https://my.lmcjl.com/post/4563.html

展开阅读全文

4 评论

留下您的评论.