微信登录
微信登录相比qq登录要简单,直接上代码。
同样需要申请appid与secret
WechatAction
<?phpclass WechatAction extends AppbaseAction {
//申请的appid secret
private $appid = "";
private $secret = "";
private $scope = "snsapi_userinfo";/继承父类/
protected function _initialize() {
parent::_initialize();
}public function index(){
echo 111;
//echo $this->appid;
}//微信登录,同意授权,获取code
public function oauthLogin(){
$appid = $this->appid;
$scope = $this->scope;
$redirect_uri = urlencode('http://www.13sai.com'.U('Wap/Wechat/oauthCallback'));
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=1#wechat_redirect";
//echo $url;die();
header("Location:".$url);
}//OAthu2.0 回调函数
public function oauthCallback(){
$appid = $this->appid;
$secret = $this->secret;
$code = $_GET["code"];
//echo $code.'<br>';
//第一步:取全局access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$token = z_get_json($url);
//dump($token).'<br>';//第二步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = z_get_json($oauth2Url);
//dump($oauth2).'<br>';
//第三步:根据全局access_token和openid查询用户信息
$access_token = $token["access_token"];
$openid = $oauth2['openid'];
$get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
//echo $get_user_info_url;
$userinfo = z_get_json($get_user_info_url);
//dump($userinfo);
//die();//if($userinfo['openid']!=''){
// echo '<br><br>'.$userinfo['openid'];
//}
//dump($userinfo);
//die();
//判断注册还是登录
if($userinfo['openid']!=''){$row = M("member")->where("m_weixin_openid='%s'",$userinfo["openid"])->find();
if($row){
session('m_id',$row['m_id']);
session('m_nick_name',$row['m_nick_name']);
session('m_login_name',$row['m_login_name']);
session('is_org',-1);
//U('Home/Home/index',null,true,true);
echo '<script>window.location.href="http://www.13sai.com'.U('Wap/Home/index').'";</script>';
}else{
// 创建新用户
$count = M("member")->max('m_id');
$count++;
$rand = mt_rand(1000,9999);
//$data['gender'] = $gender;
$data['m_avatar'] = $userinfo['headimgurl'];
$data['m_nick_name'] = mb_substr($userinfo['nickname'],0,6,"utf-8") . $count;
$data['m_login_name'] = 'wx_'.$rand.''.$count;
$data['m_password'] = md5(md5(time()));
$data['m_weixin_openid'] = $userinfo["openid"];
$data['m_jingyan'] = 50;session('kj_object',$data);
echo '<script>window.location.href="http://www.13sai.com'.U('Wap/Guide/binding').'";</script>';
}
}else{
U('Wap/Index/login','','',true);
}
}
}
前台模板类似qq 微博一键登录,就不赘述了。
注意:这是微信里的一键登录,需要申请服务号,才能获取授权。