1,公众平台配置回调域名,则通过微信访问域名会先跳转到微信 oauth2 接口,访问成功微信会返回一个用户code给回调地址
请求地址:$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
2,根据返回的code获取access_token和用户唯一标识openid
请求地址:$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
3,通过获取到的access_token 和 openid 即可获取到用户信息
请求地址:$urltoc = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$getopenid."&lang=zh_CN";
find();
$appid = $dbres['appid'];
$redirect_uri = urlencode($dbres['back_url']);
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
header("Location:".$url);exit;
}
public function http_curl($url,$type='get',$res='json',$arr=''){
//1.初始化curl
$ch = curl_init();
//2.设置curl的参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($type == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
}
//3.采集
$output = curl_exec($ch);
//4.关闭
curl_close($ch);
if ($res == 'json') {
return json_decode($output,true);
}
}
public function getUserOpentId(){
//回调地址会传回一个code,则我们根据code去获取openid和授权获取到的access_token
$code = $_GET['code'];
$dbres = Db::name("setup")->find();
$appid = $dbres['appid'];
$secret = $dbres['appsecret'];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$res = $this->http_curl($url);
$access_token = $res['access_token'];
$getopenid = $res['openid'];
//获取用户授权信息
$urltoc = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$getopenid."&lang=zh_CN";
$resinfos = $this->http_curl($urltoc);
$openid = $resinfos['openid'];
$check_member = Db::name("member")->where('openid',$openid)->find();
if(empty($check_member)){
//首次进入,则获取用户信息,插入数据库
$resinfo['openid'] = $openid;
$insert_data = [
'openid' => $openid,
'create_time' => time()
];
Db::name("member")->insert($insert_data);
$userId = Db::name('member')->getLastInsID();
Session::set('wx_member_info', $resinfo);
$this->redirect('home/index/index_html');
}else{
//说明是已经是公众号成员,则调用用户信息存到session即可
$wx_member_info = Db::name('member')->where("openid",$openid)->find();
Session::set('wx_member_info', $wx_member_info);
$this->redirect('home/index/index_html');
}
}
public function index_html(){
if(!Session::has("wx_member_info")){
action("home/index/index");
}else{
return $this->fetch('index');
}
}
}
原创©本文章为教腾豪原创,未经许可,禁止转载
0条评论