通过微信二次开发可以将公众账号由一个媒体型营销工具转化成提供服务的产品。而一旦成为用户需要的产品,公众账号的营销功能便会开启。
首先设置里token需要与上传服务器里的token相同,验证身份。
下面是自动回复的代码示例
public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//接受微信想公众号发送的消息
//extract post data
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if(!empty( $keyword )) {
$msgType = "text";
$contentStr=$this->huifu($keyword);
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
下面是回复关键字后自动回复的功能
public function huifu($keyword){
if ($keyword == "天气") {
$contentStr= "阴天";
return $contentStr;
}else if ($keyword == "放假") {
$contentStr= "周四、五、六放假";
return $contentStr;
}else{
$contentStr= "无可奉告";
return $contentStr;
}
}
然后再上方自动回复代码中调用即可
下面是验证是否是通过腾讯方式发送
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
这些是刚刚学习的微信二次开发