| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?php
- namespace app\index\controller;
- use think\Controller;
- class Msg extends Controller{
- public function valid(){
-
- //获取随机字符串
- $echoStr = input("echostr");
-
- if($echoStr){
- // 验证接口的有效性,由于接口有效性的验证必定会传递echostr 参数
- if($this ->checkSignature()){
- echo $echoStr;
-
- exit;
- }
- }else{
- $this->responseMsg();
- }
- }
- protected function checkSignature()
- {
- // 微信加密签名
- $signature = input("signature");
- $timestamp = input("timestamp");//时间戳
- $nonce =input("nonce");//随机数
- $token = "weixin"; //token值,必须和你设置的一样
- $tmpArr =array($token,$timestamp,$nonce);
- sort($tmpArr,SORT_STRING);
- $tmpStr = implode($tmpArr);
- $tmpStr =sha1($tmpStr);
- if($tmpStr == $signature){
- return true;
- }else{
- return false;
- }
- }
-
- function responseMsg()
- {
-
- $postStr = file_get_contents('php://input','r');
- if(empty($postStr)){
- echo "";
- exit;
- }
- libxml_disable_entity_loader(true);
- $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
- // 发送方账号
- $fromUsername = $postObj->FromUserName;
- //开发者账号
- $toUsername = $postObj->ToUserName;
- // 文本信息内容,仅仅针对文本消息有值
- $keyword = trim($postObj->Content);
- $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>";
-
- $msgType =$postObj->MsgType;
- if($msgType=="event"){
- // 表示为事件
- $Event =$postObj->Event;//获取事件的类型
- if($Event=="subscribe"){
- // 关注
- $contentStr ="欢迎关注保修系统";
- $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,'text', $contentStr);
- echo $resultStr;
- }elseif($Event=="unsubscribe"){
- // 取消关注 不能回复消息
-
- }
- }else{
- echo '';
- exit;
- }
- }
- }
|