Msg.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace app\index\controller;
  3. use think\Controller;
  4. class Msg extends Controller{
  5. public function valid(){
  6. //获取随机字符串
  7. $echoStr = input("echostr");
  8. if($echoStr){
  9. // 验证接口的有效性,由于接口有效性的验证必定会传递echostr 参数
  10. if($this ->checkSignature()){
  11. echo $echoStr;
  12. exit;
  13. }
  14. }else{
  15. $this->responseMsg();
  16. }
  17. }
  18. protected function checkSignature()
  19. {
  20. // 微信加密签名
  21. $signature = input("signature");
  22. $timestamp = input("timestamp");//时间戳
  23. $nonce =input("nonce");//随机数
  24. $token = "weixin"; //token值,必须和你设置的一样
  25. $tmpArr =array($token,$timestamp,$nonce);
  26. sort($tmpArr,SORT_STRING);
  27. $tmpStr = implode($tmpArr);
  28. $tmpStr =sha1($tmpStr);
  29. if($tmpStr == $signature){
  30. return true;
  31. }else{
  32. return false;
  33. }
  34. }
  35. function responseMsg()
  36. {
  37. $postStr = file_get_contents('php://input','r');
  38. if(empty($postStr)){
  39. echo "";
  40. exit;
  41. }
  42. libxml_disable_entity_loader(true);
  43. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  44. // 发送方账号
  45. $fromUsername = $postObj->FromUserName;
  46. //开发者账号
  47. $toUsername = $postObj->ToUserName;
  48. // 文本信息内容,仅仅针对文本消息有值
  49. $keyword = trim($postObj->Content);
  50. $time = time();
  51. // 文字模板
  52. $textTpl = "<xml>
  53. <ToUserName><![CDATA[%s]]></ToUserName>
  54. <FromUserName><![CDATA[%s]]></FromUserName>
  55. <CreateTime>%s</CreateTime>
  56. <MsgType><![CDATA[%s]]></MsgType>
  57. <Content><![CDATA[%s]]></Content>
  58. <FuncFlag>0</FuncFlag>
  59. </xml>";
  60. $msgType =$postObj->MsgType;
  61. if($msgType=="event"){
  62. // 表示为事件
  63. $Event =$postObj->Event;//获取事件的类型
  64. if($Event=="subscribe"){
  65. // 关注
  66. $contentStr ="欢迎关注保修系统";
  67. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time,'text', $contentStr);
  68. echo $resultStr;
  69. }elseif($Event=="unsubscribe"){
  70. // 取消关注 不能回复消息
  71. }
  72. }else{
  73. echo '';
  74. exit;
  75. }
  76. }
  77. }