<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST , ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace plugin\wechat\public_class;
use \temmoku\lib\user;
use \temmoku\db;
class wechat {
	function __construct()
	{
		$PATH=APP_PATH_PLUG."wechat/conf";
		load_conf($PATH);
	}
	//获取微信的access_token
	public function Get_Token(){
		$file=APP_PATH."plugin/wechat/conf/access_token/".md5(C('md5')).".php";
		$data=@include_once $file;
	    if ($data['expires_in'] < time() || !$data) {
		    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C('wechat|wechat.appid')."&secret=".C('wechat|wechat.appsecret');
		    $data = json_decode(http_request($url),true);
		    if($data['access_token']) {
		    	$time=time() + $data['expires_in']-'60';
			    $set="<?php \r\nreturn [\n ";
				$set .="\t'access_token'=>\"".$data['access_token']."\",\r\n";
				$set .="\t'expires_in'=>\"".$time."\",\r\n";
				$set.="]\r\n?>";
			    write_file($file, $set);
		    }else{
		    	return C('wechat|errcode.'.$data['errcode']);
		    }
	    }
	    return $data['access_token'];
	}
	
	public function getticket($Url){
		$ticket=$this->_getticket();
		$rand=_rand('8');
		$sha1 = "jsapi_ticket=$ticket&noncestr=".$rand."&timestamp=".NOWTIME."&url=".$Url;
		$sha1 = sha1($sha1);
		$array=[
				"appid" =>C('wechat|wechat.appid'),
                "nonceStr" =>$rand,
                "timestamp" =>NOWTIME,
                "url" => $Url,
                "signature" =>$sha1
			];
        return  $array;
	}
	
	//获取微信的getticket
	private function _getticket(){
		 if (C('wechat|ticket_expires_in') < NOWTIME) {
			$access_token=$this->Get_Token();
		    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
		    $res = json_decode(http_request($url),true);
			if($res['ticket']) {
				$file=APP_PATH."plugin/wechat/conf/ticket.php";
				$time=time() + '7000';
			    $set="<?php \r\nreturn [\n ";
				$set .="\t'ticket'=>\"".$res['ticket']."\",\r\n";
				$set .="\t'ticket_expires_in'=>\"".$time."\",\r\n";
				$set.="]\r\n?>";
			    write_file($file, $set);
			}
			$ticket=$res['ticket'];
		}else{
			$ticket=C('ticket');
		}
		return $ticket;
	}
	
	
	//微信注册
	public function reg($openid=''){
		
		$data=$this->get_wechat_userinfo($openid);
		
		if($data['errcode']){
			return $data ;
		}

		$is_attention=$data['subscribe'] ? 1 : 0;
		
		$openid = htmlspecialchars($data['openid']);
		
		$username = str_replace(array('|',' ','',"'",'"','/','*',',','~',';','<','>','$',"\\","\r","\t","\n","`","!","?","%","^"),'',$data['nickname']);
		
		$username = htmlspecialchars($username);
		
		$thumb = htmlspecialchars($data['headimgurl']);
		
		$test_user=(new User)->GET_User_Name($username);

		if($test_user['code']=='0' || strlen($username) <'4' || strtolower($username)=='admin' || strtolower($username)=='test' || strlen($username) > '255'){
			if(strtolower($username)=='admin' || strtolower($username)=='test' || strlen($username) > '255'){
				$username='wx'.time().rand(1000,9999);
			}else{
				$username=$username.rand(1000,9999);
			}
		}
		//随机一个密码
		$password = rand(100000,999999);
		//随机一个邮箱
		 $email = rand(100000000,999999999).'@qq.com';
		
		C('wechat|wechat.reg_groupid') ? $groupid=C('wechat|wechat.reg_groupid') :$groupid='2';
		$rand=_rand('4');
		$userDB=[
			'username'=>$username,
			'password'=>md5(md5($data['password']).$rand),
			'rand'=>$rand,
			'groupid'=>$groupid,
			'email'=>$email,
			'thumb'=>$thumb,
			'address'=>"$data[country] $data[province] $data[city]",
			'state'=>'1',
			'sex'=>intval($data['sex']),
			'mobile'=>'',
			'regtime'=>NOWTIME,
			'regip'=>onlineip,
			'wechat_openid'=>$openid,
			'wechat_is_attention'=>$is_attention
		];
		$uid = db::insert(jab.'user')->cols($userDB)->query();
		hook_listen('wechat_reg',$uid);
		return $uid;
	}
	
