微信公众平台消息接口(PHP)-官方的Demo有问题

微信公众平台消息接口(PHP)-官方的Demo有问题,下面个人进行了处理,事例代码也跑不通,我研究了一番,终于搞定.

首先:在你的服务器上上传好一个接口文件,如http://www.phpfensi.com/weixin.php 内容如下:

  1. <?php
  2. define("TOKEN", "weixin");
  3. define("MESS","输入点啥吧");
  4. $wechatObj = new wechatCallbackapiTest();
  5. $wechatObj->valid();
  6. //$wechatObj->responseMsg();
  7. class wechatCallbackapiTest
  8. {
  9. public function valid()
  10. {
  11. $echoStr = $_GET["echostr"];
  12. if($this->checkSignature()){
  13. echo $echoStr;
  14. exit;
  15. }
  16. }
  17. public function responseMsg()
  18. {
  19. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  20. if (!emptyempty($postStr)){
  21. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  22. $fromUsername = $postObj->FromUserName;
  23. $toUsername = $postObj->ToUserName;
  24. $keyword = trim($postObj->Content);
  25. $time = time();
  26. $textTpl = "<xml>
  27. <ToUserName><![CDATA[%s]]></ToUserName>
  28. <FromUserName><![CDATA[%s]]></FromUserName>
  29. <CreateTime>%s</CreateTime>
  30. <MsgType><![CDATA[%s]]></MsgType>
  31. <Content><![CDATA[%s]]></Content>
  32. <FuncFlag>0<FuncFlag>
  33. </xml>";
  34. if(!emptyempty( $keyword ))
  35. {
  36. $msgType = "text";
  37. $contentStr = MESS;
  38. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  39. echo $resultStr;
  40. }else{
  41. echo MESS;
  42. }
  43. }else {
  44. echo MESS;
  45. exit;
  46. }
  47. }
  48. private function checkSignature()
  49. {
  50. $signature = $_GET["signature"];
  51. $timestamp = $_GET["timestamp"];
  52. $nonce = $_GET["nonce"];
  53. $token =TOKEN;
  54. $tmpArr = array($token, $timestamp, $nonce);
  55. sort($tmpArr);
  56. $tmpStr = implode( $tmpArr );
  57. $tmpStr = sha1( $tmpStr );
  58. if( $tmpStr == $signature ){
  59. return true;
  60. }else{
  61. return false;
  62. }
  63. }
  64. }
  65. ?>

然后:设置回复接口,填好URL和Token(必须跟上面定义的Token一致),这个接口先要验证,成功之后再注释掉$wechatObj->valid(); 这行,同时去掉//$wechatObj->responseMsg();这行的注释.

消息接口就可以使用了,发个消息试试看吧?