Template.php 2.6 KB
<?php

namespace app\api\controller\notify;

use app\common\controller\Api;
use think\Db;
use think\exception\PDOException;

/**
 * 
 */
class Template extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    
    public function _initialize()
    {
        parent::_initialize(); 
        $this->model =  new \app\admin\model\reservoir\Template;
    }
    
    public function list()
    {
        $page = $this->request->param('page',1);
        $limit = $this->request->param('limit',10);
        $total = $this->model::count();
        $list = $this->model
            ->page($page,$limit)
            ->select();
        $data = [
            'page' => $page,
            'total'=> $total,
            'data' => $list 
        ];
        $this->success('',$data);
    }
    public function sendmsg($ids=null)
    {
        $msg = $this->model->get($ids);
        $wechat = Db::name('weixin_template')->where('tempid',$msg->code)->find();
        if (!$wechat) {
            $this->error('模板不存在');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $openid = Db::name('user')->where('id',$params['user_id'])->value('openid');
                if(!$openid){
                    $this->error('用户未绑定微信');
                }
                unset($params['user_id']);
                $res = \addons\weixin\library\WechatTemplateService::sendTemplate($openid,$wechat['tempkey'],$params['data'],'');
                if (!$res) {
                    $this->error('网络繁忙');
                }
                $this->writesmg($params['reservoir_id'],$params['title'],$params['remark']);
                $this->success('发送成功');
            }
            
        }
        preg_match_all("/\{\{(.*?)\}\}/",$wechat['content'],$matches);
        $var = $matches[1];
        foreach ($var as $key=>&$item){
            $item = substr($item,0,strlen($item)-5);
        }
        $userlist = \app\admin\model\reservoir\User::field('uid as user_id,name')->select();
        $this->success('',['varlist'=>$var,'emo'=>$msg->emo,'userlist'=>$userlist]);
    }
    
    private function writesmg($r=null,$c=null,$remark=null)
    {
        $model = new \app\admin\model\reservoir\Messagelog;
        $data= [
            'type'=>'template',
            'reservoir_id'=>$r,
            'content'=>$c,
            'createtime'=> time(),
            'remark'=>$remark
        ];
            
        $model->allowField(true)->save($data);
    }
    
    
    
    
    
    
    
    
    
    
}