Abwechat.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * Created by: PhpStorm
  4. * User: lytian
  5. * Date: 2019/11/19
  6. * Time: 14:41
  7. */
  8. namespace app\admin\controller\wechat;
  9. use app\admin\library\AbWeChatAuthorization;
  10. use app\common\controller\Backend;
  11. use app\common\library\Redis;
  12. use app\main\constants\AdminConstants;
  13. use app\main\service\AdminService;
  14. use app\main\service\GdtMpApiService;
  15. use app\main\service\OpenPlatformService;
  16. use app\main\service\ReferralService;
  17. use EasyWeChat\Factory;
  18. use Symfony\Component\Cache\Simple\RedisCache;
  19. use think\Log;
  20. class Abwechat extends Backend
  21. {
  22. protected $model = null;
  23. protected $noNeedRight = ['callbacktime'];
  24. public function _initialize()
  25. {
  26. parent::_initialize();
  27. $this->model = model('WechatAb');
  28. }
  29. public function index()
  30. {
  31. //设置过滤方法
  32. $this->request->filter(['strip_tags']);
  33. if ($this->request->isAjax())
  34. {
  35. //如果发送的来源是Selectpage,则转发到Selectpage
  36. if ($this->request->request('pkey_name'))
  37. {
  38. return $this->selectpage();
  39. }
  40. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  41. $total = $this->model
  42. ->where($where)
  43. ->where('admin_id', 'eq', $this->auth->id)
  44. ->order($sort, $order)
  45. ->count();
  46. $list = $this->model
  47. ->field(["JSON_EXTRACT(json, '$.authorizer_info.nick_name') as gzh_name", "id", "referral_id", "createtime", "updatetime", "admin_id"])
  48. ->where('admin_id', 'eq', $this->auth->id)
  49. ->where($where)
  50. ->order($sort, $order)
  51. ->limit($offset, $limit)
  52. ->select();
  53. if ($list) {
  54. foreach ($list as &$row) {
  55. $row['gzh_name'] = str_replace(['"'], [''], $row['gzh_name']);
  56. $row['referral'] = '';
  57. if ($row['referral_id']) {
  58. $referralIds = explode(',', $row['referral_id']);
  59. if ($referralIds) {
  60. foreach ($referralIds as $referralId) {
  61. $url = getCurrentDomain($row['admin_id'], '/t/'.$referralId);
  62. $row['referral'] .= $url. ' ';
  63. }
  64. $row['referral']= nl2br($row['referral']);
  65. }
  66. }
  67. }
  68. }
  69. $result = array("total" => $total, "rows" => $list);
  70. return json($result);
  71. }
  72. return $this->view->fetch();
  73. }
  74. /**
  75. * 授权A号
  76. * @return mixed
  77. */
  78. public function add()
  79. {
  80. $abPlatformId = \think\Config::get("ab_platform_id");
  81. if (empty($abPlatformId)) {
  82. $this->error("请先配置AB号专用三方平台");
  83. }
  84. if(!$platform = model('platform')->whereIn('id',$abPlatformId)->where(['status'=>'1'])->select()){
  85. $this->error("没有平台信息");
  86. }
  87. $platform = collection($platform)->toArray();
  88. $current_auth_platform = [];
  89. foreach($platform as $key => $info){
  90. $wechat = config('wechat');
  91. $wechat['app_id'] = $info['appid'];
  92. $wechat['secret'] = $info['secret'];
  93. $wechat['token'] = $info['token'];
  94. $wechat['aes_key'] = $info['aes_key'];
  95. if ($proxy = OpenPlatformService::instance()->getProxy($info['id'])) {
  96. $wechat['http'] = array_merge(\think\Config::get('wechat.http'), ['proxy' => $proxy]);
  97. }
  98. $openPlatform = Factory::openPlatform($wechat);
  99. $openPlatform['cache'] = new RedisCache(Redis::instanceCache());
  100. $params = [ //跳转参数
  101. 'platform_id' => $info['id'],
  102. 'admin_id' => $this->auth->id,
  103. 'backurl' => $this->request->scheme() . '://' . get_host_no_port() . '/admin/wechat/abwechat/index?ref=addtabs'
  104. ];
  105. $url = $openPlatform->getPreAuthorizationUrl(\think\Config::get('site.scheme').'://'.$info['authhost'].'/admin/wechat/abwechat/wxcallback?'.http_build_query($params));
  106. $platform[$key]['url'] = \think\Config::get('site.scheme').'://'.$info['authhost'].'/admin/admin/config/wxre?url='.base64_encode($url);
  107. //检查授权
  108. $platform[$key]['is_auth'] = false;
  109. if(empty($current_auth_platform)){
  110. $current_auth_platform = $platform[$key];
  111. }
  112. }
  113. $this->view->assign('current_auth_platform',$current_auth_platform);
  114. $this->view->assign("platform", $platform);
  115. $this->view->assign("is_auth", false);
  116. return $this->fetch();
  117. }
  118. /**
  119. * 编辑
  120. */
  121. public function edit($ids = NULL)
  122. {
  123. $row = $this->model->get($ids);
  124. if (!$row)
  125. $this->error(__('No Results were found'));
  126. $adminIds = $this->getDataLimitAdminIds();
  127. if (is_array($adminIds))
  128. {
  129. if (!in_array($row[$this->dataLimitField], $adminIds))
  130. {
  131. $this->error(__('You have no permission'));
  132. }
  133. }
  134. if ($this->request->isPost())
  135. {
  136. $params = $this->request->post("row/a");
  137. if ($params)
  138. {
  139. try
  140. {
  141. //是否采用模型验证
  142. if ($this->modelValidate)
  143. {
  144. $name = basename(str_replace('\\', '/', get_class($this->model)));
  145. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
  146. $row->validate($validate);
  147. }
  148. $before = $row['referral_id'];
  149. $params['referral_id'] = '';
  150. if ($params['referral']) {
  151. //处理推广链接 正则匹配
  152. if (preg_match_all("|t/(\d+)|", $params['referral'], $m)) {
  153. $params['referral_id'] = $m[1];
  154. //需要验证是否是该渠道的推广链接
  155. $params['referral_id'] = $params['referral_id'] ? implode(',', $params['referral_id']) : '';
  156. $count = model("Referral")->where('id', 'in', $params['referral_id'])->where('admin_id', 'eq', $this->auth->id)->count();
  157. if ($count != count($m[1])) {
  158. $this->error("仅能添加该渠道的推广链接", '');
  159. }
  160. }
  161. }
  162. unset($params['referral']);
  163. $params['updatetime'] = time();
  164. $result = model("WechatAb")->update($params, ['id' => $row['id']]);
  165. if ($result !== false)
  166. {
  167. $this->model->delRedis($row['id']);
  168. if ($params['referral_id']) {
  169. $after = explode(',',$params['referral_id'] ?:'');
  170. } else {
  171. $after = [];
  172. }
  173. if ($before) {
  174. $before = explode(',',$before ?:'');
  175. } else {
  176. $before = [];
  177. }
  178. $del = array_diff($before, $after);
  179. $add = array_diff($after, $before);
  180. if ($del) {
  181. foreach ($del as $referral_id) {
  182. ReferralService::instance()->modifyAdReferralCache($referral_id, $row['id'], 'del');
  183. }
  184. }
  185. if ($add) {
  186. foreach ($add as $referral_id) {
  187. ReferralService::instance()->modifyAdReferralCache($referral_id, $row['id'], 'add');
  188. }
  189. }
  190. $this->success();
  191. }
  192. else
  193. {
  194. $this->error($row->getError());
  195. }
  196. }
  197. catch (\think\exception\PDOException $e)
  198. {
  199. $this->error($e->getMessage());
  200. }
  201. }
  202. $this->error(__('Parameter %s can not be empty', ''));
  203. }
  204. //格式化内容
  205. if ($row['referral_id']) {
  206. $row['referral'] = [];
  207. $referralIds = explode(',', $row['referral_id']);
  208. if ($referralIds) {
  209. $referrals = [];
  210. foreach ($referralIds as $referralId) {
  211. $url = getCurrentDomain($row['admin_id'], '/t/'.$referralId);
  212. $referrals[]= $url;
  213. }
  214. $row['referral'] = $referrals;
  215. }
  216. }
  217. $this->view->assign("row", $row);
  218. return $this->view->fetch();
  219. }
  220. /**
  221. * 授权回调
  222. */
  223. public function wxcallback(){
  224. $url = rawurldecode($this->request->get('backurl'));
  225. try{
  226. $is_update = $this->request->param('is_update') ?? false;
  227. $wechatAuth = new AbWeChatAuthorization($this->request->get('platform_id'),$this->request->get('admin_id'));
  228. $wechatAuth->authorization($is_update);
  229. }catch (\Exception $e){
  230. Log::error('AbWechat Authorization Platform_id:'.$this->request->get('platform_id').' Admin_id:'.$this->request->get('admin_id').' Error:'.$e->getMessage());
  231. $this->error($e->getMessage(),$url);
  232. }
  233. $this->success('授权成功',$url,'',1);
  234. }
  235. /**
  236. * 选择链接
  237. * @param string $id
  238. * @param string $referral_id
  239. */
  240. public function dochoose($id = "", $referral_id = "")
  241. {
  242. if (empty($referral_id) || empty($id)) {
  243. Log::error('缺少参数');
  244. $this->error("缺少参数");
  245. }
  246. $row = $this->model->get($id);
  247. if (empty($row) || $row['admin_id'] != $this->auth->id) {
  248. $this->error("记录不存在");
  249. }
  250. $referralIds = $row['referral_id'];
  251. if ($referralIds) {
  252. $referralIds = explode(',', $referralIds);
  253. } else {
  254. $referralIds = [];
  255. }
  256. array_push($referralIds, $referral_id);
  257. $update['referral_id'] = implode(',', array_unique($referralIds));
  258. $update['updatetime'] = time();
  259. if (model("WechatAb")->update($update, ['id' => $id])) {
  260. //更新redis
  261. $this->model->delRedis($id);
  262. ReferralService::instance()->modifyAdReferralCache($referral_id, $id, 'add');
  263. $this->success("保存成功");
  264. } else {
  265. Log::error("绑定推广链接失败:id:{$id} referral_id:{$referral_id}");
  266. $this->error("保存失败");
  267. }
  268. }
  269. public function callbacktime()
  270. {
  271. $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($this->auth->id);
  272. if ($this->request->isAjax()) {
  273. $params = $this->request->post();
  274. if (isset($params['gdt_mp_report_state'])) {
  275. $params['gdt_mp_report_state'] = 1;
  276. } else {
  277. $params['gdt_mp_report_state'] = 0;
  278. }
  279. AdminService::instance()->getAdminConfigModel()->update($params, ['admin_id'=>$this->auth->id]);
  280. model('AdminConfig')->delAdminInfoAllCache($this->auth->id);
  281. $this->success();
  282. }
  283. $this->view->assign('admin', $adminConfig);
  284. $adminConfig['callback_time_mp'] = $adminConfig['callback_time_gdt'] ?? AdminConstants::CALLBACK_TIME_ONCE_24;
  285. //显示GDT web数据源ID
  286. $key = 'ASAD:WEB:' . $adminConfig['appid'];
  287. if (($wx_source_id = Redis::instance()->get($key)) == false) {
  288. //需要创建拉取
  289. $wx_source_id = GdtMpApiService::instance()->getUserActionSetId($adminConfig);
  290. }
  291. $this->view->assign('wx_source_id', $wx_source_id);
  292. return $this->view->fetch();
  293. }
  294. }