PHP微信公众号授权登录
微信公众号授权登录非常简单只需要几步就可以搞定
第一步:拼接参数获取code值,并指定后面的处理链接
/**
* 获取公众号code
*/
public function getCode(){
$appid = config('app.wechat.AppId');
$redirect_uri = urlencode('http://www.xxx.com/api/register/weChatRegister');//重定向地址
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6f8e4dba34f9d941&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:" . $url);
}
第二步:通过code获取用户openid和access_token,然后再根据openid和access_token获取用户信息
public function weChatRegister()
{
if (isset($_GET['code'])) {
// 获取openid和access_token
$app_id = config('app.wechat.AppId');
$app_secret = config('app.wechat.AppSecret');
$code = $_GET['code'];
// 发送请求,获取用户openid和access_token
$data = $this->curl('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $app_id . '&secret=' . $app_secret . '&code=' . $code . '&grant_type=authorization_code');
$data = json_decode($data);
// 防止第二次访问动态链接报错
// 判断是否获取到当前用户的openid
if (isset($data->openid)) {
$open_id = $data->openid;
$access_token = $data->access_token;
// 获取当前用户信息
$user_info = $this->curl('https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $open_id . '&lang=zh_CN');
$user_info = json_decode($user_info);
// 取出用户信息
/*
*user_openid :用户openId
*user_nickname :用户昵称
*user_sex :性别
*user_province :省
*user_city :城市
*user_headimgurl :用户头像url
*user_unionid :绑定开放平台后才有这个字段
*/
$user_openid = $user_info->openid;
$user_nickname = $user_info->nickname;
$user_headimgurl = $user_info->headimgurl;
$user_unionid = $user_info->unionid;
// 判断用户是否存在
$userInfo = Users::where(['unionid' => $user_unionid])->find();
if (empty($userInfo)) {
//用户不存在,创建用户
$insert['nickname'] = $user_nickname;
$insert['avatar'] = $user_headimgurl;
$insert['openid'] = $user_openid;
$insert['unionid'] = $user_unionid;
$insert['create_time'] = time();
$userId = Db::name('qt_users')->insertGetId($insert);
}else {
//用户已经存在进行登录操作或者进行用户下一步数据绑定和认证等
}
}else{
$this->result('无效的请求',$data,204);
}
}else{
$this->result('无效的请求','',204);
}
}
curl请求方法
// php CURL请求
public function curl($url, $post = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}