求助,关注后没有消息推送?发文本后发出“该公众号提供的服务出现故障,请稍后再试”
代码如下,应该跟视频差不多,不清楚,看了挺多解释也不是很明白
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
public function index(){
//获得参数 signature nonce token timestamp echostr
$nonce = $_GET['nonce'];
$token = 'imooc';
$timestamp = $_GET['timestamp'];
$echostr = $_GET['echostr'];
$signature = $_GET['signature'];
//形成数组,然后按字典序排序
$array = array($nonce, $timestamp, $token);
sort($array);
//拼接成字符串,sha1加密 ,然后与signature进行校验
$str = sha1( implode( $array ) );
if( $str == $signature && $echostr ){
//第一次接入weixin api接口的时候
echo $echostr;
exit;
}else{
$this->responseMsg();
}
}
// 接收事件推送并回复(关注/取消关注)
public function responseMsg(){
//1.获取到微信推送过来post数据(xml格式)
$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
//2.处理消息类型,并设置回复类型和内容
//<xml>
//<ToUserName><![CDATA[toUser]]></ToUserName>
//<FromUserName><![CDATA[FromUser]]></FromUserName>
//<CreateTime>123456789</CreateTime>
//<MsgType><![CDATA[event]]></MsgType>
//<Event><![CDATA[subscribe]]></Event>
//</xml>
$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 = '欢迎关注我们的微信公众账号'.$postObj->FromoUserName.'----'.$postObj->ToUserName;
$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;
}
}
//<xml>
//<ToUserName><![CDATA[toUser]]></ToUserName>
//<FromUserName><![CDATA[fromUser]]></FromUserName>
//<CreateTime>1348831860</CreateTime>
//<MsgType><![CDATA[text]]></MsgType>
//<Content><![CDATA[this is a test]]></Content>
//<MsgId>1234567890123456</MsgId>
//</xml>
//判断该数据包是否是用户发送的信息
if( strtolower( $postObj->MsgType) == 'text'){
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time = time();
$msgType = 'text';
$content = 'wait';
$msgId = $postObj->MsgId;
$template = "<xml>
<ToUserName><![CDATA[%s] ]></ToUserName>
<FromUserName><![CDATA[%s] ]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s] ]></MsgType>
<Content><![CDATA[%s] ]></Content>
<MsgId>%s</MsgId>
</xml>";
$info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content, $msgId);
echo $info;
}
}
}