WxPush.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\command;
  4. use app\bug\model\WechatPush;use think\console\Command;
  5. use think\console\Input;
  6. use think\console\input\Argument;
  7. use think\console\input\Option;
  8. use think\console\Output;use think\facade\Cache;use think\facade\Log;
  9. class WxPush extends Command
  10. {
  11. protected function configure()
  12. {
  13. // 指令配置
  14. $this->setName('wxpush')
  15. ->setDescription('the wxpush command');
  16. }
  17. protected function execute(Input $input, Output $output)
  18. {
  19. $redis = Cache::store('redis')->handler();
  20. $isLock = $redis->set("wxpush_lock", time() + 600, array('nx', 'ex'=>600));
  21. if(!$isLock)return;
  22. try{
  23. $appid = env('WECHAT.APPID');
  24. $appsecret = env('WECHAT.APPSECRET');
  25. $wechat = new \Wechat(['appid' => $appid, 'appsecret' => $appsecret]);
  26. $que= Cache::store('redis')->handler()->lpop('wxpush_queue');
  27. while ($que){
  28. $data=json_decode($que,true);
  29. $temp=[];
  30. $res=false;
  31. if($data['openId']!=''){
  32. $temp['touser'] =$data['openId'];
  33. $temp['template_id'] = $data['template_id'];
  34. $temp['data']=$data['template_data'];
  35. $res= $wechat->sendTemplateMessage($temp);
  36. if($res==false && $wechat->errCode==40001){
  37. $wechat->resetAuth(env('WECHAT.APPID'));
  38. $wechat->sendTemplateMessage($temp);
  39. }
  40. }
  41. $add= [
  42. 'bugNo'=>$data['code'],
  43. 'belong'=>$data['belong'],
  44. 'action_name'=>$data['action_name'],
  45. 'template_id'=>$data['template_id'],
  46. 'template_name'=>$data['template_name'],
  47. 'content'=>json_encode($temp,JSON_UNESCAPED_UNICODE),
  48. 'push_id'=>$data['uid'],
  49. 'pusher'=>$data['uname'],
  50. 'status'=>$res?1:0,
  51. 'remark'=>$res?'':$wechat->errMsg
  52. ];
  53. WeChatPush::create($add);
  54. Log::write('data:'.json_encode($add,JSON_UNESCAPED_UNICODE),'info');
  55. $output->writeln(json_encode($add,JSON_UNESCAPED_UNICODE));
  56. $que= Cache::store('redis')->handler()->lpop('wxpush_queue');
  57. }
  58. }catch (\Exception $e){
  59. Log::write('wxpush:'.$e->getMessage(),'error');
  60. $output->writeln($e->getMessage());
  61. }
  62. $redis->delete("wxpush_lock");
  63. }
  64. }