define("TOKEN", config("wx_token"));
$wechatObj = new Wxapi();
if (isset($_GET['echostr'])) {
$wechatObj->valid();
}else{
$wechatObj->responseMsg();
}
class Wxapi
{
/**
* 微信公众号验证
*/
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
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;
}
}
public function responseMsg()
{
//$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
$postArr = file_get_contents('php://input');
//2.处理消息类型,并设置回复类型和内容
$postObj = simplexml_load_string( $postArr );
//判断该数据包是否是订阅的事件推送
if(strtolower( $postObj->MsgType) == 'event'){
//如果是关注 subscribe 事件
// 超链接里边指定data-miniprogram-path跳转小程序某个页面
if( strtolower($postObj->Event == 'subscribe') ) {
Log::info("有人关注");
Log::info("1");
//回复用户消息(纯文本格式)
$fromUsername = $postObj->FromUserName; //请求消息的用户
$toUsername = $postObj->ToUserName; //"我"的公众号id
$keyword = trim($postObj->Content); //消息内容
$time = time(); //时间戳
$msgtype = 'text'; //消息类型:文本
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
if(strtolower($postObj->MsgType == 'event' )){ //如果XML信息里消息类型为event
if($postObj->Event == 'subscribe'){ //如果是订阅事件
$contentStrq = $content = '欢迎关注';
$resultStrq = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStrq);
echo $resultStrq;
exit();//一定要加!!!!不加程序运转正常就是不回复消息
}
}
}
}
}
}