1.首先登录微信公众号-〉开发者工具-〉公众平台测试账号,里面的TOKEN 必须与文件中自己定义的TOKEN保持一致才能配置成功
2. 验证请求是否来自微信服务器
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;
}
}
3. 向公众号发送消息验证是否回复
代码如下
if(!empty($keyword))
{
$msgType = "text";
$contentStr = $this->word($keyword);
// $contentStr ="we come";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
// 关键字
public function word($keyword){
if($keyword === '天气'){
return $contentStr ="今天天气有雨!";
}else if($keyword === '你好'){
return $contentStr ="你好!有什么需要帮助?";
}else{
return $contentStr ="sorry,I can not help you。";
}
4.其中起着重要作用的代码如下
define("TOKEN", "weixin");
$echoStr = $_GET["echostr"];
echo $echoStr;