	//获取用户信息
	public function get_wechat_userinfo($openid){
		$access_token = $this->Get_Token();
		$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
		$data = json_decode(http_request($url),true);
		return $data;
	}
	//自主向用户发送消息
	public function message_custom_send($to_openid,$data,$msgtype='text'){
		$access_token = $this->Get_Token();
		$url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
		//发送图片消息
		if($msgtype=='text'){
			
			$msg=[
				"touser"=>$to_openid,
				"msgtype"=>"text",
				"text"=>[
					"content"=>$data['content']
				]
			];
		}elseif($msgtype=='voice'){
			//发送语音消息
			$msg=[
				"touser"=>$to_openid,
				"msgtype"=>"voice",
				"voice"=>[
					"media_id"=>$data['media_id']
				]
			];
		}elseif($msgtype=='video'){
			//发送视频消息
			$msg=[
				"touser"=>$to_openid,
				"msgtype"=>"video",
				"video"=>[
					"media_id"=>$data['media_id'],
				    "thumb_media_id"=>$data['media_id'],
				    "title"=>$data['title'],
				    "description"=>$data['content']
				]
			];
		}elseif($msgtype=='music'){
			//发送音乐消息
			$msg=[
				"touser"=>$to_openid,
				"msgtype"=>"music",
				"music"=>[
					"title"=>$data['title'],
				    "description"=>$data['content'],
				    "musicurl"=>$data['musicurl'],
				    "hqmusicurl"=>$data['hqmusicurl'],
				    "thumb_media_id"=>$data['thumb_media_id'] 
				]
			];
		}elseif($msgtype=='news'){
			//发送图文消息（点击跳转到外链） 图文消息条数限制在8条以内，注意，如果图文数超过8，则将会无响应
			if($data['media_id']){
				//有固定模板
				$msg=[
				"touser"=>$to_openid,
					"msgtype"=>"mpnews",
					"mpnews"=>[
						"media_id"=>$data['media_id']
					]
				];
			}else{
				//自主选择发送
				foreach($data['list'] AS $key=>$row){
					if($key > '7'){
						continue;
					}
					$_row['title']=$row['title'];
					$_row['description']=$row['content'];
					$_row['url']=$row['url'];
					$_row['picurl']=get_file_url($row['picurl']);
					$list[]=$_row;
				}
				//发送音乐消息
				$msg=[
					"touser"=>$to_openid,
					"msgtype"=>"news",
					"news"=>[
						"articles"=>$list
					]
				];
			}
		}elseif($msgtype=='wxcard'){
			//微信卡券专用，暂时先放着
			//发送卡券
			//特别注意客服消息接口投放卡券仅支持非自定义Code码和导入code模式的卡券的卡券
			$msg=[
				"touser"=>$to_openid,
					"msgtype"=>"wxcard",
					"wxcard"=>[
						"card_id"=>$data['card_id']
					]
				];
		}elseif($msgtype=='wxcard'){
			//发送小程序卡片（要求小程序与公众号已关联）
			$msg=[
				"touser"=>$to_openid,
					"msgtype"=>"miniprogrampage",
					"miniprogrampage"=>[
						"title"=>$data['title'],
						"appid"=>$data['appid'],
						"pagepath"=>$data['pagepath'],
						"thumb_media_id"=>$data['thumb_media_id'],
					]
				];
		}
		$msg=json_encode($msg,JSON_UNESCAPED_UNICODE);
		$res = json_decode(http_request($url,$msg),true);
		return $res;
	}
	
	//向用户发送输入状态信息
	public function message_custom_typing($to_openid){
		/*	此接口需要客服消息接口权限。如果不满足发送客服消息的触发条件，则无法下发输入状态。下发输入状态，需要客服之前30秒内跟用户有过消息交互。
			在输入状态中（持续15s），不可重复下发输入态。在输入状态中，如果向用户下发消息，会同时取消输入状态。
			返回码说明
			参数  	说明
			45072	command字段取值不对
			45080	下发输入状态，需要之前30秒内跟用户有过消息交互
			45081	已经在输入状态，不可重复下发
		*/
		$msg=[
				"touser"=>$to_openid,
				"command"=>"Typing",
			];
			
		$res = json_decode(http_request($url,json_encode($msg)),true);
		return  $res;
	}
	
