<?php namespace WeChat\Model; use Think\Model; class JieRuModel extends Model { private $_token = ''; //令牌 private $appid; private $appsecret; public function __construct() { $this->_token = C('WECHAT.TOKEN'); //实例令牌 $this->appid = C('WECHAT.APPID');//公众号的appid $this->appsecret = C('WECHAT.APPSECRET');//公众号的秘钥 //文本模板 $this->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>"; //图文模板 $this->newsTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[news]]></MsgType> <ArticleCount>%s</ArticleCount> <Articles>%s </Articles> </xml>"; //图文模板里面的内容 $this->item = "<item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item>"; //音乐模板 $this->musicTpl = "<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>"; } //验证开发者机器的有效性 public function JieRu() { if($this->checkSignature()){ $echoStr = $_GET["echostr"]; echo $echoStr; exit; }else{ echo '失败'; } } //检验signature private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = $this->_token; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if ($tmpStr == $signature) { return true; } else { return false; } } //处理所有的微信相关信息请求和响应的处理 public function responseMsg() { //也就是说基本上$GLOBALS['HTTP_RAW_POST_DATA'] 和 $_POST是一样的。 //但是如果post过来的数据不是PHP能够识别的,你可以用 $GLOBALS['HTTP_RAW_POST_DATA']来接收,比如 text/xml 或者 soap 等等。 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //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 */ //xml安全设置操作,微信建议开启的 libxml_disable_entity_loader(true); //postStr数据进行解析 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); switch ($postObj->MsgType) { case 'text': $this->_doText($postObj); //处理文本信息的方法 break; case 'image': $this->_doImage($postObj); //处理图片消息的方法 break; case 'location': $this->_doLocation($postObj); //处理位置信息的方法 break; case 'event': $this->_doEvent($postObj); //处理事件消息的方法 break; default: # code... break; } } } /* * 处理事件类型 * Time:2016年7月10日16:14:20 * By:php47 */ private function _doEvent($postObj){ //判断event值的类型,进行相对应的操作 switch ($postObj->Event) { case 'subscribe': $this->_doSubscribe($postObj); //处理关注事件 break; case 'unsubscribe': $this->_doUnsubscribe($postObj); //处理取消关注事件 break; case 'CLICK': $this->_doClick($postObj); //处理自定义菜单点击事件 break; default: # code... break; } } /* * 点击事件的处理 * Time:2016年7月10日16:51:53 * By:php47 * */ private function _doClick($postObj){ switch ($postObj->EventKey) { case 'news': $this->_sendTuwen($postObj); //处理news Click值的方法,发送图文方法 break; default: # code... break; } } /* * 发送音乐信息 * Time:2016年7月10日17:22:48 * By:php47 * */ private function _sendMusic($postObj){ //1.歌曲信息的组合 $Title = '小歌曲'; $Description = '小歌曲'; $MusicUrl = 'http://so1.111ttt.com:8282/2016/1/06/20/199201048457.mp3?tflag=1466389833&pin=70d37142ea5d912f168918986e2e5ad1'; $HQMusicUrl = 'http://so1.111ttt.com:8282/2016/1/06/20/199201048457.mp3?tflag=1466389833&pin=70d37142ea5d912f168918986e2e5ad1'; $ThumbMediaId = 'Q4LZnvVfOWowvVj2q0z4X2YrTqqj2MsOD8SWN8cckROpAaMZ05STV5wWg9aaIHsW'; //2.组合模板 $resultStr = sprintf($this->musicTpl, $postObj->FromUserName, $postObj->ToUserName, time(), $Title, $Description, $MusicUrl, $HQMusicUrl, $ThumbMediaId); //3.输出模板信息 echo $resultStr; } /* * 发送图文方法 * Time:2016年7月10日17:00:49 * By:php47 * */ private function _sendTuwen($postObj){ //组合新闻数组 $newsList = array( array( 'Title' => ' 决战!C罗还差一步加冕欧洲之王!', 'Description' => '经过了一个多月的鏖战,由24路诸侯几百名球员联袂出演的法兰西之夏即将迎来最终结局。两张决赛门票一张属于东道主法国,经过了一个多月的鏖战,由24路诸侯几百名球员联袂出演的法兰西之夏即将迎来最终结局。两张决赛门票一张属于东道主法国,另一张则是属于低开高走,常规时间五平一胜杀进决赛的葡萄牙。而两支队伍的一切奋斗与汗水都将在7月11日得到答案。是留下一个伤心的背影,抑或是带走所有的蛋糕。', 'PicUrl' => 'http://img1.gtimg.com/sports/pics/hv1/233/90/2096/136315583.jpg', 'Url' => 'http://sports.qq.com/fans/post.htm?id=1539363816777711645&mid=142#1', ), array( 'Title' => '球探-法国新磐石武装巴萨 欧洲杯36年第一人', 'Description' => '腾讯体育7月8日讯 法国淘汰德国杀入欧洲杯决赛,同时也是队史上首次在欧洲杯零封日耳曼战车,蓝衣军防线表现出色,尤其是新锐国脚乌姆蒂蒂,连续两战打出高水准,巴萨斥资2500万欧元提前将其购入,实属明智。', 'PicUrl' => 'http://img1.gtimg.com/sports/pics/hv1/92/208/2095/136280507.jpg', 'Url' => 'http://sports.qq.com/a/20160708/026374.htm', ), ); $items = ''; //循环输出item模板 foreach ($newsList as $key => $value) { $items .= sprintf($this->item, $value['Title'], $value['Description'], $value['PicUrl'], $value['Url']); } $contentStr = sprintf($this->newsTpl, $postObj->FromUserName, $postObj->ToUserName, time(), count($newsList), $items); echo $contentStr; } /* * 关注事件处理 * Time:2016年7月10日16:21:01 * By:php47 * */ private function _doSubscribe($postObj){ $contentStr = '欢迎关注我们东升超越物流!'; $resultStr = sprintf($this->textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), "text", $contentStr); echo $resultStr; } /* * 取消关注事件处理 * Time:2016年7月10日16:28:31 * By:php47 * */ private function _doUnsubscribe($postObj){ //删除用户的一些信息获取绑定的相关操作 } /* * 处理文本信息 * Time:2016年7月10日15:02:30 * By:php47 */ private function _doText($postObj){ $keyword = trim($postObj->Content); if(!empty( $keyword )) { $msgType = "text"; $url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg='.$keyword; //2.get请求,直接发送 $contents = $this->request($url,false); //3.处理返回值 //json转化为对象信息 $contents = json_decode($contents); //输出返回的信息 $contentStr = $contents->content; $resultStr = sprintf($this->textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), $msgType, $contentStr); echo $resultStr; } } /* * 处理图片消息 * Time:2016年7月10日15:51:09 * By:php47 * */ private function _doImage($postObj){ //把接收到图片地址链接以文本形式返回 $PicUrl = $postObj->PicUrl; //保存文件到服务器 // $pic = $this->request($PicUrl,false); // file_put_contents('./pic.png',$pic); $resultStr = sprintf($this->textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), "text", $PicUrl); echo $resultStr; } /* * 处理位置消息 * Time:22016年7月10日16:03:23 * By:php47 * */ private function _doLocation($postObj){ //组合x,y数据 $contentStr = '您当前x为:'.$postObj->Location_X.',Y为:'.$postObj->Location_Y; $resultStr = sprintf($this->textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), "text", $contentStr); echo $resultStr; } //封装请求方法 public function request($url,$https=true,$method='get',$data=null){ //1.初始化url $ch = curl_init($url); //2.设置相关的参数 //字符串不直接输出,进行一个变量的存储 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //判断是否为https请求 if($https === true){ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } //判断是否为post请求 if($method == 'post'){ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } //3.发送请求 $str = curl_exec($ch); //4.关闭连接 curl_close($ch); //返回请求到的结果 return $str; } /* * 获取access_token(获取很多借口的凭证) * Time:2016年7月9日11:25:24 * By: php47 * */ public function getAccessToken(){ $lasttime = session('lasttime'); if($lasttime and time() < ($lasttime+3600)){ return session('access_token');exit; } //1.url地址 $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret; //2.get方式,直接发送放松请求 $content = $this->request($url); //3.处理返回值,先看看 //返回值json字符串,pph不能直接进行操作,把它传化为一个对象或者数组进行操作 $content = json_decode($content); $access_token = $content->access_token; session('lasttime',time()); session('access_token',$access_token); return $access_token; } /* * 创建菜单操作 * Time:2016年7月9日17:10:06 * By:php47 * */ public function createMenu(){ $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->getAccessToken(); $data = '{' .'"button":[{' .'' .'"type":"view",' .'"name":"在线下单",' .'"url":"http://dongsheng.qmlzsm.com/dswiliu/index.php/"' .'},{' .'"name":"积分商城",' .'"sub_button":[{' .'"type":"view",' .'"name":"代缴罚款",' .'"url":"http://dongsheng.qmlzsm.com/dswiliu/index.php?c=amerce"' .'},{' .'"type":"view",' .'"name":"积分商城",' .'"url":"http://dongsheng.qmlzsm.com/dswiliu/index.php?m=Home&c=integralMall&a=index"' .'}]' .'},{' .'"type":"view",' .'"name":"我的",' .'"url":"http://dongsheng.qmlzsm.com/dswiliu/index.php?c=User"' .'}]' .'}'; //3.携带post数据,发送请求 $content = $this->request($url,true,'post',$data); //4.处理返回值 //把json转化成一个对象 $content = json_decode($content); //业务逻辑判断 if($content->errmsg == 'ok'){ echo '创建菜单成功!'; }else{ echo '创建失败,错误代码为:'.$content->errcode; } } //发送模板信息 public function send_template_message($data){ //模板消息(里面的选项具体根据提供的模板设置) $template = array( 'touser' => $data['openid'],//用户的openid 'template_id' => C('WECHAT.MOBAN_ID'),//模板id 'url' => '',//点击模板的跳转地址 'data' => array( 'first' => array( 'value' => '尊敬的客户您好', 'color' => '#000000', ), 'keyword1' => array( 'value' => $data['danhao'], 'color' => '#000000', ), 'keyword2' => array( 'value' => $data['goodsName'].",".$data['loadingAddr'].'-'.$data['unloadingAddr'].",业务员已开单,请及时取单", 'color' => '#000000', ), 'remark' => array( 'value' => $data['time'], 'color' => '#000000', ) ) ); $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->getAccessToken(); $data = json_encode($template); $res = $this->request($url,true,'post',$data); return json_decode($res, true); } }
转载请注明原文地址: https://www.6miu.com/read-83183.html