Java企业微信对接(一)企业端同步到微信端

封装用户和部门对象

用户对象

/**
 *@className: WeXinUserVO
 *@description: 企业微信用户数据同步
 *@author: what
 *@date: 2022/4/21 16:30
 *@version: v1.0
 */
public class WeXinUserVO implements Serializable {

    private static final long serialVersionUID = 1L;

    //用户id,其实就是手机号
    private String username;

    //姓名
    private String realname;

    //手机号
    private String tel;

    //部门id
    private List<Integer> departmentList;

    //性别
    private String gender;

    //职务
    private String dutyName;

    //邮箱
    private String email;

    //固定电话
    private String fixedTelephone;

    //主部门id
    private Integer mainOrgId;
    
}

部门对象

/**
 *@className: WeXinoOrgVO
 *@description: 企业微信部门数据同步
 *@author: what
 *@date: 2022/4/21 16:30
 *@version: v1.0
 */
public class WeXinoOrgVO implements Serializable {

    private static final long serialVersionUID = 1L;

    //部门名称
    private String orgName;
    
    //上级部门id
    private Long parentId;
    
    //部门排序
    private Integer orgOrder;
    
    //部门id
    private Long orgId;

}

封装接口(增删改)

/**
 * @description: 微信接口对接
 * @author: what
 * @create: 2021-09-22 10:13
 **/
public interface WxService {

    /**
     * 添加微信用户
     *
     * @author: what
     */
    boolean createWxUser(WeXinUserVO weXinUserVO);

    /**
     * 修改微信用户
     *
     * @author: what
     */
    boolean updateWxUser(WeXinUserVO weXinUserVO);

    /**
     * 删除微信用户
     *
     * @author: what
     */
    boolean deleteWxUser(WeXinDeleteUserVO weXinDeleteUserVO);


    /**
     * 添加微信部门
     *
     * @author: what
     */
    boolean createWxOrg(WeXinoOrgVO weXinoOrgVO);


    /**
     * 修改微信部门
     *
     * @author: what
     */
    boolean updateWxOrg(WeXinoOrgVO weXinoOrgVO);


    /**
     * 删除微信部门
     *
     * @author: what
     */
    boolean deleteWxOrg(Integer orgId);

}

实现类

	//这里以添加用户实现类为例,其余以此内推

    /**
     * 添加微信用户
     *
     * @author: what
     */
    @Override
    public boolean createWxUser(WeXinUserVO weXinUserVO) {
        boolean flag = false;
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("userid", weXinUserVO.getUsername());
        jsonBody.put("name", weXinUserVO.getRealname());
        jsonBody.put("mobile", weXinUserVO.getTel());
        jsonBody.put("department", weXinUserVO.getDepartmentList());
        if(StringUtils.isNotBlank(weXinUserVO.getGender())){
            jsonBody.put("gender", weXinUserVO.getGender());
        }
        if(StringUtils.isNotBlank(weXinUserVO.getDutyName())){
            jsonBody.put("position", weXinUserVO.getDutyName());
        }
        if(StringUtils.isNotBlank(weXinUserVO.getEmail())){
            jsonBody.put("email", weXinUserVO.getEmail());
        }
        if(StringUtils.isNotBlank(weXinUserVO.getFixedTelephone())){
            jsonBody.put("telephone", weXinUserVO.getFixedTelephone());
        }
        if(weXinUserVO.getMainOrgId() != null){
            jsonBody.put("main_department", weXinUserVO.getMainOrgId());
        }

        String params = jsonBody.toJSONString();
        log.info("添加微信用户参数---------" + params);
        String url = HTTP_URL_CREATE_USER + getWxToken();
        String res = sendPost(url,params);
        JSONObject jsonObject = JSONObject.parseObject(res);
        Integer errCode = jsonObject.getInteger(ERR_CODE);
        if (errCode == 0) {
            flag = true;
        }
        return flag;
    }

封装http请求


    /**
     * 发送post请求
     *
     * @author: what
     */
    @Override
    public String sendPost(String url,String params) {
        String body = null;
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            // 获得Http客户端
            client = HttpClients.createDefault();

            //装填参数
            StringEntity se = new StringEntity(params, "utf-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            //设置参数到请求对象中
            httpPost.setEntity(se);
            httpPost.setHeader("Content-type", "application/json");

            // 这里根据实际情况看是否需要代理,生产环境如果可以直接访问互联网则忽略此配置
            if (useProxy) {
                //设置代理IP、端口
                HttpHost proxy = new HttpHost(wechatProxy, Integer.parseInt(wechatPort), "http");
                RequestConfig requestConfig= RequestConfig.custom().setProxy(proxy).build();
                httpPost.setConfig(requestConfig);
                log.info("使用代理-{}:{},访问接口-{}", wechatProxy, wechatPort, url);
            }
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "utf-8");
            }
            if(StringUtils.isNotBlank(body)){
                JSONObject jsonObject = JSONObject.parseObject(body);
                // 记录日志:企业微信返回信息
                log.info("weixin response:{}", jsonObject);
                Integer errCode = jsonObject.getInteger(ERR_CODE);
                String errMsg = jsonObject.getString(ERR_MSG);
                // 判断返回值是否正确
                if (ObjectUtil.isNotNull(errCode) && 0 != errCode) {
                    log.error("企业微信接口调用失败POST-{},访问接口-{}",errMsg,url);
                    throw new UserException(UserException.ErrCode.WX_REQUEST_ERROR_800);
                }
            }

        } catch (Exception e) {
            throw new UserException(UserException.ErrCode.WX_REQUEST_ERROR_800);
        } finally {
            try {
                if(client != null){
                    client.close();
                }
                if(response != null){
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return body;
    }

main本地测试下

注意执行本地main方法之前,需要在企业微信端配置通讯录ip白名单,就是你自己电脑的ip地址,否则会报错没有权限访问

    public static void main(String[] args) {

        List<Integer> objList = new ArrayList<>();
        //部门编号,这个编号必须在企业微信端存在,否则添加会报错
        objList.add(440100);
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("userid", "18500324411");
        jsonBody.put("name", "珍黛金");
        jsonBody.put("mobile", "18500324411");
        jsonBody.put("department", objList);

        JSONObject jsonBody2 = new JSONObject();
        jsonBody2.put("name", "test部门66677");
        jsonBody2.put("parentid", 440100);
        jsonBody2.put("order", 666);
        jsonBody2.put("id", 44010001);

        String params = jsonBody.toJSONString();
        String params2 = jsonBody2.toJSONString();
        try {
            String a = sendPost(params);
            String b = sendPost(params2);
            System.out.println(a);
            System.out.println(b);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

main 方法执行成功后会返回success或者失败,去企业微信页面刷新 下看是否添加成功。就可以把代码加到具体的业务逻辑中进行测试,还是很简单的,照着写基本没有什么问题,用户修改删除,部门的增删改逻辑都一样

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

珍妮玛•黛金

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值