前言
最近在做项目中,要求在后台管理中有企业微信管理的相关功能。相关准备工作,需要准备好企业微信账号,添加自建应用,获得相应功能的权限,以及agentid、secre等。
参考文档:
企业微信开发文档
功能实现
因功能接口比较多,这里以“客户敏感词”为例,以下为“敏感词”管理功能实现。
1 想法思路
企业微信接口有请求次数限制,后台操作频繁,避免多次请求企业微信接口,也为了相应速度考虑,我这里考虑将输入进行入库处理。每次新建敏感词,企业微信“新增敏感词”接口请求成功后,将数据添加到数据库,编辑和删除同理。这样敏感词列表、查看敏感词就可以减少对企业微信接口的请求。
2 注意事项
(1)敏感词这里需要依赖通讯录中的成员和部门,因此需要先开发这两个模块之后,再进行敏感词功能开发(成员和部门也做了入库处理,所以在下面代码中,我也是直接查询数据库的内容);
(2)access_token 有三种:通讯录access_token、联系人access_token以及自建应用 access_token,要根据接口需要,看需要哪一种access_token,否则就会报错。敏感词这里使用的是自建应用 access_token。
(3)要记得添加IP白名单。
3 代码实现
InterceptController.php
<?php
// +-----------------------xiaozhe-----------------------------------------------namespace app\wework\controller;use cmf\controller\AdminBaseController;
use app\wework\service\InterceptService;
use app\wework\service\WechatInterceptApi;
use app\wework\model\InterceptModel;
use app\wework\model\WeUserModel;
use app\admin\model\AdminMenuModel;class InterceptController extends AdminBaseController
{// 敏感词列表public function index(){ // 接口请求敏感词列表// $wxinterceptApi = new WechatInterceptApi();// $list = $wxinterceptApi->getInterceptRuleList();// echo "<pre>";// print_r($list);// exit;$param = $this->request->param();$interceptService = new InterceptService();$data = $interceptService->getList($param);$data->appends($param);$this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');$this->assign('lists', $data->items());$this->assign('page', $data->render());return $this->fetch();}// 新增敏感词public function add(){if ($this->request->isPost()) {$data = $this->request->param();$interceptModel = new InterceptModel();$data['create_time'] = time();$data['user_id'] = cmf_get_current_admin_id();$data['group_id'] = 0;if ($data['applicable_type'] == 2) {// 选择员工的话,是员工名$userModel = new WeUserModel();$userList = $userModel->whereIn('userid',$data['applicable_range'])->column("userid","department_id");$group_arr = array_unique(array_keys($userList));$applicable_range['user_list'] = implode(",",$userList);$applicable_range['department_list'] = implode(",",$group_arr);$data['applicable_range'] = json_encode($applicable_range,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);} else {$userModel = new WeUserModel();$userList = $userModel->whereIn('department_id',$data['applicable_range'])->column("userid");$applicable_range['user_list'] = implode(",",$userList);$applicable_range['department_list'] = $data['applicable_range'];$data['applicable_range'] = json_encode($applicable_range,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);}if (!empty($data['semantics_list'])) {$data['semantics_list'] = implode(",",$data['semantics_list']);}// 敏感词接口新增$user_list = !empty($applicable_range['user_list']) ? explode(",",$applicable_range['user_list']) : [];$department_list = explode(",",$applicable_range['department_list']);$wx_intercept = array('rule_name' => $data['rule_name'],'word_list' => explode(",",$data['word_list']),'semantics_list' => explode(",",$data['semantics_list']),'intercept_type' => $data['intercept_type'],'applicable_range' => array('user_list' => $user_list,'department_list' => $department_list));$wxinterceptApi = new WechatInterceptApi();$res = $wxinterceptApi->addInterceptRule($wx_intercept);if ($res['errcode'] != 0) {$this->error($res['errmsg'], url("Intercept/index"));}$data['rule_id'] = $res['rule_id'];$result = $interceptModel->save($data);if ($result) {$this->success('添加成功!', url("Intercept/index"));} else {$this->error('添加失败!', url("Intercept/index"));}}return $this->fetch();}// 编辑敏感词public function edit(){if ($this->request->isPost()) {$data = $this->request->param();$id = $data['id'] ?? 0;unset($data['id']);if ($data['applicable_type'] == 2) {// 选择员工的话,是员工名$userModel = new WeUserModel();$userList = $userModel->whereIn('userid',$data['applicable_range'])->column("userid","department_id");$group_arr = array_unique(array_keys($userList));$applicable_range['user_list'] = implode(",",$userList);$applicable_range['department_list'] = implode(",",$group_arr);$data['applicable_range'] = json_encode($applicable_range,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);} else {$userModel = new WeUserModel();$userList = $userModel->whereIn('department_id',$data['applicable_range'])->column("userid");$applicable_range['user_list'] = implode(",",$userList);$applicable_range['department_list'] = $data['applicable_range'];$data['applicable_range'] = json_encode($applicable_range,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);}$update_info = $data;$interceptModel = new InterceptModel();// 敏感词接口编辑// 查询原来的数据$rule_info = $interceptModel->field("rule_id,applicable_range")->where("id",$id)->find();$old_add_applicable_range = json_decode($rule_info['applicable_range'],true);$old_user_list = !empty($old_add_applicable_range['user_list']) ? explode(",",$old_add_applicable_range['user_list']) : [];$old_department_list = !empty($old_add_applicable_range['department_list']) ? explode(",",$old_add_applicable_range['department_list']) : [];$user_list = !empty($applicable_range['user_list']) ? explode(",",$applicable_range['user_list']) : [];$department_list = explode(",",$applicable_range['department_list']);$wx_intercept = array('rule_id' => $rule_info['rule_id'],'rule_name' => $update_info['rule_name'],'word_list' => explode(",",$update_info['word_list']),'extra_rule' => array('semantics_list' => $data['semantics_list'],),'intercept_type' => $data['intercept_type'],'add_applicable_range' => array('user_list' => $user_list,'department_list' => $department_list),'remove_applicable_range' => array('user_list' => $old_user_list,'department_list' => $old_department_list));$wxinterceptApi = new WechatInterceptApi();$res = $wxinterceptApi->updateInterceptRule($wx_intercept);if ($res['errcode'] != 0) {$this->error($res['errmsg'], url("Intercept/index"));}if (!empty($update_info['semantics_list'])) {$update_info['semantics_list'] = implode(",",$update_info['semantics_list']);}$result = $interceptModel->where("id",$id)->update($update_info);if ($result) {$this->success('编辑成功!', url("Intercept/index"));} else {$this->error('编辑失败!', url("Intercept/index"));}}$id = $this->request->param('id', 0, 'intval');if (empty($id)) {$this->error('请求参数有误!');}// 查询敏感词信息$interceptService = new InterceptService();$info = $interceptService->getInfo($id);// 接口请求敏感词详情// $wxinterceptApi = new WechatInterceptApi();// $list = $wxinterceptApi->getInterceptRuleInfo(['rule_id'=>$info['rule_id']]);// echo "<pre>";// print_r($list);// exit;$this->assign('info',$info);return $this->fetch();}// 删除敏感词public function delete(){$param = $this->request->param();$interceptModel = new InterceptModel();if (isset($param['id'])) {$id = $this->request->param('id', 0, 'intval');$rule_info = $interceptModel->field("rule_id")->where("id",$id)->find();$wxinterceptApi = new WechatInterceptApi();$wx_res = $wxinterceptApi->deleteInterceptRule(['rule_id'=>$rule_info['rule_id']]);if ($wx_res['errcode'] == 0) {$result = $interceptModel->where('id', $id)->delete();$this->success("删除成功!");} else {$this->error("删除失败!");}}}public function checkWorker(){$param = $this->request->param();$applicable_type = $param['type'] ?? 1;$applicable_range = $param['value'] ?? "";$interceptService = new InterceptService();$result = $interceptService->getWorkerList($param);$this->assign('menus', $result);$this->assign('applicable_range', explode(",",$applicable_range));$this->assign('applicable_type',$applicable_type);return $this->fetch();}}
InterceptService.php
<?php
// +----------------------------------------------------------------------
// xiaozhe
// +----------------------------------------------------------------------
namespace app\wework\service;use app\wework\model\InterceptModel;
use app\wework\model\DepartModel;
use app\wework\model\WeUserModel;
use think\db\Query;class InterceptService
{public function getList($filter){$field = 'a.id,a.rule_name,a.word_list,a.intercept_type,a.applicable_type,a.user_id,a.create_time,a.update_time,u.user_nickname';$interceptModel = new InterceptModel();$result = $interceptModel->alias("a")->leftJoin("user u","a.user_id = u.id")->field($field)->where(function (Query $query) use ($filter) {$keyword = empty($filter['keyword']) ? '' : $filter['keyword'];if (!empty($keyword)) {$query->where('a.title', 'like', "%$keyword%");}})->paginate(15);return $result;}public function getInfo($id){$interceptModel = new InterceptModel();$info = $interceptModel->where("id",$id)->find();if (!empty($info['semantics_list'])) {$info['semantics_list'] = explode(",",$info['semantics_list']);}if (!empty($info['applicable_range'])) {$info['applicable_range'] = json_decode($info['applicable_range'],true);$info['user_count'] = count(explode(",",$info['applicable_range']['user_list']));$info['depart_count'] = count(explode(",",$info['applicable_range']['department_list']));if ($info['applicable_type'] == 1) {// 部门$info['applicable_range_value'] = $info['applicable_range']['department_list'];} else {// 员工$userModel = new WeUserModel();$userIds = $userModel->whereIn("userid",$info['applicable_range']['user_list'])->whereIn("department_id",$info['applicable_range']['department_list'])->column("userid");$info['applicable_range_value'] = implode(",",$userIds);}}return $info;}public function getWorkerList($filter){$type = $filter['type'];switch ($type) {case 1:// 部门$departmentModel = new DepartModel();$newList = $departmentModel->field("department_id as id,name,parentid as parent_id")->select()->toArray();break;case 2:// 员工$userModel = new WeUserModel();$newList = $userModel->field("userid as id,name")->select()->toArray();break;default:// code...break;}return $newList;}}
WechatInterceptApi.php
<?php
// +----------------------------------------------------------------------
// | xiaozhe
// +----------------------------------------------------------------------
namespace app\wework\service;
use app\wework\model\ConfigModel;
use think\Db;
/**
* 企业微信接口
**/
class WechatInterceptApi
{/*** 获取通讯录access_token**/public function getStaffAccessToken(){$cache_key = 'staff_access_token';$res = cache($cache_key);if(empty($res)){// 读取配置$WeworkConfigModel = new ConfigModel();$info = $WeworkConfigModel->where("id",1)->find();$response = cmf_curl_get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$info['corpid']}&corpsecret={$info['user_secret']}");$arr = json_decode($response, true); if($arr['errcode'] !== 0){return '';}cache($cache_key, $arr['access_token'], 6900);}return $res;}/*** 获取客户联系人access_token**/static public function getCustomerAccessToken(){$cache_key = 'customer_access_token';$res = cache($cache_key);if(empty($res)){$WeworkConfigModel = new ConfigModel();$info = $WeworkConfigModel->where("id",1)->find();$response = cmf_curl_get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$info['corpid']}&corpsecret={$info['customer_secret']}");$arr = json_decode($response, true); if($arr['errcode'] !== 0){return '';}cache($cache_key, $arr['access_token'], 6900);}return $res;}/*** 获取自建应用 access_token**/public function getSelfappAccessToken(){$cache_key = 'selfapp_access_token';$res = cache($cache_key);if(empty($res)){$WeworkConfigModel = new ConfigModel();$info = $WeworkConfigModel->where("id",1)->find();$response = cmf_curl_get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$info['corpid']}&corpsecret={$info['corpsecret']}");$arr = json_decode($response, true); if($arr['errcode'] !== 0){return '';}cache($cache_key, $arr['access_token'], 6900);}return $res;}// 获取敏感词列表public function getInterceptRuleList(){$token = self::getSelfappAccessToken();$res = cmf_curl_get("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_intercept_rule_list?access_token=".$token,array());$resp_arr = json_decode($res, 1);return $resp_arr;}// 新增敏感词public function addInterceptRule($filter){$token = self::getSelfappAccessToken();$res = self::curl_post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_intercept_rule?access_token=".$token,json_encode($filter));$resp_arr = json_decode($res, 1);return $resp_arr;}// 获取敏感词详情public function getInterceptRuleInfo($filter){$token = self::getSelfappAccessToken();$res = self::curl_post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_intercept_rule?access_token=".$token,json_encode($filter));$resp_arr = json_decode($res, 1);return $resp_arr;}// 修改敏感词规则public function updateInterceptRule($filter){$token = self::getSelfappAccessToken();$res = self::curl_post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/update_intercept_rule?access_token=".$token,json_encode($filter));$resp_arr = json_decode($res, 1);return $resp_arr;}// 删除敏感词public function deleteInterceptRule($filter){$token = self::getSelfappAccessToken();$res = self::curl_post("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_intercept_rule?access_token=".$token,json_encode($filter));$resp_arr = json_decode($res, 1);return $resp_arr;}public function curl_post($url,$data){$curl = curl_init(); // 启动一个CURL会话curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referercurl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求curl_setopt($curl, CURLOPT_POSTFIELDS,$data); // Post提交的数据包curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回$result = curl_exec($curl); // 执行操作return $result;}
}
(前端代码我就不放了哈,自行写一哈)
实现效果
敏感词列表
新增敏感词
编辑敏感词