自定义菜单
参考资料
- 微信公众平台
- 微信公众号开发文档
网页授权
下面代码用THINK_PHP 5.0编写
- 网页点击 微信登录请求该接口,返回相应参数
$appId = '';
$successUrl = urlencode($this->request->post('successUrl'));
$redirectUrl = 'http://xxxxxx/index/wx/wxInfo.html?successUrl='.$successUrl;
$scope = 'snsapi_userinfo';
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId
.'&redirect_uri='.urlencode($redirectUrl)
.'&response_type=code'
.'&scope='.$scope
.'&state=xx'
.'#wechat_redirect';
return $this->jsonSuccess('微信登录', ['url'=>$url]);
- 用户同意 http://xxxxxx/index/wx/wxInfo.html 获取用户信息
$code = $this->request->get('code');
$successUrl = $this->request->get('successUrl');
if(Session::get('USER_ID')>0){
$response = new Redirect(urldecode($successUrl));
throw new HttpResponseException($response);
}
$appId = '';
$appSecret = '';
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId
."&secret=".$appSecret
."&code=".$code
."&grant_type=authorization_code";
try {
$resStr = file_get_contents($url);
$res = json_decode($resStr , true);
}catch(\Exception $e){
return $this->fail('登陆失败');
}
if(!isset($res['access_token'])){
return $this->fail('登陆失败');
}
$accessToken = $res['access_token'];
$openId = $res['openid'];
$url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$accessToken."&openid=".$openId."&lang=zh_CN";
try {
$result2 = file_get_contents($url2);
$wxUserInfo = json_decode($result2, true);
}catch(\Exception $e){
return $this->fail('登陆失败');
}
if(!isset($wxUserInfo['nickname'])){
return $this->fail('登陆失败');
}
$data = [
'nick_name' => $wxUserInfo['nickname'],
'sex' => $wxUserInfo['sex'],
'poster' => $wxUserInfo['headimgurl'],
'open_id'=>$wxUserInfo['openid'],
'unionid'=>isset($wxUserInfo['unionid']) ? $wxUserInfo['unionid'] : '',
'language'=>$wxUserInfo['language'],
'city'=>$wxUserInfo['city'],
'country'=>$wxUserInfo['country'],
'province'=>$wxUserInfo['province'],
];
$userId = '';
Session::set('USER_ID', $userId);
return $this->success('登录成功', $successUrl);