接收事件推送—关注/取消事件
**说明:
修改配置保存时需要验证服务器端填写的token,所以要先写好服务器端的逻辑才能验证成功**
三、控制器IndexController.class.php代码如下
**说明:我在直接访问的是服务器端
http://www.xxx.xxx/weixin.php(thinkphp下的Weixin模块的默认控制器里的默认方法,也就是你在上面启动开发者模式里面的服务器地址)**
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();
a
r
r
a
y
=
a
r
r
a
y
(
array = array(
array=array(nonce, $timestamp,
t
o
k
e
n
)
;
s
o
r
t
(
token); sort(
token);sort(array);
//拼接成字符串,sha1加密 ,然后与signature进行校验
$str = sha1( implode( $array ) );
if( $str == $signature && $echostr ){
//第一次接入weixin api接口的时候
echo $echostr;
exit;
}else{
KaTeX parse error: Expected 'EOF', got '}' at position 29: …Msg(); }̲ } // 接…postArr = $GLOBALS[‘HTTP_RAW_POST_DATA’];//php7以上不能用
$postArr = file_get_contents(“php://input”);
//2.处理消息类型,并设置回复类型和内容
$postObj = simplexml_load_string(
p
o
s
t
A
r
r
)
;
/
/
postArr ); //
postArr);//postObj->ToUserName = ‘’;
//
p
o
s
t
O
b
j
−
>
F
r
o
m
U
s
e
r
N
a
m
e
=
′
′
;
/
/
postObj->FromUserName = ''; //
postObj−>FromUserName=′′;//postObj->CreateTime = ‘’;
//
p
o
s
t
O
b
j
−
>
M
s
g
T
y
p
e
=
′
′
;
/
/
postObj->MsgType = ''; //
postObj−>MsgType=′′;//postObj->Event = ‘’;
// gh_e79a177814ed
//判断该数据包是否是订阅的事件推送
if( strtolower( KaTeX parse error: Expected '}', got 'EOF' at end of input: …if( strtolower(postObj->Event == ‘subscribe’) ){
//回复用户消息(纯文本格式)
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time = time();
m
s
g
T
y
p
e
=
′
t
e
x
t
′
;
/
/
msgType = 'text'; //
msgType=′text′;//content = ‘欢迎关注我们的微信公众账号’.
p
o
s
t
O
b
j
−
>
F
r
o
m
U
s
e
r
N
a
m
e
.
′
−
′
.
postObj->FromUserName.'-'.
postObj−>FromUserName.′−′.postObj->ToUserName;
$content = ‘欢迎关注放哥的微信公众账号’;
$template = "
<![CDATA[%s]]>
<![CDATA[%s]]>
%s
<![CDATA[%s]]>
<![CDATA[%s]]>
";
i
n
f
o
=
s
p
r
i
n
t
f
(
info = sprintf(
info=sprintf(template, $toUser, $fromUser, $time, $msgType, $content);
echo $info;
}
}
}//reponseMsg end
}//class end
四、补充说明
php7版本以上不支持
$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
- 1
的使用,改成:
$postArr = file_get_contents("php://input");
- 1
php7版本以下需要使用需要开启php.ini配置文件里面的:
always_populate_raw_post_data = On
- 1
参考博客:https://blog.csdn.net/hpugym/article/details/54969457
https://blog.csdn.net/John_rush/article/details/80610025