1、首先我们要有域名
2、在服务器上创建一个文件wechatCallbackapiTest.php
3、文件写入以下代码
<?php
/**
* wechat php test
*/
//默认token
define("TOKEN", 'weixin');
$wechatObj = new wechatCallbackapiTest();
//初始化配置 连接服务器
$wechatObj->valid();
//自动回复
//$wechatObj->responseMsg();
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = file_get_contents('php://input');
//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();
$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(!empty( $keyword ))
{
//消息类型
$msgType = "text";
//内容
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}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;
}
}
}
4、进入公众号后台

?5、修改配置

?服务器地址一定要能够访问到服务器的文件,token必须与服务器上的token一样
点击提交,出现

?就可以了。
若出现token验证失败,可检查
(1)、填写的服务器地址是否可以访问
(2)、token是否对应
6、服务器配置只需一次,配置成功后,可将 $wechatObj->valid(); 注释,放开 $wechatObj->responseMsg();
? ? ? ? 此方法可实现自动回复功能。
|