一首先手动创建php文件,然后在微信公众平台服务器配置指定执行这个文件,那么每次微信公众号发消息就会执行这个文件,我们
可以在这个文件中指定菜单点击事件和消息内容处理、设置自动回复规则等。具体见下面php:
<?php
/*** wechat php test
*/
//define your token
define("TOKEN", "oliveche_test");
require_once("../api.php");
require_once "lib/jssdk.php";
$GLOBALS["CurWeixinMch"] = 2; // Weixin Mch for JSAPI
require_once(dirname(__FILE__) . "/WxPayPubHelper/WxPay.pub.config.php");
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
$flage = false;
}else{
$wechatObj->valid();
}
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
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)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
switch ($RX_TYPE)
{
case "text":
if($postObj->Content =='哈哈'){
$resultStr = $this->receiveText($postObj);
$flage = true;
}
break;
case "event":
$resultStr = $this->receiveEvent($postObj);
break;
default:
$resultStr = "";
break;
}
echo $resultStr;
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = date('c');
if(!empty( $keyword ) && !$flage)
{
$msgType = $RX_TYPE;
$wxuserId = queryOne("SELECT id from WeixinUser where openId = '{$fromUsername}'");
if($wxuserId == false){
$jssdk = new JSSDK($GLOBALS["WxPayConfig"]["APPID"], $GLOBALS["WxPayConfig"]["APPSECRET"], false);
$access_token = $jssdk->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$fromUsername}&lang=zh_CN";
$ret = file_get_contents($url);
$obj = json_decode($ret);
$sql = "INSERT INTO WeixinUser (openId, nickName, data, wxPicId) VALUES ('$obj->openid', '$obj->nickname', '$ret', '$obj->headimgurl')";
$wxuserId = execOne($sql,true);
}
$sql = "INSERT INTO WxMsg (wxUserId, fromUsername, toUsername, tm, msgType, keyword) VALUES ('$wxuserId','$fromUsername', '$toUsername', '$time', '$msgType', '$keyword')";
execOne($sql);
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
private function receiveText($object)
{
$funcFlag = 0;
$contentStr = "你好聪明";
$resultStr = $this->transmitText($object, $contentStr, $funcFlag);
return $resultStr;
}
private function checkSignature()
{
// you must define TOKEN by yourself
if (!defined("TOKEN")) {
throw new Exception('TOKEN is not defined!');
}
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
private function receiveEvent($object)
{
$contentStr = "";
switch ($object->Event)
{
case "subscribe":
$contentStr = "欢迎关注展达";
case "unsubscribe":
break;
case "CLICK":
switch ($object->EventKey)
{
case "hh":
$contentStr[] = array("Title" =>"公司简介",
"Description" =>"展达提供移动互联网相关的产品及服务",
"PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg",
"Url" =>"weixin://addfriend/pondbaystudio");
break;
case "key_aboutUs":
$contentStr = "联系我们 联系邮件:yanfengzhen@oliveche.com 联系电话: 闫小姐-18501781812 施先生-15800793345 联系QQ:819434914, 313620166";
break;
default:
$contentStr[] = array("Title" =>"征途是星辰大海",
"Description" =>"我们为汽车行业内的客户,提供移动互联网的基础平台服务,帮助汽车4S店以及连锁维修店提供提高运营能力,促进销售的产品和服务。我们坚信技术是引领社会与行业进步的基石!",
"PicUrl" =>"https://mmbiz.qlogo.cn/mmbiz_jpg/FFbjf6Gx2npWcvvNfUIqoD9bEic4tzPHZt5icdt1kFk0ILVkIFgwvSbVhJChM81wZCwOyxcMCBKT70w0cJKHeIzw/0?wx_fmt=jpeg",
"Url" =>"http://mp.weixin.qq.com/s?__biz=MzIzNDE5MjA1Mg==&mid=2649550179&idx=1&sn=5ba842e75130bc8a525048164d05c8c8&chksm=f0e260b8c795e9aedc90d84ced0ccc3fb084b723662189af7eaa0c8a9ed8994b9712d0a28038&mpshare=1&scene=1&srcid=1013JSjF5BIExKh5SxpEw6jc&from=singlemessage&isappinstalled=0#wechat_redirect");
break;
}
break;
default:
break;
}
if (is_array($contentStr)){
$resultStr = $this->transmitNews($object, $contentStr);
}else{
$resultStr = $this->transmitText($object, $contentStr);
}
return $resultStr;
}
private function transmitText($object, $content, $funcFlag = 0)
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
$resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $funcFlag);
return $resultStr;
}
private function transmitNews($object, $arr_item, $funcFlag = 0)
{
//首条标题28字,其他标题39字
if(!is_array($arr_item))
return;
$itemTpl = " <item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
";
$item_str = "";
foreach ($arr_item as $item)
$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";
$resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $funcFlag);
return $resultStr;
}
}
?>