PHP微信公众号授权登录
微信公众号授权登录非常简单只需要几步就可以搞定
第一步:拼接参数获取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'])) {
$app_id = config('app.wechat.AppId');
$app_secret = config('app.wechat.AppSecret');
$code = $_GET['code'];
$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);
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 = $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请求方法
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;
}
|