企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
``` <?php /** * 微信公众号网页授权 * * Class GetWxUser */ class GetWxUser { private $appId = ''; private $appSecret = ''; /** * 1、获取微信用户信息,判断有没有code,有使用code换取access_token,没有去获取code。 * * @return array 微信用户信息数组 */ public function getUserInfos() { if (!isset($_GET['code'])) {//没有code,去微信接口获取code码 $callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //微信服务器回调url,这里是本页url $this->getCode($callback); } else { $code = $_GET['code']; $data = $this->getAccessToken($code); //获取网页授权access_token和用户openid // 增加access_token缓存 $accessToken = $data['access_token'] ?? ''; $openid = $data['openid'] ?? ''; return $this->getUserInfo($accessToken, $openid); //获取微信用户信息 } } /** * 2、用户授权并获取code * * @param string $callback 微信服务器回调链接url */ private function getCode($callback) { $appId = $this->appId; $scope = 'snsapi_userinfo'; $state = md5(uniqid(rand(), true)); //唯一ID标识符绝对不会重复 $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appId . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect'; header("Location:$url"); } /** * 3、使用code换取access_token * * @param string $code 用于换取access_token的code,微信提供 * * @return array [ * 'openid'=>1111, * 'access_token'=>3333 * ] */ private function getAccessToken($code) { // 缓存 $fileName = 'access_token.txt'; if (file_exists($fileName)) { if ($fileToken = file_get_contents($fileName)) { $data = json_decode($fileToken, 1); if (isset($data['access_token']) && !empty($data['access_token']) && isset($data['expire_time']) && !empty($data['expire_time']) ) { if ($data['expire_time'] > time()) { $accessToken = $data['access_token']; $openid = $data['openid']; return [ 'access_token' => $accessToken, 'openid' => $openid, ]; } } } } $appId = $this->appId; $appSecret = $this->appSecret; $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appId . '&secret=' . $appSecret . '&code=' . $code . '&grant_type=authorization_code'; $user = json_decode(file_get_contents($url)); if (isset($user->errcode)) { echo 'error:' . $user->errcode . '<hr>msg :' . $user->errmsg; exit; } $data = json_decode(json_encode($user), true); //记录缓存 file_put_contents('access_token.txt', json_encode(['access_token' => $data['access_token'], 'openid' => $data['openid'], 'expire_time' => 5000])); return $data; } /** * 4、使用access_token获取用户信息 * * @param string $accessToken access_token * @param string $openid 用户的openid * * @return array 用户信息数组 */ private function getUserInfo($accessToken, $openid) { $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessToken . '&openid=' . $openid . '&lang=zh_CN'; $user = json_decode(file_get_contents($url)); if (isset($user->errcode)) { echo 'error:' . $user->errcode . '<hr>msg :' . $user->errmsg; exit; } return json_decode(json_encode($user), true); //返回的json数组转换成array数组 } } $wx = new GetWxUser(); $res = $wx->getUserInfos(); var_dump($res); exit; ```