本文实例讲述了微信公众平台开发关注及取消关注事件的方法。分享给大家供大家参考。具体分析如下:
用户在关注与取消关注公众号时,微信会把这个事件推送到开发者填写的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 =
%s
0
;
$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程序设计有所帮助。