开发公众号,最常用到的就是获取用户信息,对于大神来说,这技术跟本就不是什么事儿,但对于小冰这样的小白来说,却是一件苦差事儿,就上次,因为这活儿,弄了我一个大晚上。
1、首先在公众号后台填 写授权域名
注:授权回调页面域名:填写域名(不带http和www)本址可以先使用本机ip地址
2、php代码块
(1、)先引导用户进入授权页面,使用appid获取code;
public function wxLogin(){
//appId
$appId = 'your appId';
// 回调的url
$redirect_uri = urlencode('http://127.0.0.1/test/public/index/user/getUserInfo');
//跳转微信回调到redirect_uri获取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";
$this->redirect($url);
}
//参数解释
appid:公从号中的appid
redirect_uri:授权后重定向的地址,即引导用户进入授权的那个页面,需要使用urlEncode函数进行处理
response_type:填写code即可
scope:有两个选择 snsapi_base(不弹出授权页面,直接跳转,只能拿到用户的opedid) snsapi_userinfo(弹出授权页面,可以拿到opendid 和用户头像等)
state:填写STATE(大写)
#wechat_redirect:没有参数 (注意前面有井号)
(2、)通过code 换取 access_token
public function getUserInfo(){
//获取code
$code = $_GET["code"];
// appId与appSecret
$appId = 'your appId';
$appSecret = 'your appSecret';
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
$res = $this->sendRequest($url);
$access_token = $res["access_token"];//拿到access_token
$openId = $res['openid']; //拿到用户的oppid
$getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
//得到用户信息
$user_info = $this->sendRequest($getUserInfo);
dump($user_info);
//接下来的逻辑...
}
//url参数解析
appid:公众号的appid
appSecret:公众号的appSecret
code:第一步中的get过来的code
grant_type:填写authorization_code即可
(3、)发送请求
public function sendRequest($url){
$ch = curl_init();
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);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}