微信oauth2授权获得用户信息
时间:2015-05-07 13:54:10
收藏:0
阅读:240
<?php
session_start();
header("Content-type: text/html; charset=utf-8");
$home = ‘index.php‘;
class db{
private $host;
private $user;
private $pass;
private $database;
private $charset;
function __construct($host,$user,$pass,$database,$charset){
$this->host=$host;
$this->user=$user;
$this->pass=$pass;
$this->database=$database;
$this->charset=$charset;
$this->connect();
}
function connect(){
mysql_connect($this->host,$this->user,$this->pass) or die ("连接数据库服务器失败!");
mysql_select_db($this->database) or die ("连接数据库失败!");
mysql_query("set names $this->charset");
}
function select($sql){
$select=mysql_query($sql);
$rows = ‘‘;
while($row = mysql_fetch_array($select, MYSQL_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
function insert($tab,$col,$value){
mysql_query("INSERT INTO $tab($col)values($value)");
return mysql_insert_id();
}
function update($tab,$col,$new_value,$colm,$value){
mysql_query("UPDATE $tab SET $col=$new_value where $colm=$value");
}
function delete($tab,$col,$value){
mysql_query("DELETE FROM $tab where $col=$value");
}
function close(){
mysql_close();
}
}
$db = new db(‘127.0.0.1‘,‘root‘,‘lizhifeng‘,‘jinba‘,‘utf8‘);
//通过oauth2授权获取用户详细信息
//$url = ‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx954b290311defa52&redirect_uri=http://jinba2.emailcar.net&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect‘;
if(!$_SESSION[‘userid‘]){
if (isset($_GET[‘code‘])){
$code = $_GET[‘code‘];
$url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx954b290311defa52&secret=299a1a9ba0db6d1b09266842de62079c&code=‘.$code.‘&grant_type=authorization_code‘;
$json = file_get_contents($url);
$arr = json_decode($json,true);
$token = $arr[‘access_token‘];
$openid = $arr[‘openid‘];
$url = ‘https://api.weixin.qq.com/sns/userinfo?access_token=‘.$token.‘&openid=‘.$openid.‘&lang=zh_CN‘;
$json = file_get_contents($url);
$arr = json_decode($json,true);
$name = $arr[‘nickname‘];
$imgURL = $arr[‘headimgurl‘];
$sex = $arr[‘sex‘];
$province = $arr[‘province‘];
$city= $arr[‘city‘];
$country= $arr[‘country‘];
$result = $db->select(‘select * from member where openid = "‘.$openid.‘"‘);
if($result){
$userid = $result[0][‘id‘];
$_SESSION[‘userid‘] = $userid;
}else{
if($openid){
$userid = $db->insert(‘member‘,‘openid,nickname,headimgurl,sex,city,country,province,create_time‘,‘"‘.$openid.‘","‘.$name.‘","‘.$imgURL.‘","‘.$sex.‘","‘.$city.‘","‘.$country.‘","‘.$province.‘","‘.time().‘"‘);
$_SESSION[‘userid‘] = $userid;
}else{
header("Location: $url");
}
}
}else{
header("Location: $url");
}
}
$userid = $userid?$userid:$_SESSION[‘userid‘];
评论(0)