<?php
namespace Home\Controller;
use Think\Controller;
/**
*
*/
class WeixinController extends Controller
{
var $tokenFile;
const appid = 'appid';
const secret = 'secret';
public function __construct()
{
parent::__construct();
$session_openid = session('openid');
define('BASE_PATH',str_replace('\\','/',realpath(dirname(__FILE__).'/../../../'))."/");
$this->tokenFile = BASE_PATH . 'token.txt';
// echo $this->tokenFilee;
// exit;
if (empty($session_openid)) {
$shouji = $_GET['shouji'];
//unset($_SESSION['think']['openid']);
$appid = self::appid;
$secret = self::secret;
$code = isset($_GET['code']) ? $_GET['code'] : "";
if (!$code) {
$REDIRECT_URI = 'http://' . $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
//dump($REDIRECT_URI);die;
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri=" . $REDIRECT_URI . "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
echo "<meta http-equiv=\"refresh\" content=\"1;URL=" . $url . "\" />";
header('Location:' . $url);
exit ();
}
$res = $this->getmemberOpenId($code); //获取openid
$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $res['access_token'] . "&openid=" . $res['openid'] . "&lang=zh_CN";
$r = $this->getJson($get_user_info_url);
$openid = $r['openid'];
$nickname = $r['nickname'];
$user = M("admin_user")->where("openid = '$openid'")->find();
$shangji_arr = $this->get_shangjiuser($user['jiagou_id']);
$user['jiagou_name'] = $this->get_jiagouname($user['jiagou_id']);
$user['shangji_id'] = $shangji_arr['id'];
$user['shangji_name'] = $shangji_arr['name'];
$user['hangye_name'] = $this->get_hangyename($user['hangye_id']);
// echo "<pre>";
// print_r($user);
// exit;
//如果已经将用户的微信存入数据库,则直接写入session
if ($user) {
session('user', $user);
session('openid', $openid);
session('nickname', $nickname);
} else {
//第一次使用微信登录记录用户的微信信息
$data['wx_name'] = $nickname;
//$img = file_get_contents($r['headimgurl']);
//$time = time();
//file_put_contents(ROOT_PATH.'/public/static/upload/touxiang/'.$time.'.jpg', $img);
$data['headimg'] = $r['headimgurl'];
//$data['sex'] = $r['sex'];
$data['openid'] = $r['openid'];
$res = M('admin_user')->where(array('shouji' => $shouji))->save($data);
if ($res) {
$user = M('admin_user')->where("openid = '$openid'")->find();
$shangji_arr = $this->get_shangjiuser($user['jiagou_id']);
$user['jiagou_name'] = $this->get_jiagouname($user['jiagou_id']);
$user['shangji_id'] = $shangji_arr['id'];
$user['shangji_name'] = $shangji_arr['name'];
$user['hangye_name'] = $this->get_hangyename($user['hangye_id']);
if ($user) {
session('user', $user);
session('openid', $openid);
}
}
}
}
}
/*获取架构名称*/
public function get_jiagouname($jiagou_id)
{
$arr = M("jiagou")->where("id = {$jiagou_id}")->find();
if($arr)
{
return $arr['name'];
}
else
{
return '暂无';
}
}
/*获取行业名称*/
public function get_hangyename($hangye_id)
{
$arr = M("hangye")->where("id = {$hangye_id}")->find();
if($arr)
{
return $arr['name'];
}
else
{
return '暂无';
}
}
/*获取上级*/
public function get_shangjiuser($jiagou_id)
{
$arr = M("admin_user")->where("jiagou_id = {$jiagou_id} and is_duizhang = 1")->find();
if($arr)
{
return $arr;
}
else
{
return array('id' => '','name' => '暂无');
}
}
public function getAccessToken(){
if(! is_file($this->tokenFile)){
return $this->getToken();
}
$now_time = time();
$last_time = filemtime($this->tokenFile);
if(($now_time - $last_time) > 5000)
{
return $this->getToken();
}
// echo date("Y-m-d H:i:s") . '/' . date("Y-m-d H:i:s",$last_time) . '<br>';
// echo ($now_time - $last_time) . '<br>';
$_SESSION['access_token'] = file_get_contents($this->tokenFile);
return $_SESSION['access_token'];
}
public function send_wxmsg($openid,$w_title,$w_url,$w_description,$picurl='' )
{
$accessToken = $this->getAccessToken();
$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$accessToken;
// $cfg_baseurl = $GLOBALS['db']->getOne("SELECT cfg_value FROM ".$GLOBALS['hhs']->table("weixin_cfg")." WHERE cfg_name = 'baseurl'");
// preg_match("/^(http:\/\/)?([^\/]+)/i", $cfg_baseurl , $matches);
// $cfg_baseurl=$matches[0]."/";
// $w_url = strstr($w_url,'mp.weixin.qq.com') ? $w_url: ($w_url?$cfg_baseurl.$w_url:'');
// $picurl = strstr($picurl,'qpic.cn') ? $picurl: ($picurl ? $cfg_baseurl.$picurl: '');
$picurl = 'http://duijie.shenganwenhua.com/Public/img/haliluya.jpg';
$post_msg = '{
"touser":"'.$openid.'",
"msgtype":"news",
"news":{
"articles": [
{
"title":"'.$w_title.'",
"description":"'.$w_description.'",
"url":"'.$w_url.'",
"picurl":"'.$picurl.'"
}
]
}
}';
$ret_json = $this->httpPost($url, $post_msg);
$ret = json_decode($ret_json);
if(isset($ret->errcode) && $ret->errcode > 0 && $ret->errcode != 45015 ){
@unlink($this->tokenFile);
}
// print_r($ret). '<br>';
return $ret->errmsg ;
}
private function getToken()
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::appid."&secret=".self::secret;
$tmpInfo=$this->httpGet($url);
$info=json_decode($tmpInfo,true);
file_put_contents($this->tokenFile, $info['access_token']);
//setcookie("access_token",$info['access_token'],time()+7000,'/');
$_SESSION['access_token']=$info['access_token'];
$_SESSION['access_token_time']=time();
@unlink($this->ticketFile);
return $info['access_token'];
}
/**
* getmemberOpenId获取用户openid
*
* @param unknown $code
* @return unknown
*/
public function getmemberOpenId($code)
{
$appid = self::appid;
$secret = self::secret;
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = $this->getJson($oauth2Url);
return $oauth2;
}
/**
* getJson($url)得到返回值
*
* @param unknown $url
* @return mixed
*/
public function getJson($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
public function httpPost($url, $data = null)
{
$ch = curl_init();
//curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$temp=curl_exec ($ch);
curl_close ($ch);
return $temp;
}
public function httpGet($url, $data = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);
if(curl_errno($ch))
{
return curl_error($ch);
}
curl_close($ch);
return $tmpInfo;
}
}
?>
微信公众号开发获取openid和用户基本信息还有发消息的TP3.23方法类
猜你喜欢
转载自blog.csdn.net/weixin_40896800/article/details/83014302
今日推荐
周排行