本文实例讲述了微信公众平台开发关注及取消关注事件的方法。分享给大家供大家参考。具体分析如下:
用户在关注与取消关注公众号时,微信会把这个事件推送到开发者填写的url,方便开发者给用户下发欢迎消息或者做帐号的解绑.
下面是一个微信公众平台关注和取消关注的实例,代码如下:
define("token", "w3note");//定义识别码
$wechatobj = new wechatcallbackapitest();//实例化wechatcallbackapitest类
if(!isset($_get["echostr"])){
$wechatobj->responsemsg();
}else{
$wechatobj->valid();
}
class wechatcallbackapitest
{
public function valid()
{
$echostr = $_get["echostr"];
if($this->checksignature()){
echo $echostr;
exit;
}
}
public function responsemsg()//执行接收器方法
{
$poststr = $globals["http_raw_post_data"];
if (!emptyempty($poststr)){
$postobj = simplexml_load_string($poststr, 'simplexmlelement', libxml_nocdata);
$rx_type = trim($postobj->msgtype);
switch($rx_type){
case "event":
$result = $this->receiveevent($postobj);
breadk;
}
echo $result;
}else{
echo "";
exit;
}
}
private function receiveevent($object){
$content = "";
switch ($postobj->event){
case "subscribe":
$content = "欢迎关注网志博客";//这里是向关注者发送的提示信息
break;
case "unsubscribe":
$content = "";
break;
}
$result = $this->transmittext($object,$content);
return $result;
}
private function transmittext($object,$content){
$texttpl = "<xml>
<tousername><![cdata[%s]]></tousername>
<fromusername><![cdata[%s]]></fromusername>
<createtime>%s</createtime>
<msgtype><![cdata[text]]></msgtype>
<content><![cdata[%s]]></content>
<funcflag>0</funcflag>
</xml>";
$result = sprintf($texttpl, $object->fromusername, $object->$tousername, time(), $content);
return $result;
}
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;
}
}
}
代码相关参数说明:
参数 |
描述 |
tousername |
开发者微信号 |
fromusername |
发送方帐号(一个openid) |
createtime |
消息创建时间 (整型) |
msgtype |
消息类型,event |
event |
事件类型,subscribe(订阅)、unsubscribe(取消订阅) |
希望本文所述对大家的php程序设计有所帮助。
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
-
-
-
-
-
-
管理后台无限级菜单
管理后台菜单遍历很久就想做一个通用的管理后台出来,一直太懒没做,今天开始粗略搞了一下,只是先把框架搭建好,菜单栏...
[阅读全文]
-
桥接模式学习总结
桥接模式引言假如一个系统需要加入报表模块,主要的开发点是数据的获取和报表的显示方式。数据的获取可能是从系统数据库...
[阅读全文]
-
网友评论