随着网上商城的流行,微信商城借助微信这一超级流量入口,成为电商企业的标配。微信商城中的自动回复是一种提升商城体验的方式,如何实现文本消息自动回复及系统关注自动回复,本文安菲云将以实际代码给大家分享。
首先,我们需要设计数据库表,将自动回复的消息类型和内容、触发回复的关键字等预设好模板,我们按照如下设计好数据库:
我们以安菲多用户商城的微信商城代码为例:
消息自动回复:
/*************** 被动回复消息 ****************/
public function _doText($postObj)
{
$time = time();
$msgType = "text";
$keyword =
trim($postObj->Content);// 用户发送过来的关键字
$keyword = "$keyword";
$m = Db::name('wx_passive_replys');
$msgType =
$m->where([['keyword','=',$keyword]])->value('msgType');
if($msgType=='text'){
$contentStr =
$m->where([['keyword','=',$keyword],['dataFlag','=',1]])->value('content');
$resultStr = sprintf($this->tpl['text'],
$postObj->FromUserName, $postObj->ToUserName, $time, $contentStr);
echo $resultStr;
}elseif($msgType=='news'){
// 图文消息最多发送10条
$news =
$m->field('title,description,picurl,url')->where([['keyword','=',$keyword],['dataFlag','=',1]])->limit(10)->select();
$count = count($news);
$newC='';
for($i=0;$i<$count;++$i){
$newC .=
sprintf($this->tpl['content'], $news[$i]['title'], $news[$i]['description'],
WSTConf('CONF.resourcePath').'/'.$news[$i]['picurl'], $news[$i]['url']);
}
//将内容输出到新闻模板
$news =
sprintf($this->tpl['news'], $postObj->FromUserName,
$postObj->ToUserName, $time, $count, $newC);
echo $news;
}
exit;
}
系统关注自动回复:
/**
* 关注回复事件第一条用关注事件推送,之后的用客服消息推送
*/
public function
subscribeEvent($postObj){
$m = Db::name('wx_passive_replys');
$subscribes =
$m->where([['dataFlag','=',1],['isSubscribe','=',1]])->order('subscribeSort
asc,id desc')->limit(10)->select();
$userOpenId = (string)$postObj->FromUserName;
foreach ($subscribes as $key => $v) {
if($key==0){
$resultStr = '';
switch ($v['msgType']) {
case 'text':$resultStr
= sprintf($this->tpl['text'], $postObj->FromUserName, $postObj->ToUserName,
time(), $v['content'], 0);
break;
case 'news':$newC =
sprintf($this->tpl['content'], $v['title'], $v['description'],
WSTConf('CONF.resourcePath').'/'.$v['picUrl'], $v['url']);
$resultStr =
sprintf($this->tpl['news'], $postObj->FromUserName,
$postObj->ToUserName, time(), 1, $newC);
break;
}
echo $resultStr;
}else{
$sendData = [];
$sendData['touser'] = $userOpenId;
switch ($v['msgType']) {
case
'text':$sendData['msgtype'] = 'text';
$sendData['text'] = ['content'=>urlencode($v['content'])];
break;
case 'news':$sendData['msgtype'] =
'news';
$sendData['news'] = ['articles'=>[[
'title'=>urlencode($v['title']),
'description'=>urlencode($v['description']),
'url'=>$v['url'],
'picurl'=>WSTConf('CONF.resourcePath').'/'.$v['picUrl']
]]
];
break;
}
$this->sendCustomMessage(urldecode(json_encode($sendData)));
}
}
}