<?php //写你自己的token define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); //接口验证 /*$wechatObj->valid();*/ //调用回复消息方法 $wechatObj->responseMsg(); class wechatCallbackapiTest{ //验证方法 public function valid(){ $echoStr = $_GET["echostr"]; if($this->checkSignature()){ echo $echoStr; exit; } } //消息回复 public function responseMsg(){ $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //如果用户有请求 if (!empty($postStr)){ 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(); //消息类型 $msgType = $postObj->MsgType; //事件类型 $event = $postObj->Event; //xml模板 $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>"; //如果用户的请求类型是事件 if($msgType=="event"){ if($event=="subscribe"){ $contentStr = "欢迎词"; } } //用户的请求类型是文本 if($msgType=="text"){ $contentStr =$keyword; $msgType = "text"; } //自动填充xml $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); //回复 echo $resultStr; } //用户没有请求 else{ echo ""; exit; } } //验证 private function checkSignature(){ if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); } $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } }
微信自动回复模板
回复图片模板