PHP对接企业微信

这篇具有很好参考价值的文章主要介绍了PHP对接企业微信。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

        最近在做项目中,要求在后台管理中有企业微信管理的相关功能。相关准备工作,需要准备好企业微信账号,添加自建应用,获得相应功能的权限,以及agentid、secre等。

        参考文档:

        企业微信开发文档

PHP对接企业微信,php,企业微信

功能实现

        因功能接口比较多,这里以“客户敏感词”为例,以下为“敏感词”管理功能实现。

        1 想法思路

         企业微信接口有请求次数限制,后台操作频繁,避免多次请求企业微信接口,也为了相应速度考虑,我这里考虑将输入进行入库处理。每次新建敏感词,企业微信“新增敏感词”接口请求成功后,将数据添加到数据库,编辑和删除同理。这样敏感词列表、查看敏感词就可以减少对企业微信接口的请求。

        2 注意事项

         (1)敏感词这里需要依赖通讯录中的成员和部门,因此需要先开发这两个模块之后,再进行敏感词功能开发(成员和部门也做了入库处理,所以在下面代码中,我也是直接查询数据库的内容);

         (2)access_token 有三种:通讯录access_token、联系人access_token以及自建应用 access_token,要根据接口需要,看需要哪一种access_token,否则就会报错。敏感词这里使用的是自建应用 access_token。

         (3)要记得添加IP白名单。

PHP对接企业微信,php,企业微信

        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); // 自动设置Referer
        curl_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;
    }
}

(前端代码我就不放了哈,自行写一哈) 

PHP对接企业微信,php,企业微信

实现效果

敏感词列表

PHP对接企业微信,php,企业微信

新增敏感词

PHP对接企业微信,php,企业微信

PHP对接企业微信,php,企业微信 编辑敏感词

PHP对接企业微信,php,企业微信

PHP对接企业微信,php,企业微信 文章来源地址https://www.toymoban.com/news/detail-759832.html

到了这里,关于PHP对接企业微信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • php+mysql的基于微信小程序的企业装修平台的设计与实现 TP框架(附源码 调试 讲解 文档)

    随着移动互联网的普及,传统的装修行业逐渐向互联网装修转型。微信小程序作为一种新型的应用形态,凭借其便捷性、易用性和普及性,成为了企业装修平台开发的首选。本文旨在设计和实现一个基于微信小程序的企业装修平台,通过公司展示、案例展示、设计师展示、在

    2024年02月05日
    浏览(33)
  • 如何在PHP中对接openAI接口,PHP创建AI会话思路以及代码讲解

    https://platform.openai.com/account/api-keys 在这个地址进行注册,但是需要翻墙,可自己查找国内的试用地址。就不多赘述… php端代码: 思路:前端通过一个图标入口,点击后 发送请求,创建一个会话(也就是聊天室),并且把创建的这个会话 入库。并且后端返回一个入库生成的

    2024年01月18日
    浏览(37)
  • PHP 文心千帆API接口对接

    创建一个智能云应用。根据实际需求创建智能云应用。创建成功后,获取AppID、API Key、Secret Key 等信息。 API 授权。对应用的 AppID 进行授权。 获取接口访问凭证 access_token 。根据第1步获取的 API Key 和 Secret Key , 获取 access_token ,通过 access_token 鉴权调用者身份。 调用API接口。

    2024年02月11日
    浏览(30)
  • php对接飞书机器人

    有同事接到对接飞书机器人任务,开发中遇到响应错误: 意思应该就是签名错误或者时间戳不在有效范围内等,官方文档解释: 时间戳是取的实时的,也确认过了没问题,那基本确认就是签名错误了。 按照文档尝试调试了一下还是一样的结果,如果把后台安全设置那个签名

    2024年02月07日
    浏览(27)
  • 阿里云短信php-sdk对接

    早期用过阿里的大鱼,但现在看已经合并在了阿里云的短信服务 1)签名 2)短信模板 3)accessKeyId  4)accessKeySecret 国内消息-添加签名,添加完需要阿里云审核,大概2小时左右 国内消息-添加模板,添加完需要阿里云审核,大概2小时左右   右上角-账号-AccessKey管理 创建Acces

    2024年02月10日
    浏览(28)
  • php对接飞书自定义机器人发送消息功能

    今天收到一个需求,需要定时去监控业务是否正常稳定,并将错误信息发送到飞书,之前接入过钉钉机器人都比较顺利,但是今天接入飞书居然卡了半天,特此分享给大家,避免踩坑 1,首先创建飞书机器人 2.创建完成之后,获取机器人对应的 webhook 地址 格式如下: 3.下面提

    2024年04月09日
    浏览(41)
  • 二级域名分发系统源码 对接易支付php源码 全开源

    全面开源的易支付PHP源码分享:实现二级域名分发对接 首先,在epay的config.php文件中修改您的支付域名。 随后,在二级域名分发网站上做相应修改。 伪静态 location / { try_files $uri $uri/ /index.php?$query_string; } 源码下载:https://download.csdn.net/download/m0_66047725/88745739 更多资源下载:关

    2024年01月18日
    浏览(30)
  • php对接AWS S3云存储,上传S3及访问权限问题

    首先先下载sdk包 https://docs.aws.amazon.com/zh_cn/sdk-for-php/v3/developer-guide/getting-started_installation.html S3创建存储桶 去安全凭证-》创建访问秘钥 创建的时候会提示,主账号创建不安全,这个时候我们需要创建一个IAM账号来创建秘钥 创建的步骤访问这个链接 https://www.codenong.com/a513c91ea

    2024年02月10日
    浏览(24)
  • php对接讯飞星火认知大模型SparkDesk的Web API示例代码

    最近我在给客户开发科大讯飞的星火认知大模型SparkDesk,踩过一些坑,网上几乎搜不到PHP的demo代码,这里模板兔给出以下成果代码供大家参考。 首先,sparkdesk的接口需要使用到websocket,所以我们需要先安装websocket,使用composer在网站根目录安装: 然后就是写php代码: 我把接

    2024年02月10日
    浏览(25)
  • PHP聚合支付网站源码/对接十多个支付接口 第三方/第四方支付/系统源码

    PHP聚合支付网站源码/对接十多个支付接口 第三方/第四方支付/系统源码 内附数十个支付接口代码文件。 下载地址:https://bbs.csdn.net/topics/616764485  

    2024年02月11日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包