class Wechat extends Controller

{
  private $appid='';
  private $appsecret='';
  public function index(){
    // $this->createMenu();
    // echo $this->getToken();
  }

/**
* 素材上传页面
* @return mixed
*/
public function files(){
return $this->fetch('upload');
}
/**
*微信上传素材
*/
public function upload(){
$request=request();
$file=$_FILES['file'];
if($request->param()['type']=='image'){
// print_r($file);
$this->uploads('image',$file);
}
}
public function uploads($type,$arr){
  $token=$this->getToken();//调用接口需要获取token
  // 临时素材上传
  $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=".$type;
  // 永久上传上传
  // $url ="https://api.weixin.qq.com/cgi-bin/material/add_news?access_token".$token."&type=".$type;
  //这里是请求地址,token和素材类型通过get方式传递
  $time=time();
  if($type=="image"){
    $name="uploads/$time.png";
  }elseif($type=="video"){
    $name="uploads/$time.mp4";
  }
  if(move_uploaded_file($arr["tmp_name"],"uploads/$name")) {
    $file_path = realpath("uploads/$time.png");
    //这里声明文件的路径,使用绝对路径
    if(class_exists('\CURLFile')) {
      $data = array('media' => new \CURLFile($file_path));
    }else{
      $data = array('media' => '@'.$file_path);
    }
      $str=$this->curl($url,"post","https",$data);
      $media_id=json_decode($str)->media_id;
      $created_at=json_decode($str)->created_at;//媒体文件上传时间戳
      echo $media_id;
    } else {
      echo '上传失败';
    }
  }

/**
*微信接口
*/
public function valid()
{
$str=$this->responseMsg();
echo $str;
// if(!empty(request()->param())) {
// if ($this->checkSignature()) {
// $echoStr = request()->param("echostr");
// ob_clean(); //清除之前的所有输出
// echo $echoStr;
// exit;
// }
// }
}

/**
* 微信连接是验证函数
* @return bool
*/
private function checkSignature()
{
if(!empty(request()->param())){
$signature = request()->param("signature");
$timestamp = request()->param("timestamp");
$nonce =request()->param("nonce");
$token = "weixin2009";
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}

}

/**
* 根据传入传入的值返回不同的内容
* @return string
*/
public function responseMsg()
{
//get post data, May be due to the different environments
// $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
$postStr = file_get_contents("php://input");//接收消息
//extract post data
if (!empty($postStr)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //用户openId
$toUsername = $postObj->ToUserName; //微信公众号
$msgType=$postObj->MsgType; //消息类型
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
}
if($msgType=="event"){
$event=$postObj->Event; //发送事件
if($event=='subscribe'){//订阅事件
$msgType = "text";
$contentStr = "Welcome to dry!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}elseif($event=='CLICK'){
$EventKey=$postObj->EventKey; //发送key
if($EventKey=='V1001_GOOD'){
$msgType = "text";
$contentStr = "赞一下!!!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}
}
}elseif($msgType=="text"){
$keyword = trim($postObj->Content); //发送内容
if($keyword=='1'){
$msgType = "text";
$contentStr = "你好!!!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}elseif($keyword=='2'){
$msgType = "text";
$contentStr = "hello!!!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}elseif($keyword=='3'){//图片
$msgType = "image";
$MediaId = "HLh5cqnebahKNlKpjCvcgbJZ85SXHOgbKs3--cqKybXh7OOCJfeazkTQXZCftfyD";
$image="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image><MediaId><![CDATA[%s]]></MediaId></Image>
</xml>";
$resultStr = sprintf($image, $fromUsername, $toUsername,$time, $msgType, $MediaId);
return $resultStr;
}elseif($keyword=='4'){//图文
$arr = array(
array('title' => '百度新闻消息', 'description' => '百度新闻消息描述', 'pic' => 'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=3062734635,4183904616&fm=96', 'url' => 'http://news.baidu.com'),
array('title' => '新浪新闻消息', 'description' => '新浪新闻消息描述', 'pic' => 'https://img04.sogoucdn.com/app/a/4001/7e126b8c-39ef-41ff-8ac9-50ab0e5d1c5f.jpg', 'url' => 'http://news.sina.com.cn'),
array('title' => '腾讯新闻消息', 'description' => '腾讯新闻消息描述', 'pic' => 'https://img01.sogoucdn.com/app/a/100520115/7f4c79817fabaeaa0e909754cfe655e7', 'url' => 'http://news.qq.com'),
array('title' => '搜狐新闻消息', 'description' => '搜狐新闻消息描述', 'pic' => 'http://www.phpos.net/image/news3.png', 'url' => 'http://news.sohu.com')
);
$num = count($arr);
$news="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>$num</ArticleCount>
<Articles>";
$str="<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
foreach($arr as $item){
$rstr=sprintf($str,$item['title'],$item['description'],$item['pic'],$item['url'] );
$news.=$rstr;
}
$news.="</Articles></xml>";
$resultStr = sprintf($news, $fromUsername, $toUsername, $time );
return $resultStr;
}elseif($keyword=='5'){//音乐
$title="音乐";
$Description="音乐播放";
$Url="http://mp3.qqmusic.cc/yq/213942399.mp3";//音乐链接
$Url1="http://mp3.qqmusic.cc/yq/213942399.mp3";//音乐高清链接wifi下播放
$MediaId = "HLh5cqnebahKNlKpjCvcgbJZ85SXHOgbKs3--cqKybXh7OOCJfeazkTQXZCftfyD";
$music="<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
</Music>
</xml>";
$resultStr = sprintf($music, $fromUsername, $toUsername, $time,$title,$Description,$Url,$Url1,$MediaId);
return $resultStr;
}else{
$msgType = "text";
$contentStr = "不合法请求";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}
}elseif($msgType=="image"){
$msgType = "text";
$contentStr = "图片消息";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}elseif($msgType=="voice"){
$msgType = "text";
$contentStr = "语言消息";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}elseif($msgType=="video"){
$msgType = "text";
$contentStr = "视频消息";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}elseif($msgType=="location"){
$msgType = "text";
$contentStr = "地理位置消息";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
return $resultStr;
}
}

/**
* 得到各人信息
* @param $id
*/
public function getBaseInfo($id){
$token=$this->getToken();
$url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$id."&lang=zh_CN";
$str=$this->curl($url);
// $unionid=json_decode($str)->unionid;
file_put_contents('base.txt',$str);
}

/**
*系统生成菜单
*/
public function createMenu(){
$data='{
"button": [
{
"type": "view",
"name": "预定",
"url": "http://www.baidu.com/"
},
{
"type": "view",
"name": "查看订单",
"url": "http://www.baidu.com/"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"搜索",
"url":"http://www.soso.com/"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}]
}
]
}';
$token=$this->getToken();
$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token;
$str=$this->curl($url,"post","https",$data);
// var_dump($str);
}

/**
* 抓取网页内容返回json串
* @param $url
* @param string $method get/post 默认get
* @param string $type http/https 默认http
* @param string $data $method 为post 时必须写
* @return mixed|string
*/
public function curl($url, $method="get", $type="http", $data=""){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
if($type=="https"){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//不做服务器认证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//不做客户端认证
}
if($method=="post"){
curl_setopt($ch, CURLOPT_POST, TRUE);//设置请求是POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
$data=curl_exec($ch);
curl_close($ch);
return $data;
}

/**
* 得到token值,2小时刷新一次
* @return string
*/
public function getToken(){
$file="token.txt";
if(file_exists($file)){
$time=time();
$rtoken=filemtime($file);
if(($time-$rtoken)<7000){
$token=file_get_contents($file);
}else{
$str=$this->curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret);
$token=json_decode($str)->access_token;
file_put_contents('token.txt',$token);
}
}else{
$str=$this->curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret);
$token=json_decode($str)->access_token;
file_put_contents('token.txt',$token);
}
return $token;
}
}