platform = $platform; $where = ['user_id' => (int)$user_id, 'client' => $platform]; $user_model = UserAuth::where($where)->find(); $this->openid = $user_model['openid']; if ($this->platform === Client_::oa) { $this->config = WeChatServer::getOaConfig(); $this->app = Factory::officialAccount($this->config); } else if ($this->platform === Client_::mnp) { $this->config = WeChatServer::getMnpConfig(); $this->app = Factory::miniProgram($this->config); } } // 发送消息 public function send($params) { if (empty($this->openid)) { return false; } // 获取template_id $scene = NoticeSetting::where(['scene' => $params['scene']])->find()->toArray(); if ($this->platform == Client_::oa) { $scene_model = $scene['oa_notice']; $send_type = NoticeEnum::OA_NOTICE; } else { $scene_model = $scene['mnp_notice']; $send_type = NoticeEnum::MNP_NOTICE; } if (!$scene_model || $scene_model['status'] == 0 || $scene_model['template_id'] == '') { return false; } else { $this->template_id = $scene_model['template_id']; } if ($this->platform == Client_::oa) { $template = $this->oaTemplate($params, $scene_model); } else { $template = $this->mnpTemplate($params, $scene_model); } $this->notice = MessageNoticeLogic::addNoticeLog($params, $scene_model, $send_type, json_encode($template, true)); // 发送消息 try { if ($this->platform === Client_::oa) { $res = $this->app->template_message->send($template); } else if ($this->platform === Client_::mnp) { $res = $this->app->subscribe_message->send($template); } MessageNoticeLogic::updateNotice($this->notice['id'], json_encode($res, true)); return true; } catch (\Exception $e) { MessageNoticeLogic::updateNotice($this->notice['id'], $e->getMessage()); return false; } } // 公众号消息模板 public function oaTemplate($params, $scene_model) { $domain = request()->domain(); $tpl = [ 'touser' => $this->openid, 'template_id' => $this->template_id, 'url' => $domain.$params['url'], 'data' => [ 'first' => $scene_model['first'], 'remark' => $scene_model['remark'] ] ]; return $this->tplformat($scene_model, $params, $tpl); } // 小程序消息模板 public function mnpTemplate($params, $scene_model) { $tpl = [ 'touser' => $this->openid, 'template_id' => $this->template_id, 'page' => $params['page'] ]; return $this->tplformat($scene_model, $params, $tpl); } // 调换变量 public function tplformat($scene_model, $params, $tpl) { foreach ($scene_model['tpl'] as $item) { foreach ($params['params'] as $k => $v) { $search_replace = '{'.$k.'}'; $item['tpl_content'] = str_replace($search_replace, $v, $item['tpl_content']); } $tpl['data'][$item['tpl_keyword']] = $item['tpl_content']; } return $tpl; } }