微信公众号文档
文档中验证消息来自微信服务器,按照文档来写
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;
}
}
微信文档已说明,【按照原样返回echostr参数】,所以例子中return true会一直接入失败,这里改为
return $_GET["echostr"];或者echo $_GET["echostr"];exit;
laravel 关注/取消微信公众号事件需要注意的是路由
Route::match(['get','post'], 'api/index', 'ApiController@checkSignature');
微信公众号事件也是回调这个方法,只是用POST方式请求
// 验证来自微信服务器
private function checkSignature(Request $request)
{
// 验证消息来自微信服务器
if($request->method()=='GET'){
$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 && $_GET['echostr']){
echo $_GET['echostr'];
exit;
}else{
return false;
}
} elseif ($request->method()=='POST') {
// 事件处理 关注/取消事件等
$postArr = file_get_contents("php://input");
//获取到xml数据后,处理消息类型,并设置回复消息内容(回复就是直接打印xml数据)
//数据格式
$arr = simplexml_load_string($postArr);
if(strtolower($arr->MsgType)=="event")
{
$toUser = $arr->ToUserName;
$foUser = $arr->FromUserName; // 用户openid
$msgType = 'text';
$createTime = time();
$content = '欢迎关注我的微信公众平台';
if(strtolower($arr->Event)=="subscribe") {//订阅
$temp = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
echo $temp;
}elseif (strtolower($arr->Event)=="unsubscribe"){ // 取消订阅
echo '';
}
}
}
}