直接上代码:
public function weixinLogin(){
$item = db('setting')->where('id',1)->find();
$item = json_decode($item['weixin'],true);
$app_id = $item['app_id'];//应用的APPID
$rsaPrivateKey = $item['private_key'];//APPSECRET
//Step2: 使用auth_code换取apauth_token
if(isset($_REQUEST["state"])){
$auth_code = $_REQUEST["code"];//存放auth_code
$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$rsaPrivateKey}&code={$auth_code}&grant_type=authorization_code";
$token = json_decode(file_get_contents($token_url));
if(isset($token->errcode)) {
header('Location: /home/auth/login.html');
exit();
}
$access_token_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$app_id}&grant_type=refresh_token&refresh_token=".$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if(isset($access_token->errcode)) {
header('Location: /home/auth/login.html');
exit();
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_data = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
header('Location: /home/auth/login.html');
exit();
}
$user_data = json_decode(json_encode($user_data),true);
//某个参数可能不存在,需要进行判断,防止报错
$member = array(
"nickname"=>isset($user_data['nickname'])?$user_data['nickname']:"",
"openid"=>isset($user_data['openid'])?$user_data['openid']:"",
"gender"=>isset($user_data['sex'])&&$user_data["sex"]=="1"?0:1,
"avatar"=>isset($user_data['headimgurl'])?$user_data['headimgurl']:"",
"address"=>(isset($user_data['province'])?$user_data["province"]:"").(isset($user_data['city'])?$user_data["city"]:"").(isset($user_data['country'])?$user_data["country"]:"")
);
$m = Member::getUserInfoByAliID($member["openid"]);
if(empty($m)){
$member['ip']=getIp();
$member['salt'] = random(8);
$member['invitation_code'] = random(6);
$member['create_time'] = TIMESTAMP;
$member['pet_jihua'] = date('Ymd');
$uid = Member::addInfo($member);
$m = Member::getUserInfoById($uid);
}
Cookie::set('member',base64_encode($m));
header('Location: /home/account.html');
}else{
$my_url = $this->get_http_type().$_SERVER['HTTP_HOST']."/home/auth/weixinLogin.html";
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$app_id}&redirect_uri={$my_url}&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect";
return $url;
}
}