namespace Home\Controller;
use Think\Controller;
class WxLoginController extends Controller {
const AppID = 'wx897er6594e4f3d';
const AppSecret = '22a872e9w0f0fbw932ff4fa7a33';
const callback = 'http://xxxxxxxxxx/index.php?s=/Home/WxLogin/callbackUrl.html';
public function doLogin()
{
session_start();
$state = md5(uniqid(rand(), TRUE));
$_SESSION["wx_state"] = $state;
$callback = urlencode(self::callback);
$wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid=".self::AppID."&redirect_uri={$callback}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
echo $wxurl;die;
}
public function callbackUrl()
{
if($_GET['state']!=$_SESSION["wx_state"])
{
exit("5001");
}
$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::AppID.'&secret='.self::AppSecret.'&code='.$_GET['code'].'&grant_type=authorization_code';
$arr = $this->curlRequest($url);
$userUrl='https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&lang=zh_CN';
$userInfo = $this->curlRequest($userUrl);
$this->VerifyUser($userInfo);
}
public function curlRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$json = curl_exec($ch);
curl_close($ch);
$arr=json_decode($json,true);
return $arr;
}
public function VerifyUser($WxUserInfo)
{
$where = array('status'=>1,'wx_openid'=>$WxUserInfo['openid']);
$userInfo = td_iconv(M('user')->where($where)->find());
if (!empty($userInfo)) {
session('userid',$userInfo['id']);
session('groupid',$userInfo['groupid']);
session('uname',$userInfo['wx_nickname']);
$data['ip'] = get_client_ip();
$data['lasttime']=time();
if(M("user")->where(array('id'=>$userInfo['id']))->save($data)){
M("user")->where(array('id'=>$userInfo['id']))->setInc("loginnum");
}
$this->success("登录成功...",U("Index/index"));
}else{
$data = array(
'groupid'=>15,
'status'=>0,
'ip'=>get_client_ip(),
'dateline'=>$_SERVER['REQUEST_TIME'],
'loginnum'=>0,
'wx_openid'=>$WxUserInfo['openid'],
'wx_nickname'=>iconv('UTF-8','gbk',$WxUserInfo['nickname'])
);
$res = M("user")->data($data)->add();
if (!empty($res)) {
echo "";
}
}
}
}
<li>
<img src="__PUBLIC__/images/login/wx.png" alt="微信登录" style="width: 70px;height: 50px;cursor:pointer;" onclick="wxLogin()">
li>
<script type="text/javascript">
function wxLogin()
{
$.get("{:U('WxLogin/doLogin')}",function(msg){
if(msg!=''){
window.location.href=msg;
}
});
}