php微站微信公众号授权登录

有没有人在啊,想请讲解下,php微站微信公众号授权登录
最新回答
言清欢

2024-09-28 15:21:14

php微站微信公众号授权登录,即在微信客户端的浏览器里面授权登录
1.getBaseInfo.php文件获取code ?php //1.获取到code $appid = "***************"; $redirect_uri = urlencode("http://**********.com/weixin_wap_shouquan/getWxCode.php"); $url = "
https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."redirect_uri=".$redirect_uri."response_type=codescope=snsapi_userinfostate=0#wechat_redirect";
header("Location:".$url); ?
2.getWxCode.php文件获取微信用户信息并存入数据库 ?php require_once './httpCurl.php'; require_once './MySQLiDb.class.php'; //2.获取到网页授权的access_token $appid = "******************"; $app_secret = "************************"; $code = isset($_GET["code"])? trim($_GET["code"]) : ""; $url = "
https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."secret=".$app_secret."code=".$code."grant_type=authorization_code";
/*$res = object(stdClass)#1 (6) { ["access_token"]= string(107) "***************************" ["expires_in"]= int(7200) ["refresh_token"]= string(107) "****************************" ["openid"]= string(28) "***********************" ["scope"]= string(12) "snsapi_login" ["unionid"]= string(28) "**************************" }*/ //3.拉取用户的openid $res = json_decode(httpCurl($url)); $access_token = $res-access_token; $openid = $res-openid; //4获取用户信息 $userUrl = "
https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."openid=".$openid;
/*$userInfo = object(stdClass)#2 (10) { ["openid"]= string(28) "***********************" ["nickname"]= string(6) "***" ["sex"]= int(1) ["language"]= string(5) "zh_CN" ["city"]= string(7) "Baoding" ["province"]= string(5) "Hebei" ["country"]= string(2) "CN" ["headimgurl"]= string(140) "*******************************" ["privilege"]= array(0) { } ["unionid"]= string(28) "*************************" }*/ $userInfo = json_decode(httpCurl($userUrl)); //获取微信unionid $wx_unionid = $userInfo-unionid; $info = $db-getRow("SELECT * FROM user WHERE wx_unionid='$wx_unionid' LIMIT 1"); if (!!$info){ //跳转到登录页面 header("Location:/m/login_ajax.php?t=0wx_unionid=".$wx_unionid); }else{ //将微信用户信息存入数据库 $user_sn = randomString().$db-autoId("user"); $res = $db-query("INSERT INTO user (user_sn,auth_type,wx_unionid,wx_nickname,wx_avatar,wx_sex,add_time,wx_open_id) VALUES('$user_sn','0','$wx_unionid','$userInfo-nickname','$userInfo-headimgurl','$wx_sex',now(),'$openid')"); if (!!$res){ header("Location:/m/login_ajax.php?t=0wx_unionid=".$wx_unionid); }else{ header("Location:/m/login.php"); } } /* * 获取随机串 * */ function randomString($type=1,$length=4){ if ($type == 1){ $chars = join("",range(0,9)); }elseif ($type == 2){ $chars = join("",array_merge(range("a","z"),range("A","Z"))); }elseif ($type == 3){ $chars = join("",array_merge(range("a","z"),range("A","Z"),range(0,9))); } if ($length strlen($chars)){ exit("字符串长度不够"); } $chars = str_shuffle($chars); return substr($chars,0,$length); } ?
3.httpCurl.php文件 ?php function httpCurl($url, $method="", $postfields = null, $headers = array(), $debug = false) { $ci = curl_init(); /* Curl settings */ curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ci, CURLOPT_TIMEOUT, 30); curl_setopt($ci, CURLOPT_RETURNTRANSFER, true); switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, true); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); } break; } if ( strlen( $url ) 5 strtolower( substr( $url , 0 , 5 ) ) == 'https' ){ curl_setopt( $ci , CURLOPT_SSL_VERIFYPEER , FALSE ); curl_setopt( $ci , CURLOPT_SSL_VERIFYHOST , FALSE ); } curl_setopt($ci, CURLOPT_URL, $url); curl_setopt($ci, CURLOPT_HTTPHEADER, $headers); curl_setopt($ci, CURLINFO_HEADER_OUT, true); $response = curl_exec($ci); //  $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $http_code = curl_getinfo($ci); if ($debug) { echo "=====post data======\r\n"; var_dump($postfields); echo '=====info=====' . "\r\n"; print_r(curl_getinfo($ci)); echo '=====$response=====' . "\r\n"; print_r($response); } curl_close($ci); return $response; } ?
4.MySQLiDb.class.php文件 ?php //连接数据库 class MySQLiDb{ private $dbhost; // 数据库主机 private $dbuser; // 数据库用户名 private $dbpass; // 数据库用户名密码 private $dbname; // 数据库名 private $link; //数据库链接本身 private $charset; // 数据库编码,GBK,UTF8,gb2312 private $sql;//最后一次执行的sql语句 //初始化类 public function __construct($dbhost, $dbuser, $dbpass, $dbname = '', $charset = 'utf8'){ $this-dbhost = $dbhost; $this-dbuser = $dbuser; $this-dbpass = $dbpass; $this-dbname = $dbname; $this-charset = strtolower(str_replace('-', '', $charset)); $this-link = new mysqli($this-dbhost,$this-dbuser,$this-dbpass,$this-dbname); if($this-error()){ $errorInfo='Error:Could not make a database link ('.$this-errno().')'.$this-error(); throw new ErrorException($errorInfo, 1); } $this-setCharset($this-charset); } /** * @param 设置字符集 */ private function setCharset($charset){ $this-link-set_charset($charset); } /** * 数据库执行语句,可执行查询添加修改删除等任何sql语句 * @access public * @param $sql string 查询sql语句 * @return $result,成功返回资源,失败则输出错误信息,并退出 */ public function query($sql){ $this-sql = $sql; $result = $this-link-query($this-sql); if (!$result) { return false; // die($this-errno().':'.$this-error().'br /出错语句为'.$this-sql.'br /'); } return $result; } /** * 拼装查询的sql语句 * @param $tablename 数据表名称 * @param $opts 查询的元素 * @param $where 条件 数组或字符串 * @param $order 排序条件 * @return 返回sql语句 */ public function selectSql($tablename,$opts=array(),$where=" 1=1 ",$order=" id DESC "){ if (empty($opts)){ $fields = "*"; }else{ $opts = $this-cleanseArray($opts); $keys = array_keys($opts); $vals = array_values($opts); $fields = ""; for ($i = 0; $i count($keys); $i++) { if ($fields == ""){ $fields = $vals[$i]; } else { $fields = $fields.",".$vals[$i].""; } } } if (is_array($where)){ $whereArr = $this-cleanseArray($where); $keysWhere = array_keys($whereArr); $valsWhere = array_values($whereArr); $whereString = ""; for ($j = 0; $j count($keysWhere); $j++) { if ($whereString == ""){ $whereString = $keysWhere[$j]." = '".$valsWhere[$j]."'"; } else { $whereString = $whereString." AND ".$keysWhere[$j]." = '".$valsWhere[$j]."'"; } } }else{ $whereString = $where; } $sql = "SELECT ".$fields." FROM ".$tablename." WHERE ".$whereString." ORDER BY ".$order; return $sql; } /** * 更新的通用语句 * @param $tablename 数据表名称 * @param $opts 更新的元素 * @param $where 条件 数组或字符串 * @return 影响的行数 */ public function genericUpdate($tablename, $opts, $where) { $opts = $this-cleanseArray($opts); $keys = array_keys($opts); $vals = array_values($opts); $setString = ""; $whereString = ""; for ($i = 0; $i count($keys); $i++) { if ($setString == ""){ $setString = $keys[$i]." = '".$vals[$i]."'"; } else { $setString = $setString.", ".$keys[$i]." = '".$vals[$i]."'"; } } if (is_array($where)){ $whereArr = $this-cleanseArray($where); $keysWhere = array_keys($whereArr); $valsWhere = array_values($whereArr); for ($j = 0; $j count($keysWhere); $j++) { if ($whereString == ""){ $whereString = $keysWhere[$j]." = '".$valsWhere[$j]."'"; } else { $whereString = $whereString." AND ".$keysWhere[$j]." = '".$valsWhere[$j]."'"; } } }else{ $whereString = $where; } $sql = "UPDATE `$tablename` SET ".$setString." WHERE ".$whereString; $result = $this-query($sql); if (!!$result){ return $this-affectedRows(); }else{ return false; } } /** * 删除的通用语句 * @param $tablename 数据表名称 * @param $where 条件 数组或字符串 * @return 影响的行数 */ function genericDelete($tablename, $where="1") { $whereString = ""; if (is_array($where)){ $whereArr = $this-cleanseArray($where); $keysWhere = array_keys($whereArr); $valsWhere = array_values($whereArr); for ($j = 0; $j count($keysWhere); $j++) { if ($whereString == ""){ $whereString = $keysWhere[$j]." = '".$valsWhere[$j]."'"; } else { $whereString = $whereString." AND ".$keysWhere[$j]." = '".$valsWhere[$j]."'"; } } }else{ $whereString = $where; } $sql = "DELETE FROM ". $tablename . " WHERE " . $whereString; $result = $this-query($sql); if (!!$result){ return $this-affectedRows(); }else{ return false; } } /** * 过滤字符串 * @param 字符串 * @param string $char * @return $cleansed */ private function cleansePureString($str, $char = '\\') { ///[^a-zA-Z0-9\s]/ NON ALPHA $cleansed = preg_replace("/[%_'\"]/", '', $str); //_, % and ' return $cleansed; } /** * 过滤数组 * @param unknown $opts * @return multitype:$cleansed */ private function cleanseArray($opts) { $cleansedArray = array(); $keys = array_keys($opts); $vals = array_values($opts); for ($i = 0; $i count($keys); $i++) { $newKey = $this-cleansePureString($keys[$i],"'"); $newVal = $this-cleansePureString($vals[$i],"'"); $cleansedArray[$newKey] = $newVal; } return $cleansedArray; } /** * return 返回一个字符串指出了客户端库的版本 */ public function clientInfo(){ return $this-link-client_info; } /** * return 作为一个整数返回MySQL服务器的版本 */ public function clientVersion(){ return $this-link-client_version; } /** * 获取结果集中行的数目 * @access private * @return 结果集中行的数目 */ function numRows($sql) { $result = $this-query($sql); if (!!$result){ $nums = $result-num_rows; return $nums; }else{ return false; } } /** * 获取第一条记录的第一个字段 * @access public * @param $sql string 查询的sql语句 * @return 返回一个该字段的值 */ public function getOne($sql){ $result = $this-query($sql); if (!!$result) { $row = $result-fetch_row(); return $row[0]; } else { return false; } } /** * 获取一条记录 * @access public * @param $sql 查询的sql语句 * @return array 关联数组 */ public function getRow($sql){ $result = $this-query($sql); if ($result) { $row = $result-fetch_assoc(); return $row; } else { return false; } } /** * 获取所有的记录 * @access public * @param $sql 执行的sql语句 * @return $list 返回所有记录组成的二维数组 */ public function getAll($sql){ $result = $this-query($sql); $list = array(); if (!!$result){ while (!!($row = $result-fetch_assoc())){ $list[] = $row; } return $list; }else{ return false; } } /** * 获取某一列的值 * @access public * @param $sql string 执行的sql语句 * @return $list array 返回由该列的值构成的一维数组 */ public function getCol($sql){ $result = $this-query($sql); $list = array(); if (!!$result){ while (!!($row = $result-fetch_row())) { $list[] = $row[0]; } return $list; }else{ return false; } } /** * 获取上一步insert操作产生的id */ public function getInsertId(){ return $this-link-insert_id; } /** * 获取下一个自增(id)值 * @param $tablename 数据表名 */ public function autoId($tablename) { return $this-getOne("SELECT auto_increment FROM information_schema.`TABLES` WHERE TABLE_SCHEMA='" . $this-dbname . "' AND TABLE_NAME = '" . trim($tablename, '`') . "'"); } /** * 获取影响的记录行数 * @access private * @return 前一次 MySQL 操作所影响的记录行数 */ public function affectedRows() { return $this-link-affected_rows; } /** * 返回结果集中字段的数 * @access public * @param $sql string 执行的sql语句 * @return 结果集中字段的数 */ public function numFields($sql) { $result = $this-query($sql); return $result-field_count; } /** * 释放结果内存 * @access public * @param $result 要释放的结果标识符 * @return 释放结果内存 */ public function freeResult($result) { return $result-free(); } /** * 关闭先前打开的数据库连接 */ public function close(){ $this-link-close(); } /** * 获取错误号 * @access private * @return 错误号 */ private function errno(){ return $this-link-connect_errno; } /** * 获取错误信息 * @access private * @return 错误private信息 */ private function error(){ return $this-link-connect_error; } //开启事务 public function startTransaction(){ $this-link-autocommit(FALSE); } //提交事务 public function commit(){ $this-link-commit(); $this-link-autocommit(TRUE); } //回滚事务 public function rollback(){ $this-link-rollback(); } } header("Content-type:text/html; charset=UTF-8"); // database host $dbhost  = "localhost"; // database name $dbname  = "***"; // database username $dbuser  = "***"; // database password $dbpass  = "****"; // 字符集 $charset = 'utf8'; $db = new MySQLiDb($dbhost, $dbuser, $dbpass, $dbname, $charset); ?
5.目录结构