123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326 |
- <?php
- /**
- * Created by: PhpStorm
- * User: lytian
- * Date: 2019/11/19
- * Time: 14:41
- */
- namespace app\admin\controller\wechat;
- use app\admin\library\AbWeChatAuthorization;
- use app\common\controller\Backend;
- use app\common\library\Redis;
- use app\main\constants\AdminConstants;
- use app\main\service\AdminService;
- use app\main\service\GdtMpApiService;
- use app\main\service\OpenPlatformService;
- use app\main\service\ReferralService;
- use EasyWeChat\Factory;
- use Symfony\Component\Cache\Simple\RedisCache;
- use think\Log;
- class Abwechat extends Backend
- {
- protected $model = null;
- protected $noNeedRight = ['callbacktime'];
- public function _initialize()
- {
- parent::_initialize();
- $this->model = model('WechatAb');
- }
- public function index()
- {
- //设置过滤方法
- $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)
- ->where('admin_id', 'eq', $this->auth->id)
- ->order($sort, $order)
- ->count();
- $list = $this->model
- ->field(["JSON_EXTRACT(json, '$.authorizer_info.nick_name') as gzh_name", "id", "referral_id", "createtime", "updatetime", "admin_id"])
- ->where('admin_id', 'eq', $this->auth->id)
- ->where($where)
- ->order($sort, $order)
- ->limit($offset, $limit)
- ->select();
- if ($list) {
- foreach ($list as &$row) {
- $row['gzh_name'] = str_replace(['"'], [''], $row['gzh_name']);
- $row['referral'] = '';
- if ($row['referral_id']) {
- $referralIds = explode(',', $row['referral_id']);
- if ($referralIds) {
- foreach ($referralIds as $referralId) {
- $url = getCurrentDomain($row['admin_id'], '/t/'.$referralId);
- $row['referral'] .= $url. ' ';
- }
- $row['referral']= nl2br($row['referral']);
- }
- }
- }
- }
- $result = array("total" => $total, "rows" => $list);
- return json($result);
- }
- return $this->view->fetch();
- }
- /**
- * 授权A号
- * @return mixed
- */
- public function add()
- {
- $abPlatformId = \think\Config::get("ab_platform_id");
- if (empty($abPlatformId)) {
- $this->error("请先配置AB号专用三方平台");
- }
- if(!$platform = model('platform')->whereIn('id',$abPlatformId)->where(['status'=>'1'])->select()){
- $this->error("没有平台信息");
- }
- $platform = collection($platform)->toArray();
- $current_auth_platform = [];
- foreach($platform as $key => $info){
- $wechat = config('wechat');
- $wechat['app_id'] = $info['appid'];
- $wechat['secret'] = $info['secret'];
- $wechat['token'] = $info['token'];
- $wechat['aes_key'] = $info['aes_key'];
- if ($proxy = OpenPlatformService::instance()->getProxy($info['id'])) {
- $wechat['http'] = array_merge(\think\Config::get('wechat.http'), ['proxy' => $proxy]);
- }
- $openPlatform = Factory::openPlatform($wechat);
- $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
- $params = [ //跳转参数
- 'platform_id' => $info['id'],
- 'admin_id' => $this->auth->id,
- 'backurl' => $this->request->scheme() . '://' . get_host_no_port() . '/admin/wechat/abwechat/index?ref=addtabs'
- ];
- $url = $openPlatform->getPreAuthorizationUrl(\think\Config::get('site.scheme').'://'.$info['authhost'].'/admin/wechat/abwechat/wxcallback?'.http_build_query($params));
- $platform[$key]['url'] = \think\Config::get('site.scheme').'://'.$info['authhost'].'/admin/admin/config/wxre?url='.base64_encode($url);
- //检查授权
- $platform[$key]['is_auth'] = false;
- if(empty($current_auth_platform)){
- $current_auth_platform = $platform[$key];
- }
- }
- $this->view->assign('current_auth_platform',$current_auth_platform);
- $this->view->assign("platform", $platform);
- $this->view->assign("is_auth", false);
- return $this->fetch();
- }
- /**
- * 编辑
- */
- 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);
- }
- $before = $row['referral_id'];
- $params['referral_id'] = '';
- if ($params['referral']) {
- //处理推广链接 正则匹配
- if (preg_match_all("|t/(\d+)|", $params['referral'], $m)) {
- $params['referral_id'] = $m[1];
- //需要验证是否是该渠道的推广链接
- $params['referral_id'] = $params['referral_id'] ? implode(',', $params['referral_id']) : '';
- $count = model("Referral")->where('id', 'in', $params['referral_id'])->where('admin_id', 'eq', $this->auth->id)->count();
- if ($count != count($m[1])) {
- $this->error("仅能添加该渠道的推广链接", '');
- }
- }
- }
- unset($params['referral']);
- $params['updatetime'] = time();
- $result = model("WechatAb")->update($params, ['id' => $row['id']]);
- if ($result !== false)
- {
- $this->model->delRedis($row['id']);
- if ($params['referral_id']) {
- $after = explode(',',$params['referral_id'] ?:'');
- } else {
- $after = [];
- }
- if ($before) {
- $before = explode(',',$before ?:'');
- } else {
- $before = [];
- }
- $del = array_diff($before, $after);
- $add = array_diff($after, $before);
- if ($del) {
- foreach ($del as $referral_id) {
- ReferralService::instance()->modifyAdReferralCache($referral_id, $row['id'], 'del');
- }
- }
- if ($add) {
- foreach ($add as $referral_id) {
- ReferralService::instance()->modifyAdReferralCache($referral_id, $row['id'], 'add');
- }
- }
- $this->success();
- }
- else
- {
- $this->error($row->getError());
- }
- }
- catch (\think\exception\PDOException $e)
- {
- $this->error($e->getMessage());
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- //格式化内容
- if ($row['referral_id']) {
- $row['referral'] = [];
- $referralIds = explode(',', $row['referral_id']);
- if ($referralIds) {
- $referrals = [];
- foreach ($referralIds as $referralId) {
- $url = getCurrentDomain($row['admin_id'], '/t/'.$referralId);
- $referrals[]= $url;
- }
- $row['referral'] = $referrals;
- }
- }
- $this->view->assign("row", $row);
- return $this->view->fetch();
- }
- /**
- * 授权回调
- */
- public function wxcallback(){
- $url = rawurldecode($this->request->get('backurl'));
- try{
- $is_update = $this->request->param('is_update') ?? false;
- $wechatAuth = new AbWeChatAuthorization($this->request->get('platform_id'),$this->request->get('admin_id'));
- $wechatAuth->authorization($is_update);
- }catch (\Exception $e){
- Log::error('AbWechat Authorization Platform_id:'.$this->request->get('platform_id').' Admin_id:'.$this->request->get('admin_id').' Error:'.$e->getMessage());
- $this->error($e->getMessage(),$url);
- }
- $this->success('授权成功',$url,'',1);
- }
- /**
- * 选择链接
- * @param string $id
- * @param string $referral_id
- */
- public function dochoose($id = "", $referral_id = "")
- {
- if (empty($referral_id) || empty($id)) {
- Log::error('缺少参数');
- $this->error("缺少参数");
- }
- $row = $this->model->get($id);
- if (empty($row) || $row['admin_id'] != $this->auth->id) {
- $this->error("记录不存在");
- }
- $referralIds = $row['referral_id'];
- if ($referralIds) {
- $referralIds = explode(',', $referralIds);
- } else {
- $referralIds = [];
- }
- array_push($referralIds, $referral_id);
- $update['referral_id'] = implode(',', array_unique($referralIds));
- $update['updatetime'] = time();
- if (model("WechatAb")->update($update, ['id' => $id])) {
- //更新redis
- $this->model->delRedis($id);
- ReferralService::instance()->modifyAdReferralCache($referral_id, $id, 'add');
- $this->success("保存成功");
- } else {
- Log::error("绑定推广链接失败:id:{$id} referral_id:{$referral_id}");
- $this->error("保存失败");
- }
- }
- public function callbacktime()
- {
- $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($this->auth->id);
- if ($this->request->isAjax()) {
- $params = $this->request->post();
- if (isset($params['gdt_mp_report_state'])) {
- $params['gdt_mp_report_state'] = 1;
- } else {
- $params['gdt_mp_report_state'] = 0;
- }
- AdminService::instance()->getAdminConfigModel()->update($params, ['admin_id'=>$this->auth->id]);
- model('AdminConfig')->delAdminInfoAllCache($this->auth->id);
- $this->success();
- }
- $this->view->assign('admin', $adminConfig);
- $adminConfig['callback_time_mp'] = $adminConfig['callback_time_gdt'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
- //显示GDT web数据源ID
- $key = 'ASAD:WEB:' . $adminConfig['appid'];
- if (($wx_source_id = Redis::instance()->get($key)) == false) {
- //需要创建拉取
- $wx_source_id = GdtMpApiService::instance()->getUserActionSetId($adminConfig);
- }
- $this->view->assign('wx_source_id', $wx_source_id);
- return $this->view->fetch();
- }
- }
|