前言
今天学习了微信公众号开发,学习过程极度曲折,首先是因为大小写问题,一直提示配置出错;然后因为我用方蓓那个微信测试工具,
回复消息一直为空,搞了许久用官方的接口就好了,辛苦抄了一下午的代码终于把回复搞定了,于是想把源码贴出来便于初学者测试用。
源码说明
本源码只有基础的验证配置和简单文字回复功能。
源码(没安装代码工具格式有点乱,见谅)
<?php
// 接收参数
define("TOKEN", "test123456");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest{
public function valid() {
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
$this->responseMsg();
exit;
}
}
public function transmitText($object, $content) {
$xmlTpl = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>';
$res = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $res;
}
public function responseMsg() {
//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();
$res = $this->transmitText($postObj, $keyword);
echo $res;
}else {
echo "";
exit;
}
}
private function checkSignature() {
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
截图说明