用户在关注与取消关注公众号时,微信会把这个事件推送到开发者填写的URL,方便开发者给用户下发欢迎消息或者做帐号的解绑.
下面是一个微信公众平台关注和取消关注的实例,代码如下:
-
define("TOKEN", "w3note");
-
$wechatObj = new 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(取消订阅)
(责任编辑:最模板) |