wechatcallbackresponse.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Created by 上海风车教育科技有限公司.
  4. * User: 刘红伟
  5. * Date: 15-11-24
  6. * Email: 454303753@qq.com
  7. * File:wechatcallbackresponse.php
  8. */
  9. class wechatcallbackresponse{
  10. public function responseMsg()
  11. {
  12. //get post data, May be due to the different environments
  13. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  14. //extract post data
  15. if (!empty($postStr)){
  16. /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
  17. the best way is to check the validity of xml by yourself */
  18. libxml_disable_entity_loader(true);
  19. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  20. $fromUsername = $postObj->FromUserName;
  21. $toUsername = $postObj->ToUserName;
  22. $keyword = trim($postObj->Content);
  23. $time = time();
  24. $textTpl = "<xml>
  25. <ToUserName><![CDATA[%s]]></ToUserName>
  26. <FromUserName><![CDATA[%s]]></FromUserName>
  27. <CreateTime>%s</CreateTime>
  28. <MsgType><![CDATA[%s]]></MsgType>
  29. <Content><![CDATA[%s]]></Content>
  30. <FuncFlag>0</FuncFlag>
  31. </xml>";
  32. if(!empty( $keyword ))
  33. {
  34. $msgType = "text";
  35. $contentStr = "Welcome to wechat world!";
  36. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  37. echo $resultStr;
  38. }else{
  39. echo "Input something...";
  40. }
  41. }else {
  42. echo "";
  43. exit;
  44. }
  45. }
  46. private function checkSignature()
  47. {
  48. // you must define TOKEN by yourself
  49. if (!defined("TOKEN")) {
  50. throw new Exception('TOKEN is not defined!');
  51. }
  52. $signature = $_GET["signature"];
  53. $timestamp = $_GET["timestamp"];
  54. $nonce = $_GET["nonce"];
  55. $token = TOKEN;
  56. $tmpArr = array($token, $timestamp, $nonce);
  57. // use SORT_STRING rule
  58. sort($tmpArr, SORT_STRING);
  59. $tmpStr = implode( $tmpArr );
  60. $tmpStr = sha1( $tmpStr );
  61. if( $tmpStr == $signature ){
  62. return true;
  63. }else{
  64. return false;
  65. }
  66. }
  67. }