123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389 |
- <?php
- namespace app\admin\controller;
- use app\common\controller\Backend;
- use app\common\library\WeChatObject;
- use app\common\utility\DiyQRCode;
- use app\main\constants\CacheConstants;
- use think\Controller;
- use think\Request;
- use app\common\library\Ssdb;
- use think\Config;
- use EasyWeChat\Factory;
- use app\common\library\Redis;
- use Symfony\Component\Cache\Simple\RedisCache;
- use app\common\model\WechatResponse;
- /**
- * 自定义二维码
- *
- * @icon fa fa-circle-o
- */
- class Customqrcode extends Backend
- {
-
- /**
- * CustomQrcode模型对象
- */
- protected $model = null;
- /**
- * 是否开启数据限制
- * 支持auth/personal
- * 表示按权限判断/仅限个人
- * 默认为禁用,若启用请务必保证表中存在admin_id字段
- */
- protected $dataLimit = 'personal';
- public function _initialize()
- {
- parent::_initialize();
- $this->model = model('CustomQrcode');
- $this->view->assign("typeList", $this->model->getTypeList());
- }
-
- /**
- * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
- * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
- * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
- */
- /**
- * 查看
- */
- public function index()
- {
- $redis = Redis::instance();
- //设置过滤方法
- $this->request->filter(['strip_tags']);
- if ($this->request->isAjax())
- {
- //如果发送的来源是Selectpage,则转发到Selectpage
- if ($this->request->request('pkey_name'))
- {
- return $this->selectpage();
- }
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $total = $this->model
- ->where($where)
- ->order($sort, $order)
- ->count();
- $list = $this->model
- ->where($where)
- ->order($sort, $order)
- ->limit($offset, $limit)
- ->select();
- foreach($list as $val){
- $val['url_list'] = DiyQRCode::getTplPath($val['url']);
- //有推广链接获取,推广链接信息
- if(intval($val['referral_id']) && intval($val['type']) == 3){
- $ref = model('Referral')->where('id',$val['referral_id'])->find();
- //累计阅读UV
- $val['all_read_uv'] = $ref['uv'];
- //当日阅读UV
- $val['day_read_uv'] = (int)Redis::instance()->get(CacheConstants::getReadOfReferralIdKey($val['referral_id']));
- //累计充值金额
- $val['all_pay_money'] = $ref['money'];
- //当日充值金额
- $dayMTkey = "M-T:".$val['referral_id'].":".date("d"); //今日充值金额key
- $val['day_pay_money'] = (int)Redis::instance()->get($dayMTkey)? round(Redis::instance()->get($dayMTkey) / 100, 2) :0; //今日充值金额
- //推广成本
- $val['cost'] = $ref['cost'];
- }else{
- $val['day_read_uv'] = 0;
- $val['all_read_uv'] = 0;
- $val['day_pay_money'] = 0;
- $val['all_pay_money'] = sprintf("%.2f",0);
- $val['cost'] = sprintf("%.2f",0);
- }
- $uv_key = "QR_UV:{$this->auth->id}:{$val['index']}";
- $uv = $redis->pfCount($uv_key);
- if( ($uv && !$val['uv']) || $uv > $val['uv']){
- $val['uv'] = $uv;
- }
- $uv_per_day_key = "QR_UV:".date('Ymd').":{$this->auth->id}:{$val['index']}";
- $val['uv_per_day'] = $redis->pfCount($uv_per_day_key);
- }
- $result = array("total" => $total, "rows" => $list);
- return json($result);
- }
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id;
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- if ($this->dataLimit)
- {
- $params[$this->dataLimitField] = $this->auth->id;
- }
- try
- {
- //是否采用模型验证
- if ($this->modelValidate)
- {
- $name = basename(str_replace('\\', '/', get_class($this->model)));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
- $this->model->validate($validate);
- }
- $params['index'] = $this->getLastQrCodeIndex($channel_id);
- //生成二维码
- $params['url'] = $this->createWechatQrCode($channel_id,$params['index']);
- //如果使用模板,则根据模板创建二维码
- if(isset($params['template_id']) && $params['template_id']){
- DiyQRCode::createTplQRCode($params['url'],$params['template_id']);
- }
- $result = $this->model->allowField(true)->save($params);
- if ($result !== false)
- {
- $this->success();
- }
- else
- {
- $this->error($this->model->getError());
- }
- }
- catch (\think\exception\PDOException $e)
- {
- $this->error($e->getMessage());
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- return $this->view->fetch();
- }
- /**
- * 获取自定义二维码索引
- * @param $channel_id
- * @return int
- */
- private function getLastQrCodeIndex($channel_id){
- $index = 1;
- $last_index = $this->model->field('index')->where(['admin_id'=>$channel_id])->order('`index` desc')->find();
- if($last_index){
- if($last_index['index'] >= 100000){
- //大于十万时检查,是否有被删除没有使用的索引
- $indexs = $this->model->where(['admin_id'=>$channel_id])->column('index');
- $full_index = range(1,100000);
- if($rep_indexs = array_diff($full_index, $indexs)){
- return current($rep_indexs);
- }else{
- $this->error(__('WeChat QRCode Max 100000'));
- }
- }
- $index = $last_index['index'] + 1;
- }
- return $index;
- }
- /**
- * 获取自定义二维码URL
- * @param $index
- * @return mixed
- */
- private function createWechatQrCode($channel_id,$index){
- $adminConfig = model('AdminConfig')->getAdminInfoAll($channel_id);
- $wechat = new WeChatObject($adminConfig);
- $officialAccount = $wechat->getOfficialAccount();
- $result = $officialAccount->qrcode->forever($index);
- if(empty($result) || isset($result['errcode'])){
- $this->error(__('Get WeChat QRCode Error'));
- }
- return $officialAccount->qrcode->url($result['ticket']);
- }
- /**
- * 编辑
- */
- public function edit($ids = NULL)
- {
- $row = $this->model->get($ids);
- if (!$row)
- $this->error(__('No Results were found'));
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- if (!in_array($row[$this->dataLimitField], $adminIds))
- {
- $this->error(__('You have no permission'));
- }
- }
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- 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);
- }
- //如果模板不一致,生成新的模板
- if(intval($params['template_id']) != $row['template_id'] && intval($params['template_id'])){
- DiyQRCode::createTplQRCode($row['url'],$params['template_id']);
- }
- $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', ''));
- }
- $response = WechatResponse::get(['eventkey' => $row['eventkey'], 'admin_id' => $this->auth->id]);
- $this->view->assign('qrcode_list',DiyQRCode::getTplPath($row['url']));
- $this->view->assign('referral_url',model('referral')->where('id',$row['referral_id'])->value('source_url'));
- $this->view->assign("response", $response);
- $this->view->assign("row", $row);
- $this->assignconfig('ids', $ids);
- return $this->view->fetch();
- }
- /**
- * 删除
- */
- public function del($ids = "")
- {
- if ($ids)
- {
- $pk = $this->model->getPk();
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
- }
- $list = $this->model->where($pk, 'in', $ids)->select();
- $count = 0;
- foreach ($list as $k => $v)
- {
- //删除二维码图片
- DiyQRCode::unlinkQRCode($v['url']);
- //删除Redis缓存
- $redis = Redis::instance();
- $redis->del("QR_UV:{$v['admin_id']}:{$v['index']}");
- //删除数据库
- $count += $v->delete();
- }
- if ($count)
- {
- $this->success();
- }
- else
- {
- $this->error(__('No rows were deleted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', 'ids'));
- }
- /**
- * 创建二维码
- * @param $ids
- * @param $tpl_id
- * @throws \Exception
- */
- public function createimage($ids, $tpl_id)
- {
- if ($this->request->isPost())
- {
- if (empty($ids) || !is_numeric($ids) || empty($tpl_id) || !is_numeric($tpl_id)) {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $row = $this->model->get($ids);
- if (!$row)
- $this->error(__('No Results were found'));
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- if (!in_array($row[$this->dataLimitField], $adminIds))
- {
- $this->error(__('You have no permission'));
- }
- }
- $url = $row['url'];
- $qrcode_save_path = ROOT_PATH.'public'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'qrcode'.DIRECTORY_SEPARATOR;
- if(file_exists($qrcode_save_path .md5($url.$tpl_id).'.png')){
- $imgUrl = cdnurl("/uploads/qrcode/" .md5($url.$tpl_id).'.png');
- } else {
- $imgUrl = DiyQRCode::createTplQRCode($url, $tpl_id);
- }
- $this->success('二维码图片生成成功', '', $imgUrl);
- }
- }
- /**
- * 下载二维码图片
- * @param $ids
- * @param $tpl_id
- */
- public function download($ids, $tpl_id)
- {
- if (empty($ids) || !is_numeric($ids)) {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $row = $this->model->get($ids);
- if (!$row)
- $this->error(__('No Results were found'));
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- if (!in_array($row[$this->dataLimitField], $adminIds))
- {
- $this->error(__('You have no permission'));
- }
- }
- $url = $row['url'];
- if ($tpl_id) {
- $imgUrl = DiyQRCode::getTplPath($url, $tpl_id);
- if (empty($imgUrl)) {
- $this->error(__('二维码图片不存在', ''));
- }
- } else {
- $imgUrl = DiyQRCode::createQRCodeByUrl($url);
- }
- header("Cache-Control: public");
- header('Content-disposition: attachment; filename='.basename($imgUrl)); //文件名
- header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
- header('Content-Length: '. @filesize($imgUrl)); //告诉浏览器,文件大小
- @readfile($imgUrl);
- }
- }
|