ChangeMenu.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. /*
  3. * 检测公众号是否被封
  4. */
  5. namespace app\admin\command;
  6. use app\common\library\Redis;
  7. use app\common\library\WeChatObject;
  8. use EasyWeChat\Factory;
  9. use Symfony\Component\Cache\Simple\RedisCache;
  10. use think\Config;
  11. use think\console\Command;
  12. use think\console\Input;
  13. use think\console\input\Option;
  14. use think\console\Output;
  15. use app\common\model\AdminConfig;
  16. use app\common\model\Config as dbconfig;
  17. use think\Log;
  18. use think\Exception;
  19. use think\Request;
  20. class ChangeMenu extends Command
  21. {
  22. protected $message = '';
  23. protected function configure()
  24. {
  25. $this->setName('ChangeMenu')
  26. ->addOption("find","f",Option::VALUE_REQUIRED,'查找要替换的菜单域名')
  27. ->addOption("replace","r",Option::VALUE_REQUIRED,'替换菜单域名为当前域名')
  28. ->addOption("delay","d",Option::VALUE_REQUIRED,'休眠时间')
  29. ->addOption('channel',"c",Option::VALUE_REQUIRED,'替换的渠道OR配号代理商例: 1 or 1,2,3,4 or 1-100 or 1-20&30-40')
  30. ->addOption('params','p',Option::VALUE_REQUIRED,'添加参数例: type=1 or type=1&name=ss')
  31. ->setDescription('替换微信菜单地址');
  32. }
  33. protected function execute(Input $input, Output $output){
  34. $channel_map = null;
  35. //cli模式下无法获取到当前的项目模块,手动指定一下
  36. Request::instance()->module('admin');
  37. //查找替换
  38. $find = $input->getOption('find');
  39. //替换地址
  40. $replace = $input->getOption('replace');
  41. //获取休眠时间
  42. $sleep = $input->getOption('delay');
  43. //获取渠道ID
  44. $channel_id = $this->getInputChannelParams($input);
  45. //获取参数
  46. parse_str(trim($input->getOption('params'),'&'),$params);
  47. if($channel_id){
  48. $channel_map['admin_id'] = ['in',$channel_id];
  49. }
  50. $output->info('ChangeMenu -----------------------------------> Start');
  51. $output->info('Params: find = '.$find);
  52. $output->info('Params: replace = '.$replace);
  53. $output->info('Params: sleep = '.$sleep);
  54. $output->info('Params: channel_id = '.$channel_id);
  55. $output->info('Params: params = '.var_export($params,true));
  56. Log::info("ChangeMenu->Params: find:{$find},replace:{$replace},sleep:{$sleep},channel_id:{$channel_id},params:".var_export($params,true));
  57. if(!$adminConfig = model('AdminConfig')->where($channel_map)->field('admin_id,appid,refresh_token,wx_menu')->select()){
  58. $output->error('ChangeMenu->Error:渠道OR配号代理商为空');
  59. return;
  60. }
  61. $output->info('ChangeMenu->SQL:'.model('AdminConfig')->getLastSql());
  62. Log::info('ChangeMenu->SQL:'.model('AdminConfig')->getLastSql());
  63. foreach($adminConfig as $channel){
  64. //微信菜单为空时跳过
  65. if(empty($channel['wx_menu'])){
  66. $output->info('ChangeMenu->Source->Menu:'.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} Menu Is NULL");
  67. continue;
  68. }
  69. Log::info('ChangeMenu->Source->Menu:'.var_export($channel['wx_menu'],true));
  70. //为查找替换时,值不匹配时处理
  71. $channel['wx_menu'] = json_encode($channel['wx_menu'],JSON_UNESCAPED_UNICODE);
  72. if(!empty($find) && !strpos($channel['wx_menu'],$find)){
  73. $output->info('ChangeMenu->Find->Replace: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} Mismatch");
  74. Log::info('ChangeMenu->Find->Replace: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} Mismatch");
  75. continue;
  76. }
  77. //为查找替换时,替换指定地址
  78. if($find && $replace){
  79. $channel['wx_menu'] = str_replace($find,$replace,$channel['wx_menu']);
  80. }
  81. $menu = json_decode($channel['wx_menu'],true);
  82. foreach($menu as $key => &$val){
  83. if(isset($val['url'])){
  84. //直接替换顶级域名
  85. if(empty($find) && $replace){
  86. if(preg_match("/\/\/wx[A-Za-z0-9]+./i", $val['url'])){
  87. $val['url'] = $this->replaceDomain($val['url'],$replace);
  88. }
  89. // //检测入口域名
  90. // if($isEntry = $this->checkIsEntryHost($val['url'])){
  91. // $val['url'] = $this->replaceDomain($val['url'],$replace,$isEntry);
  92. // }
  93. }
  94. //参数不为空时,追加参数
  95. if($params){
  96. $val['url'] = $this->addUrlParams($val['url'],$params);
  97. }
  98. }
  99. if(isset($val['sub_button']) && !empty($val['sub_button'])){
  100. foreach($val['sub_button'] as $sub_k => &$sub_v){
  101. if(isset($sub_v['url'])){
  102. //直接替换顶级域名
  103. if(empty($find) && $replace) {
  104. if (preg_match("/\/\/wx[A-Za-z0-9]+./i", $sub_v['url'])) {
  105. $sub_v['url'] = $this->replaceDomain($sub_v['url'], $replace);
  106. }
  107. // //检测入口域名
  108. // if($isEntry = $this->checkIsEntryHost($sub_v['url'])){
  109. // $sub_v['url'] = $this->replaceDomain($sub_v['url'], $replace,$isEntry);
  110. // }
  111. }
  112. //参数不为空时,追加参数
  113. if($params){
  114. $sub_v['url'] = $this->addUrlParams($sub_v['url'],$params);
  115. }
  116. }
  117. }
  118. }
  119. }
  120. $channel['wx_menu'] = $menu;
  121. Log::info('ChangeMenu->Replace->Menu:'.var_export($channel['wx_menu'],true));
  122. try {
  123. //更新菜单
  124. $admin = model('AdminConfig')->getAdminInfoAll($channel['admin_id']);
  125. if(empty($admin['refresh_token'])){
  126. Log::info('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} refresh_token Empty!!");
  127. continue;
  128. }
  129. $wechat = new WeChatObject($admin);
  130. $officialAccount = $wechat->getOfficialAccount();
  131. // $officialAccount->menu->delete(); //删除全部菜单 主要是掌中云个性化菜单
  132. $ret = $officialAccount->menu->create($channel['wx_menu']);
  133. if ($ret['errcode'] == 0) {
  134. $output->info('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} WeChat Update Success");
  135. Log::info('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} WeChat Update Success");
  136. //更新数据
  137. $update = model('AdminConfig')->update(['wx_menu' => $channel['wx_menu']], ["admin_id" => $channel['admin_id']]);
  138. if ($update) {
  139. $output->info('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} Mysql Update Success");
  140. Log::info('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} Mysql Update Success");
  141. } else {
  142. $output->info('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} Mysql Update Fail");
  143. Log::error('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} Mysql Update Fail");
  144. }
  145. } else {
  146. $output->info('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} WeChat Update Fail Error:" . $ret['errmsg']);
  147. Log::error('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} WeChat Update Fail Error:" . $ret['errmsg']);
  148. }
  149. //休眠
  150. if (!empty($sleep) && is_numeric($sleep)) {
  151. sleep($sleep);
  152. }
  153. }catch (\Exception $exception){
  154. Log::error('ChangeMenu->WeChat->Menu: '.date('Y-m-d H:i:s') . " admin_id:{$channel['admin_id']} WeChat Update Fail Error:" . $exception->getMessage());
  155. }
  156. }
  157. $output->info('ChangeMenu -----------------------------------> End');
  158. }
  159. /**
  160. * 检测是否是入口域名
  161. * @param $url
  162. * @return bool
  163. */
  164. protected function checkIsEntryHost($url){
  165. $entryHost = model('Entryhost')->getHosts();
  166. foreach($entryHost as $host){
  167. if (preg_match("/{$host}/i", $url)) {
  168. return true;
  169. }
  170. }
  171. return false;
  172. }
  173. /**
  174. * 替换顶级域名
  175. * @param $source_url
  176. * @param $replace
  177. * @param $isEntry
  178. * @return string
  179. */
  180. protected function replaceDomain($source_url,$replace,$isEntry = false){
  181. $url = '';
  182. $url_arr = parse_url($source_url);
  183. if($isEntry){
  184. $url .= $url_arr['scheme'].'://'.$replace.($url_arr['path'] ?? '');
  185. }else{
  186. $app_id = explode('.',$url_arr['host'])[0];
  187. $url .= $url_arr['scheme'].'://'.$app_id.'.'.$replace.($url_arr['path'] ?? '');
  188. }
  189. if(isset($url_arr['query']) && !empty($url_arr['query'])){
  190. $url .= '?'.$url_arr['query'];
  191. }
  192. return $url;
  193. }
  194. /**
  195. * URL地址追加参数
  196. * @param $url
  197. * @param $params
  198. * @return string
  199. */
  200. protected function addUrlParams($url,$params){
  201. $url_arr = parse_url($url);
  202. parse_str(($url_arr['query'] ?? ''),$url_params);
  203. $url_params = array_merge($url_params,$params);
  204. $url_params = array_filter($url_params,function($val){if($val != '')return true;});
  205. $url = $url_arr['scheme'].'://'.$url_arr['host'].($url_arr['path']??'');
  206. if($url_params){
  207. $url .= '?'.http_build_query($url_params);
  208. }
  209. return $url;
  210. }
  211. /**
  212. * 获取渠道ID
  213. * @param Input $input
  214. * @return string
  215. */
  216. protected function getInputChannelParams(Input $input){
  217. $channel = $input->getOption('channel');
  218. $channelIds = [];
  219. if($channel_params = explode('&',$channel)){
  220. foreach($channel_params as $val){
  221. if($index = explode('-',$val)){
  222. if(isset($index[0]) && isset($index[1]) && !empty($index[0]) && !empty($index[1]) && ($index[0] < $index[1])){
  223. for($i = $index[0];$i<=$index[1];$i++){
  224. if(!in_array($i,$channelIds)){
  225. array_push($channelIds,$i);
  226. }
  227. }
  228. }else{
  229. if(isset($index[0]) && !empty($index[0])){
  230. if($ids = explode(',',$index[0])){
  231. $channelIds = array_merge($channelIds,$ids);
  232. }
  233. }
  234. }
  235. }
  236. }
  237. }
  238. return implode(',',$channelIds);
  239. }
  240. }