问答详情
源自:3-1 接收事件订阅与回复响应消息(一)

订阅号关注后没有推送事件, 除了检查代码还需要检查哪里?

 <?php
namespace app\wechat\controller;

class Index
{
    public function index(){
//1)将token、timestamp、nonce三个参数进行字典序排序 
$token    = 'weixin';
$timestamp = $_GET['timestamp'];
$nonce     = $_GET['nonce'];
$signature = $_GET['signature'];
$echostr   = $_GET['echostr'];
//2)将三个参数字符串拼接成一个字符串进行sha1加密 
$array = array($token, $timestamp, $nonce);
sort($array);
$str = sha1(implode('', $array));
//3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
if($str == $signature && $echostr){
//第一次接入微信api接口的时候
echo $echostr;
exit;
}else{
$this->reponseMsg();
}
}
public function reponseMsg(){
$postArr = file_get_contents("php://input");
$postObj = simplexml_load_string($postArr);
//判断数据包是否是订阅号推送
if(strtolower($postObj->MsgType) == 'event'){
//如果关注 subscribe 事件
if(strtolower($postObj->Event) == 'subscribe'){
//回复用户消息
$toUser   = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time     = time();
$msgType  = 'text';
$content  = '欢迎关注本聪的测试公众号';
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
echo $info;
}
}
}
}


提问者:糖油饼 2018-12-11 14:12

个回答