	/*
	 * 
	 	自主回复消息
	 	$toUsername ,需要发送给的用户OPENID
		$fromUsername,开发者的OPENID
	*/
	public function post_msg($toUsername,$fromUsername,$data=[],$type='text'){
		$time = time();
		switch($type){
			//文本消息
			case 'text':
				$textTpl = "
					<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>    
                        <FromUserName><![CDATA[%s]]></FromUserName>    
                        <CreateTime>%s</CreateTime>    
                        <MsgType><![CDATA[text]]></MsgType>    
                        <Content><![CDATA[%s]]></Content>
                   </xml>";
                $resultStr = sprintf($textTpl, $toUsername, $fromUsername, $time, $data['description']);    
                echo $resultStr;
				break;
			//图片消息
			case 'image':
				$textTpl="
					<xml>
						<ToUserName><![CDATA[%s] ]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime><MsgType>
						<![CDATA[image]]></MsgType>
						<Image>
							<MediaId>< ![CDATA[%s]]></MediaId>
						</Image>
					</xml>
				";
				$resultStr = sprintf($textTpl, $toUsername, $fromUsername, $time, $data['mediaid']);    
                echo $resultStr;
				break;
			//语音消息
			case 'voice':
				$textTpl="
					<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[voice]]></MsgType>
						<Voice>
							<MediaId>< ![CDATA[%s]]></MediaId>
						</Voice>
					</xml>
				";
				$resultStr = sprintf($textTpl, $toUsername, $fromUsername, $time, $data['mediaid']);    
                echo $resultStr;
				break;
			//视频消息
			case 'video':
				$textTpl="
					<xml>
						<ToUserName>< ![CDATA[".$toUsername."]]></ToUserName>
						<FromUserName>< ![CDATA[".$fromUsername."]]></FromUserName>
						<CreateTime>".$time."</CreateTime>
						<MsgType>< ![CDATA[video]]></MsgType>
						<Video>
							<MediaId>< ![CDATA[".$data['mediaid']."] ]></MediaId>
							<Title>< ![CDATA[".$data['title']."]]></Title>
							<Description>< ![CDATA[".$data['description']."]]></Description>
						</Video>
					</xml>
				";
				  
                echo $textTpl;
				break;
			//回复音乐消息
			case 'music':
				$textTpl="
					<xml>
						<ToUserName><![CDATA[".$toUsername."] ]></ToUserName>
						<FromUserName><![CDATA[".$fromUsername."]]></FromUserName>
						<CreateTime>".$time."</CreateTime>
						<MsgType><![CDATA[music]]></MsgType>
						<Music>
							<Title><![CDATA[".$data['title']."]]></Title>
							<Description><![CDATA[".$data['description']."]]></Description>
						<MusicUrl>
							<![CDATA[".$data['musicurl']."] ]>
						</MusicUrl>
							<HQMusicUrl><![CDATA[".$data['hqmusicurl']."]]></HQMusicUrl>
							<ThumbMediaId><![CDATA[".$data['mediaid']."]]></ThumbMediaId>
						</Music>
					</xml>
				";
                echo $textTpl;
				break;
			//回复图文消息
			case 'news':
				//设置数量
				$num=count($data['list']);
				if($num >= '8'){
					$num='7';
				}
				/*
				 * $data样式
				 *$data=[
	    			'list'=>[
	    				['title'=>'1'],['title'=>'2'],['title'=>'3']
	    			]
	    		];*/
				//取出
				$listDB='';
				foreach($data['list'] as $key => $row){
					if($key > '6'){
						continue;
					}
					$listDB.=" <item>
						            <Title><![CDATA[".$row['title']."]]></Title>
						            <Description><![CDATA[".$row['description']."]]></Description>
						            <PicUrl><![CDATA[".$row['picurl']."]]></PicUrl>
						            <Url><![CDATA[".$row['url']."]]></Url>
						        </item>
						    ";
				}
				
				$textTpl="
						<xml>
						    <ToUserName><![CDATA[".$toUsername."]]></ToUserName>
						    <FromUserName><![CDATA[".$fromUsername."]]></FromUserName>
						    <CreateTime>".$time."</CreateTime>
						    <MsgType><![CDATA[news]]></MsgType>
						    <ArticleCount>".$num."</ArticleCount>
						    <Articles>
						        ".$listDB."
						    </Articles>
						</xml>
				";
                echo $textTpl;
				break;
		}
	}
}
?>