微信接口文件关键部分:
define("TOKEN", "myweixin");
//define your token ,用于对接时的验证
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
//处理请求
}else{
$wechatObj->valid();
//用于验证,第一次接入后就可以关闭
}
class wechatCallbackapiTest{
public function valid(){
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
//这个函数就是专门处理业务逻辑
public function responseMsg($connect){
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//extract post data
//如果用户输入不为空
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
//这个event就是事件的具体内容
$event = $postObj->Event;
$key = $postObj->EventKey;
//如果我们做微信开发时,当需要调试信息时,请将信息输出到文件中
//file_put_contents('abc.log',$fromUsername.' '.$toUsername.' '.FILE_APPEND);
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
//当用户关注我们微信平台时,会发送一个订阅事件,我们处理即可
//存在类型,类型为event时
switch($postObj->MsgType){
case 'event':
break;
case 'text':
break;
}
}
private function checkSignature(){
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
被动回复信息,其他类型请自行参考文档
文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432
其他参考链接:
https://www.jianshu.com/p/131d0c4a07cf
https://www.cnblogs.com/txw1958/p/wechat-tutorial.html