微信公众号登录

      
public function getWechatOpenid()
{
$appid = trim($this->result["sites"]["appid"]);
$secret = trim($this->result["sites"]["appsecret"]);
$code = $_GET['code'];//获取code
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".urlencode("http://".$_SERVER["HTTP_HOST"]."/".$_SERVER["REQUEST_URI"])."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
if(!$code)header("Location: $url");
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
//根据openid和access_token查询用户信息
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
//解析json
$userinfo = json_decode($res,true);
if(!empty($openid))
{
$sql = "SELECT * FROM ".get_table("customers")." WHERE openid='$openid'";
$rs = $this->mDb->getRow($sql);
if($rs)
{
$_SESSION["login_user"] = $rs;
}
else
{
//注册微信临时用户

$sql = "INSERT INTO ".get_table("customers")." SET openid='$openid',
nickname='".$userinfo["nickname"]."',
city='".$userinfo["city"]."',
province='".$userinfo["province"]."',
headimgurl='".$userinfo["headimgurl"]."',
truename='微信注册用户',createdate=now(),client_id=".$this->result["sites"]["client_id"];
$this->mDb->execute($sql);
$id = $this->mDb->Insert_ID();
$sql = "SELECT * FROM ".get_table("customers")." WHERE id=$id";
$rs = $this->mDb->getRow($sql);
$_SESSION["login_user"] = $rs;
//die();
//print_r($userinfo);

}
$_SESSION["login_user"]["headimgurl"] = $userinfo["headimgurl"];
$_SESSION["login_user"]["nickname"] = $userinfo["nickname"];
$_SESSION["login_user"]["province"] = $userinfo["province"];
$_SESSION["login_user"]["city"] = $userinfo["city"];
$this->result["login_user"] = $_SESSION["login_user"];
$this->result["openid"] = $openid;
}
else
{
//header("Location: /login.html?baseurl=".urlencode($_SERVER["REQUEST_URI"]));exit();
}

//print_r($userinfo);

//die();
}
posted @ 2020-01-02 09:09  北满  阅读(326)  评论(0编辑  收藏  举报