123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 |
- <?php
- namespace app\admin\controller;
- use app\admin\service\ExclusiveService;
- use app\common\constants\BigData;
- use app\common\controller\Backend;
- use app\common\library\WeChatObject;
- use app\main\constants\TemplateMsgConstants;
- use app\main\service\TemplateService;
- use app\main\service\UrlService;
- use app\main\service\VisitLimitService;
- use EasyWeChat\Factory;
- use EasyWeChat\OfficialAccount\TemplateMessage\Client;
- use think\Config;
- use app\common\library\Redis;
- use Symfony\Component\Cache\Simple\RedisCache;
- use app\main\constants\AdminConstants;
- /**
- * 模板消息
- *
- * @icon fa fa-circle-o
- */
- class Templatemessage extends Backend
- {
- /**
- * Templatemessage模型对象
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->model = model('Templatemessage');
- $this->view->assign("statueList", $this->model->getStatueList());
- $this->assign('admin_id', $this->auth->id);
- $this->assignconfig('admin_id', $this->auth->id);
- }
- public function index()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags']);
- $this->assignconfig('nowtime',time());
- if ($this->request->isAjax()) {
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $total = $this->model
- ->join('template_collect', 'templatemessage.id = template_collect.templetemessage_id', 'left')
- ->field('templatemessage.*, template_collect.pv, template_collect.uv, template_collect.recharge_orders, template_collect.recharge_money')
- ->where($where)
- ->where('admin_id','in',$this->auth->id)
- ->order('templatemessage.'.$sort, $order)
- ->count();
- $list = $this->model
- ->join('template_collect', 'templatemessage.id = template_collect.templetemessage_id', 'left')
- ->field('templatemessage.*, template_collect.pv, template_collect.uv, template_collect.recharge_orders, template_collect.recharge_money')
- ->where($where)
- ->where('admin_id','in',$this->auth->id)
- ->order('templatemessage.'.$sort, $order)
- ->limit($offset, $limit)
- ->select();
- if (VisitLimitService::instance()->checkMigrated()) {
- $ids = array_column($list, 'id');
- $collectList = TemplateService::instance()->getMigratedCollectAnalysis($ids)->data;
- foreach ($list as $index => $item) {
- if (array_key_exists($item['id'], $collectList)) {
- $list[$index]['uv'] = $collectList[$item['id']]['uv'];
- $list[$index]['recharge_money'] = $collectList[$item['id']]['recharge_money'];
- $list[$index]['day_uv'] = $collectList[$item['id']]['day_uv'];
- $list[$index]['day_money'] = $collectList[$item['id']]['day_recharge_money'];
- } else {
- $list[$index]['uv'] = 0;
- $list[$index]['recharge_money'] = 0;
- $list[$index]['day_uv'] = 0;
- $list[$index]['day_money'] = 0;
- }
- }
- } else {
- $redis = Redis::instance();
- foreach($list as $item){
- $item['day_uv'] = intval($redis->get(TemplateMsgConstants::getTemplateUvToDayKey($item['id'])));
- $item['day_money'] = floatval($redis->get(TemplateMsgConstants::getTemplateRechargeMoneyToDayKey($item['id'])));
- if(empty($item['recharge_money'])){
- $item['recharge_money'] = '0.00';
- }
- if(empty($item['day_money'])){
- $item['day_money'] = '0.00';
- }
- }
- }
- $result = array("total" => $total, "rows" => $list);
- return json($result);
- }
- return $this->view->fetch();
- }
- //测试发送模板消息
- public function sent()
- {
- // refresh_token adminConfig表获取
- $admin_id = $this->auth->id;
- $user_id = $_POST['user_id'];
- if (preg_match("/\d+/i", $user_id, $matches)) {
- if(!empty($matches)){
- if(empty($matches)){
- //没有匹配到数字。错误
- return json(['errcode' => 1, 'errmsg' => '无法匹配到此用户']);
- }else{
- $user_id = intval($matches[0]);
- }
- }
- } else {
- //没有匹配到数组,错误
- return json(['errcode' => 1, 'errmsg' => '无法匹配到此用户']);
- }
- $user = model('User')->setConnect($user_id)->where('id', $user_id)->find();
- if (!$user) {
- return json(['errcode' => 1, 'errmsg' => '无此用户']);
- }
- $openid = $user->openid;
- $Config = model('AdminConfig')->getAdminInfoAll($admin_id); //where('admin_id', '=', $admin_id)->find();
- $wechat = new WeChatObject($Config);
- $officialAccount = $wechat->getOfficialAccount();
- $user_nickname = $user->nickname;
- $user_id = $user->id;
- $user_vip_endtime = $user->vip_endtime;
- $df_config = $Config;
- $wx_nickname = $df_config['json']['authorizer_info']['nick_name'] ?: $df_config['json']['authorizer_info']['user_name'];
- $book_name = '';
- $redis = Redis::instance();
- $key = 'U-R:'.$user_id;
- if($redis->exists($key)){
- $readkey = $redis->zrevrange($key,0,1);
- $book_name = $redis->hget($readkey[0],'chapter_name');
- }
- $message = json_decode($_POST['message_html'],true);
- $message_json['touser'] = '{$openid}';
- $message_json['template_id'] = $_POST['template_id'];
- $message_json['url'] = trim($_POST['url']);
- $message_json['data'] = [];
- foreach ($message as $v){
- foreach ($v as $value){
- if((preg_match ("/^[a-z]/i", $value['key'])) && !empty($value['fieldname'])){
- $value['fieldname'] = stripslashes($value['fieldname']);
- $value['fieldname'] = preg_replace("/\">(.*?)<\/strong>/",'',$value['fieldname']);
- $value['fieldname'] = str_replace('</strong>','',$value['fieldname']);
- $value['fieldname'] = str_replace('">','',$value['fieldname']);
- $value['fieldname'] = str_replace(' ','',$value['fieldname']);
- $value['fieldname'] = str_replace('<strong contenteditable="false" data-key="','',$value['fieldname']);
- $value['fieldname'] = str_replace('$user_nickname',$user_nickname,$value['fieldname']);
- $value['fieldname'] = str_replace('$user_id',$user_id,$value['fieldname']);
- if(!empty($user_vip_endtime)){$value['fieldname'] = str_replace('$user_vip_endtime',$user_vip_endtime,$value['fieldname']);}else{
- $value['fieldname'] = str_replace('$user_vip_endtime','',$value['fieldname']);
- }
- $value['fieldname'] = str_replace('$wx_nickname',$wx_nickname,$value['fieldname']);
- $value['fieldname'] = str_replace('$book_name',$book_name,$value['fieldname']);
- $message_json['data'][$value['key']] = ['color'=>$value['color'],'value'=>$value['fieldname']];
- }
- }
- }
- $message_json['touser']= $openid;
- $send_res = $officialAccount->template_message->send($message_json);
- if($send_res['errcode'] == 40037){
- $send_res['errmsg'] = '模板ID无效,请到公众号后台检查该模板是否存在';
- }
- return json($send_res);
- }
- /*
- * 创建新模板
- */
- // public function WeChatTemplate()
- // {
- // $openPlatform = Factory::openPlatform(Config::get('wechat'));
- // $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
- // $Config = model('AdminConfig')->where('admin_id', '=', $this->auth->id)->find();
- // $officialAccount = $openPlatform->officialAccount($Config->appid, $Config->refresh_token);
- // $getIndustry = $officialAccount->template_message->getIndustry();
- // $getIndustry = array_values($getIndustry);
- //
- // if (empty($getIndustry[0]['first_class']) && empty($getIndustry[1]['first_class'])) {
- // $officialAccount->template_message->setIndustry(37, 2);
- // $officialAccount->template_message->addTemplate('TM00009');
- // $officialAccount->template_message->addTemplate('TM405959619');
- // }
- //
- // $this->getTemplate();
- // }
- /*
- *获取远程模板
- */
- public function getTemplate()
- {
- $Config = model('AdminConfig')->getAdminInfoAll($this->auth->id);
- $wechat = new WeChatObject($Config);
- $officialAccount = $wechat->getOfficialAccount();
- $tmps = $officialAccount->template_message->getPrivateTemplates();
- model('templatelist')->where(array('admin_id' => $this->auth->id))->delete();
- if (!empty($tmps['template_list'])) {
- foreach ($tmps['template_list'] as &$value) {
- $value['admin_id'] = $this->auth->id;
- }
- if (model('templatelist')->saveall($tmps['template_list'])) {
- return $tmps['template_list'];
- }
- }
- }
- //
- public function add()
- {
- if ($this->request->isPost()) {
- $row = $this->request->post('row/a');
- if(isset($row['sub_from'])){
- unset($row['sub_from']);
- }
- if(isset($row['sub_to'])){
- unset($row['sub_to']);
- }
- if (strtotime($row['sendtime']) < time()) {
- $this->error('发送时间不能小于当前时间');
- }
- unset($row['type']);
- $url = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $row['url'])->data;
- $row['url'] = trim($url);
- $tmp_row = $row;
- $row['message_json'] = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $this->message_json($row))->data;
- // $this->error(json_encode($row,JSON_UNESCAPED_UNICODE));
- if ($row) {
- $templatemessage = new \app\admin\model\Templatemessage();
- $templatemessage->save($row);
- $id = $templatemessage->id;
- $tmp_row['url'] = $this->_appendUrlExt($url, BigData::BIG_DATA_TEMPLATE_MSG, strtotime($row['sendtime']), $id);
- $tmp_row['message_json'] = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $this->message_json($tmp_row))->data;
- $this->model->update(
- [
- 'url' => $tmp_row['url'],
- 'message_json' => $tmp_row['message_json'],
- ],
- ['id' => $id]
- );
- $this->success();
- }
- $this->error();
- }
- return $this->view->fetch();
- }
- /**
- * 追加打点信息到URL
- * @param $url
- * @param $mark
- * @param $sendTime
- * @param $push_id
- * @return string
- */
- private function _appendUrlExt($url, $mark, $sendTime, $push_id)
- {
- $url = trim($url);
- $ext = [
- 'mark' => $mark,
- 'push_time' => $sendTime,
- 'push_id' => $push_id,
- ];
- $strExt = json_encode($ext);
- if (strpos($url, '?') === false) {
- $url .= '?ext=' . $strExt;
- } else {
- $url .= '&ext=' . $strExt;
- }
- return $url;
- }
- /*
- * 模板列表
- * @param w=1 远程获取模板
- */
- public function ajaxtmp()
- {
- $tmps = [];
- if(intval(input('w'))){
- $tmps = $this->getTemplate();
- }
- if(empty($tmps)){
- $tmps = model('templatelist')->field('id,template_id,title,content')->where(array('admin_id' => $this->auth->id))->select();
- }
- if (empty($tmps)) {
- return json(['error' => -1, 'msg' => '模板数据未创建,请点击刷新模板列表']);
- }
- foreach ($tmps as &$value) {
- $value['content'] = str_replace('{', '#', $value['content']);
- $value['content'] = str_replace('}', '#', $value['content']);
- $value['content'] = str_replace('.DATA', '', $value['content']);
- $value['content'] = str_replace(':', '#', $value['content']);
- $value['content'] = str_replace('##', '#', $value['content']);
- $contentArr = explode('<br />',nl2br($value['content']));
- $fieldListArr = [];
- foreach ($contentArr as $k =>$text) {
- $text = trim($text);
- if (strlen($text) > 0) {
- $keywordArr = explode('#',$text);
- foreach ($keywordArr as $key =>$keywordArrValue){
- $keywordArrValue = trim($keywordArrValue);
- $field = [];
- if (strlen(trim($keywordArrValue)) > 0) {
- if(preg_match ("/^[a-z]/i", $keywordArrValue)){
- $field['fieldname'] = '';
- $field['key'] = $keywordArrValue;
- $field['color'] = '#000000';
- }else{
- $field['fieldname'] = $keywordArrValue.':';
- $field['key'] = $keywordArrValue. ':';
- $field['color'] = '';
- }
- $keywordArr[$key]= $field;
- }else{
- unset($keywordArr[$key]);
- }
- }
- $fieldListArr[] = array_values($keywordArr);
- }
- }
- $value['content'] = array_values($fieldListArr);
- }
- $return['error'] = 0;
- $return['msg'] = '请求成功.';
- $return['data'] = $tmps;
- return json_encode($return, JSON_UNESCAPED_UNICODE);
- }
- public function edit($ids=null){
- $canEdit = 0;
- $row = $this->model->get($ids);
- if (!$row)
- $this->error(__('No Results were found'));
- if($row['sendtime'] <= time()){
- $canEdit = 1;
- }
- if($row['sendtime'] > time() && $row['sendtime']-time() <= 600){
- $canEdit = 1;
- }
- //解析占位符
- $row['message_json'] = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $row['message_json'], false)->data;
- $row['url'] = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $row['url'], false)->data;
- if ($this->request->isAjax())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- unset($row['type']);
- if(isset($params['sub_from'])){
- unset($params['sub_from']);
- }
- if(isset($params['sub_to'])){
- unset($params['sub_to']);
- }
- $params['url'] = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $params['url'])->data;
- $params['url'] = trim($this->_appendUrlExt($params['url'], BigData::BIG_DATA_TEMPLATE_MSG, $row['sendtime'], $ids));
- $params['message_json'] = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $this->message_json($params))->data;
- try
- {
- //是否采用模型验证
- if ($this->modelValidate)
- {
- $name = basename(str_replace('\\', '/', get_class($this->model)));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
- $row->validate($validate);
- }
- $result = $row->allowField(true)->save($params);
- if ($result !== false)
- {
- $this->success();
- }
- else
- {
- $this->error($row->getError());
- }
- }
- catch (\think\exception\PDOException $e)
- {
- $this->error($e->getMessage());
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $row['sendtime'] = date('Y-m-d H:i:s',$row['sendtime']);
- //获取独家书籍id
- $bnotin= [];
- ExclusiveService::instance()->getExclusiveNotidsWithoutWhere($this->group, $this->auth->id,$bnotin);
- $this->assignconfig('bnotin', $bnotin);
- $this->assign("canedit",$canEdit);
- $json = json_decode($row['user_json'], true);
- $from = $to = '';
- if ($json['all'] == 0 && !$json['subscribe_time'] && $json['subscribe_range']) {
- list($from, $to) = explode('-', $json['subscribe_range']);
- if($from == 'NaN'){
- $from = '';
- }
- if($to == 'NaN'){
- $to = '';
- }
- if($from){
- $from = date('Y-m-d H:i:s', $from);
- }
- if($to){
- $to = date('Y-m-d H:i:s', $to);
- }
- }
- $this->view->assign('from', $from);
- $this->view->assign('to', $to);
- $this->view->assign("row", $row);
- return $this->view->fetch();
- }
- /*
- * 处理message_json返回的数据
- */
- public function message_json($row){
- $message = json_decode($row['message_html'],true);
- $message_json['touser'] = '{$openid}';
- $message_json['template_id'] = $row['template_id'];
- $message_json['url'] = trim($row['url']);
- $message_json['data'] = [];
- foreach ($message as $v){
- foreach ($v as $value){
- if((preg_match ("/^[a-z]/i", $value['key'])) && !empty($value['fieldname'])){
- $value['fieldname'] = stripslashes($value['fieldname']);
- $value['fieldname'] = preg_replace("/\">(.*?)<\/strong>/",'',$value['fieldname']);
- $value['fieldname'] = str_replace('</strong>','',$value['fieldname']);
- $value['fieldname'] = str_replace('">','',$value['fieldname']);
- $value['fieldname'] = str_replace(' ','',$value['fieldname']);
- $value['fieldname'] = str_replace('<strong contenteditable="false" data-key="','',$value['fieldname']);
- $message_json['data'][$value['key']] = ['color'=>$value['color'],'value'=>$value['fieldname']];
- }
- }
- }
- return json_encode($message_json);
- }
- }
|