mp.init.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. if (! defined('IS_INITPHP'))
  3. exit('Access Denied!');
  4. /**
  5. * 微信基础类
  6. *
  7. * @author Chen Deben
  8. * @copyright Meitu
  9. */
  10. class mpInit {
  11. /**
  12. *
  13. * @var 接收到的数据
  14. */
  15. public $mpobj;
  16. public function __construct() {
  17. // $this->valid();
  18. $this->parseMp();
  19. }
  20. public function valid() {
  21. if ($this->checkSignature()) {
  22. $echoStr = $_GET['echostr'];
  23. if ($echoStr != "") {
  24. echo $echoStr;
  25. exit();
  26. }
  27. } else {
  28. exit("非法访问1!");
  29. }
  30. }
  31. public function parseMp() {
  32. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  33. if (! empty($postStr)) {
  34. libxml_disable_entity_loader(true);
  35. $this->mpobj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  36. } else {
  37. exit("非法访问2");
  38. }
  39. }
  40. /**
  41. * 获取用户发过来的指令keyword
  42. */
  43. public function getKeyword() {
  44. return InitPHP::output($this->mpobj->Content);
  45. }
  46. /**
  47. * 获取消息类型
  48. */
  49. public function getType() {
  50. return $this->mpobj->MsgType;
  51. }
  52. /**
  53. * 回复文本消息
  54. *
  55. * @param string $msg
  56. * 消息内容
  57. */
  58. public function responseText($msg) {
  59. $textTpl = "<xml>
  60. <ToUserName><![CDATA[%s]]></ToUserName>
  61. <FromUserName><![CDATA[%s]]></FromUserName>
  62. <CreateTime>%s</CreateTime>
  63. <MsgType><![CDATA[%s]]></MsgType>
  64. <Content><![CDATA[%s]]></Content>
  65. <FuncFlag>0</FuncFlag>
  66. </xml>";
  67. $resultStr = sprintf($textTpl, $this->mpobj->FromUserName, $this->mpobj->ToUserName, time(), "text", $msg);
  68. echo $resultStr;
  69. die();
  70. }
  71. /**
  72. * 校验授权
  73. *
  74. * @throws TOKEN未定义异常
  75. * @return boolean
  76. */
  77. private function checkSignature() {
  78. if (! defined("TOKEN")) {
  79. throw new Exception('TOKEN未定义!');
  80. }
  81. $signature = $_GET["signature"];
  82. $timestamp = $_GET["timestamp"];
  83. $nonce = $_GET["nonce"];
  84. $token = TOKEN;
  85. $tmpArr = array(
  86. $token,
  87. $timestamp,
  88. $nonce
  89. );
  90. sort($tmpArr, SORT_STRING);
  91. $tmpStr = implode($tmpArr);
  92. $tmpStr = sha1($tmpStr);
  93. if ($tmpStr == $signature) {
  94. return true;
  95. } else {
  96. return false;
  97. }
  98. }
  99. }