企业微信开发之通讯录同步

前言:

本文主要是用来拉取企业微信用户数据,企业微信有人员变更等参考我的另一篇文章

目录

开发文档:http://work.weixin.qq.com/api/doc#10093

步骤:

第一步:  后台管理界面开启通讯录同步

第二步.     AccessTokenController 编写接口,直接在网页上访问这个接口

第三步     CommonServiceImpl 类

第四步:  ContactsDepartmentService

第五步:  我的用户表(用来保存用户信息到数据库中)

第六步:   QiWeiXinParamesUtil

                 SendRequest




开发文档:http://work.weixin.qq.com/api/doc#10093

步骤:

第一步:  后台管理界面开启通讯录同步

 

第二步.  AccessTokenController 编写接口,直接在网页上访问这个接口

引入maven(补充说明)

 


        <!-- lombok start -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
        <!-- lombok end -->

         <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180130</version>
        </dependency>
    @ApiOperation(value = "1.2 第一次拉取企业微信数据需要调用此接口")
    @RequestMapping(value = "/getUser")
    public void getUser() {
        commonService.insertBosPositionData();
    }

第三步 CommonServiceImpl类

 /**
     * 将数据保存到数据库中(BosPosition)
     *
     * @param
     * @return
     */
    @Override
    public void insertBosPositionData() {
       
        try {
            //1查询出access_Token的值
            String accessToken = QiWeiXinParamesUtil.getAccessToken("department");
            //获取用户信息
            getAllQiYeUser(accessToken);
            //获取部门列表信息(不填则是查询出所有的部门列表)
            List<String> depts = contactsDepartmentService.getDepartmentList(accessToken, "");
            //根据部门信息去获取成员的详细信息(查询到的数据)
            getDepartmentUserDetails(depts, accessToken, "1");
          
        } catch (Exception e) {
        
            logger.error("数据保存失败!", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
       }
 /**
     * 功能描述: 手动获取企业微信人员信息
     *
     * @param accessToken
     */
    private void getAllQiYeUser(String accessToken) {
        List<BosUserModel> users = new ArrayList<BosUserModel>();
        List<BosUserModel> removeBosUserList = new ArrayList<BosUserModel>();
      
        //--拉取企业微信所有人员信息
        String url = QiWeiXinParamesUtil.getUser_url.replace("{access_token}", accessToken);
        JSONObject jsonObject = SendRequest.sendGet(url);
        JSONArray array = jsonObject.getJSONArray("userlist");
        if (null != array) {
            for (int i = 0; i < array.size(); i++) {
                JSONObject detailJsonObject = array.getJSONObject(i);
                //用户名
                String name = detailJsonObject.getString("name");
                //用户id
                String userId = detailJsonObject.getString("userid");
                //部门信息
                String department = detailJsonObject.getString("department");
                //去掉部门id中的[]
                String splitDepartment = department.substring(department.indexOf("[") + 1, department.indexOf("]"));
                BosUserModel userModel = bosUserJPARepositoty.findBosUserModelByUserId(userId);
                //如果当前系统包含这个拉取得数据,则修改原有用户数据信息
                removeBosUserList.remove(userModel);
                if (userModel != null) {
                    //这个方法是排除一些用户并非在企业微信里面,而是手动添加的
                    if (!Strings.isNullOrEmpty(userId)) {
                        userModel.setUserId(userId);
                    }
                    //部门id
                    userModel.setDepartment(splitDepartment);
                    userModel.setName(name);
                    //部门名称(当前用户有部门的时候添加部门)
                    if (!Strings.isNullOrEmpty(splitDepartment)) {
                        StringBuffer sb = new StringBuffer();
                        String[] splitDepartments = splitDepartment.split(",");
                        List<Integer> ids = new ArrayList<>();
                        for (int j = 0; j < splitDepartments.length; j++) {
                            ids.add(Integer.parseInt(splitDepartments[j]));
                        }
                        //List<DepartmentModel> departmentModels = departmentJPARepository.findDepartmentModelById(ids);
                        //for (int j = 0; j < departmentModels.size(); j++) {
                            //if (departmentModels.size() > 1 && j != departmentModels.size() - 1) {
                                //sb.append(departmentModels.get(j).getName() + ",");
                            //} else {
                             //   sb.append(departmentModels.get(j).getName());
                            //}
                        //}
                        //userModel.setDepartmentName(sb.toString());
                    }
                    //最后将user放到list中去
                    users.add(userModel);
                } else {
                    //拉取过来的数据有新成员则新增
                    BosUserModel newUserModel = new BosUserModel();
                    newUserModel.setUserId(userId);
                    newUserModel.setUserDataSource("企业微信调用");
                    newUserModel.setDepartment(department);
                    newUserModel.setName(name);
                    //利用shiro对密码进行MD5加密
                    String pwd = "123456";
                    newUserModel.setPassword(pwd);
                    //最后将user放到list中去
                    users.add(newUserModel);
                }

            }
            //将所有离职人员信息删除
            for (int j = 0; j < removeBosUserList.size(); j++) {
                BosUserModel removeBosUserModel = removeBosUserList.get(j);
                if (!removeBosUserModel.getUserDataSource().equals("自助添加")) {
                    bosUserJPARepositoty.deleteBosUserModelById(removeBosUserModel.getId());
                }
          
                }
            }
            bosUserJPARepositoty.saveAll(users);
        }
    }

附加:CommonService

 /**
     * 获取所有的企业联系人
     * @return
     */
    void getAllUser();

 

第四步:ContactsDepartmentService

 /**
     * 功能描述: 拉取具体各个部门人员在企业微信中的角色
     */
    @Override
    public void getDepartmentUserDetails(List<String> depts, String accessToken, String fetchChild) {
        //1.循环所有部门
        for (int j = 0; j < depts.size(); j++) {
            String deptId = depts.get(j);
            String str = QiWeiXinParamesUtil.getDepartmentUserDetailsUrl.replace("ACCESS_TOKEN", accessToken).replace("DEPARTMENT_ID", deptId).replace("FETCH_CHILD", fetchChild);
            JSONObject jsonObject = SendRequest.sendGet(str);
            if (null != jsonObject) {
                //查询结果为true
                if (jsonObject.getString("errmsg").equals("ok")) {
                    JSONArray array = jsonObject.getJSONArray("userlist");
                    if (null != array) {
                        for (int i = 0; i < array.size(); i++) {
                            JSONObject deptJsonObject = array.getJSONObject(i);
                            //getQiYeMemberToPosition(deptJsonObject, deptId);
                        }
                    }
                } else {
                    logger.error("获取部门成员详情失败 errcode:{} errmsg:{}", jsonObject.getString("errmsg"));
                }
            }
        }
    }

 

第五步:我的用户表(用来保存用户信息到数据库中)

package com.bos.data.model;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Objects;
/**
    用户表
 * @Author: tanghh18
 */
@Entity
@Table(name = "bos_user", schema = "test3", catalog = "")
public @Data class BosUserModel implements Serializable {

    private Integer id;
    private Integer parentId;
    private String userId;
    private String name;
    private String adName;
    private String openId;
    private String nickName;
    private String password;
    private String mobile;
    private Integer power;
    private String department;
    private String email;
    private String position;
    private String gender;
    private String status;
    private String entryTime;
    private String zhanghao;
    private String avatar;
    private String groupId;
    private String loginType;
    private String departmentName;
    private String loginStatus;
    private Integer IMLoginStatus;
    //im未读消息数量
    private Integer IMMessageNumber;
    private String rank;
    private String isDel="0";
    private Timestamp updateTime;
    private String userDataSource;
    private String post;
    private String centralizedBusinessUnit1;
    private String centralizedBusinessUnit2;
    private String centralizedBusinessUnit3;
    private String centralizedBusinessType1;
    private String centralizedBusinessType2;
    private String centralizedBusinessType3;
    private String idNumber;
    private String bornDate;
    private String majorStudied;
    private String highestAcademic;
    private String professionalLevel;
    private String graduationTime;
    private String workingLife;
    private String dateEntry;
    private String workingDays;
    private String workingMonths;
    private String workingYears;
    private String eboPermissions;
    private String woringGroup;
    private String responsibilityContent;
    private String phoneCompany;
    private String teamWorkRole;
    private String teamTechnologyMajor;
    private String openingBank;
    private String bankCardNumber;
    private String isMarry;
    private Timestamp createTime;
    private String entryCompany;
    private String yearsLaborContract;
    private String richTextResponsibilities;
    private String richTextAssessment;
    private String teamManagementLevel;
    private String eboSystemRole;
    private String superior;
    private String managementSupervisor;
    private Integer ocompile;
    private Integer odelete;
    private String age;
    private String sex;
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Basic
    @Column(name = "parent_id")
    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    @Basic
    @Column(name = "userId")
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "ad_name")
    public String getAdName() {
        return adName;
    }

    public void setAdName(String adName) {
        this.adName = adName;
    }

    @Basic
    @Column(name = "password")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "mobile")
    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    @Basic
    @Column(name = "power")
    public Integer getPower() {
        return power;
    }

    public void setPower(Integer power) {
        this.power = power;
    }

    @Basic
    @Column(name = "department")
    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Basic
    @Column(name = "email")
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Basic
    @Column(name = "position")
    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "status")
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Basic
    @Column(name = "entryTime")
    public String getEntryTime() {
        return entryTime;
    }

    public void setEntryTime(String entryTime) {
        this.entryTime = entryTime;
    }

    @Basic
    @Column(name = "zhanghao")
    public String getZhanghao() {
        return zhanghao;
    }

    public void setZhanghao(String zhanghao) {
        this.zhanghao = zhanghao;
    }

    @Basic
    @Column(name = "avatar")
    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    @Basic
    @Column(name = "group_id")
    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    @Basic
    @Column(name = "login_type")
    public String getLoginType() {
        return loginType;
    }

    public void setLoginType(String loginType) {
        this.loginType = loginType;
    }

    @Basic
    @Column(name = "department_name")
    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    @Basic
    @Column(name = "login_status")
    public String getLoginStatus() {
        return loginStatus;
    }

    public void setLoginStatus(String loginStatus) {
        this.loginStatus = loginStatus;
    }

    @Basic
    @Column(name = "im_message_number")
    public Integer getIMMessageNumber() {
        return IMMessageNumber;
    }

    public void setIMMessageNumber(Integer IMMessageNumber) {
        this.IMMessageNumber = IMMessageNumber;
    }

    @Basic
    @Column(name = "im_login_status")
    public Integer getIMLoginStatus() {
        return IMLoginStatus;
    }

    public void setIMLoginStatus(Integer IMLoginStatus) {
        this.IMLoginStatus = IMLoginStatus;
    }

    @Basic
    @Column(name = "rank")
    public String getRank() {
        return rank;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    @Basic
    @Column(name = "is_del")
    public String getIsDel() {
        return isDel;
    }

    public void setIsDel(String isDel) {
        this.isDel = isDel;
    }

    @Basic
    @Column(name = "update_time")
    public Timestamp getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Timestamp updateTime) {
        this.updateTime = updateTime;
    }

    @Basic
    @Column(name = "user_data_source")
    public String getUserDataSource() {
        return userDataSource;
    }

    public void setUserDataSource(String userDataSource) {
        this.userDataSource = userDataSource;
    }

    @Basic
    @Column(name = "post")
    public String getPost() {
        return post;
    }

    public void setPost(String post) {
        this.post = post;
    }

    @Basic
    @Column(name = "centralized_business_unit1")
    public String getCentralizedBusinessUnit1() {
        return centralizedBusinessUnit1;
    }

    public void setCentralizedBusinessUnit1(String centralizedBusinessUnit1) {
        this.centralizedBusinessUnit1 = centralizedBusinessUnit1;
    }

    @Basic
    @Column(name = "centralized_business_unit2")
    public String getCentralizedBusinessUnit2() {
        return centralizedBusinessUnit2;
    }

    public void setCentralizedBusinessUnit2(String centralizedBusinessUnit2) {
        this.centralizedBusinessUnit2 = centralizedBusinessUnit2;
    }

    @Basic
    @Column(name = "centralized_business_unit3")
    public String getCentralizedBusinessUnit3() {
        return centralizedBusinessUnit3;
    }

    public void setCentralizedBusinessUnit3(String centralizedBusinessUnit3) {
        this.centralizedBusinessUnit3 = centralizedBusinessUnit3;
    }

    @Basic
    @Column(name = "centralized_business_type1")
    public String getCentralizedBusinessType1() {
        return centralizedBusinessType1;
    }

    public void setCentralizedBusinessType1(String centralizedBusinessType1) {
        this.centralizedBusinessType1 = centralizedBusinessType1;
    }

    @Basic
    @Column(name = "centralized_business_type2")
    public String getCentralizedBusinessType2() {
        return centralizedBusinessType2;
    }

    public void setCentralizedBusinessType2(String centralizedBusinessType2) {
        this.centralizedBusinessType2 = centralizedBusinessType2;
    }

    @Basic
    @Column(name = "centralized_business_type3")
    public String getCentralizedBusinessType3() {
        return centralizedBusinessType3;
    }

    public void setCentralizedBusinessType3(String centralizedBusinessType3) {
        this.centralizedBusinessType3 = centralizedBusinessType3;
    }

    @Basic
    @Column(name = "id_number")
    public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    @Basic
    @Column(name = "born_date")
    public String getBornDate() {
        return bornDate;
    }

    public void setBornDate(String bornDate) {
        this.bornDate = bornDate;
    }

    @Basic
    @Column(name = "major_studied")
    public String getMajorStudied() {
        return majorStudied;
    }

    public void setMajorStudied(String majorStudied) {
        this.majorStudied = majorStudied;
    }

    @Basic
    @Column(name = "highest_academic")
    public String getHighestAcademic() {
        return highestAcademic;
    }

    public void setHighestAcademic(String highestAcademic) {
        this.highestAcademic = highestAcademic;
    }

    @Basic
    @Column(name = "professional_level")
    public String getProfessionalLevel() {
        return professionalLevel;
    }

    public void setProfessionalLevel(String professionalLevel) {
        this.professionalLevel = professionalLevel;
    }

    @Basic
    @Column(name = "graduation_time")
    public String getGraduationTime() {
        return graduationTime;
    }

    public void setGraduationTime(String graduationTime) {
        this.graduationTime = graduationTime;
    }

    @Basic
    @Column(name = "working_life")
    public String getWorkingLife() {
        return workingLife;
    }

    public void setWorkingLife(String workingLife) {
        this.workingLife = workingLife;
    }

    @Basic
    @Column(name = "date_entry")
    public String getDateEntry() {
        return dateEntry;
    }

    public void setDateEntry(String dateEntry) {
        this.dateEntry = dateEntry;
    }

    @Basic
    @Column(name = "working_days")
    public String getWorkingDays() {
        return workingDays;
    }

    public void setWorkingDays(String workingDays) {
        this.workingDays = workingDays;
    }

    @Basic
    @Column(name = "working_months")
    public String getWorkingMonths() {
        return workingMonths;
    }

    public void setWorkingMonths(String workingMonths) {
        this.workingMonths = workingMonths;
    }

    @Basic
    @Column(name = "working_years")
    public String getWorkingYears() {
        return workingYears;
    }

    public void setWorkingYears(String workingYears) {
        this.workingYears = workingYears;
    }

    @Basic
    @Column(name = "ebo_permissions")
    public String getEboPermissions() {
        return eboPermissions;
    }

    public void setEboPermissions(String eboPermissions) {
        this.eboPermissions = eboPermissions;
    }

    @Basic
    @Column(name = "woring_group")
    public String getWoringGroup() {
        return woringGroup;
    }

    public void setWoringGroup(String woringGroup) {
        this.woringGroup = woringGroup;
    }

    @Basic
    @Column(name = "responsibility_content")
    public String getResponsibilityContent() {
        return responsibilityContent;
    }

    public void setResponsibilityContent(String responsibilityContent) {
        this.responsibilityContent = responsibilityContent;
    }

    @Basic
    @Column(name = "phone_company")
    public String getPhoneCompany() {
        return phoneCompany;
    }

    public void setPhoneCompany(String phoneCompany) {
        this.phoneCompany = phoneCompany;
    }

    @Basic
    @Column(name = "team_work_role")
    public String getTeamWorkRole() {
        return teamWorkRole;
    }

    public void setTeamWorkRole(String teamWorkRole) {
        this.teamWorkRole = teamWorkRole;
    }

    @Basic
    @Column(name = "team_technology_major")
    public String getTeamTechnologyMajor() {
        return teamTechnologyMajor;
    }

    public void setTeamTechnologyMajor(String teamTechnologyMajor) {
        this.teamTechnologyMajor = teamTechnologyMajor;
    }

    @Basic
    @Column(name = "opening_bank")
    public String getOpeningBank() {
        return openingBank;
    }

    public void setOpeningBank(String openingBank) {
        this.openingBank = openingBank;
    }

    @Basic
    @Column(name = "bank_card_number")
    public String getBankCardNumber() {
        return bankCardNumber;
    }

    public void setBankCardNumber(String bankCardNumber) {
        this.bankCardNumber = bankCardNumber;
    }

    @Basic
    @Column(name = "is_marry")
    public String getIsMarry() {
        return isMarry;
    }

    public void setIsMarry(String isMarry) {
        this.isMarry = isMarry;
    }

    @Basic
    @Column(name = "create_time")
    public Timestamp getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }

    @Basic
    @Column(name = "entry_company")
    public String getEntryCompany() {
        return entryCompany;
    }

    public void setEntryCompany(String entryCompany) {
        this.entryCompany = entryCompany;
    }

    @Basic
    @Column(name = "years_labor_contract")
    public String getYearsLaborContract() {
        return yearsLaborContract;
    }

    public void setYearsLaborContract(String yearsLaborContract) {
        this.yearsLaborContract = yearsLaborContract;
    }

    @Basic
    @Column(name = "rich_text_responsibilities")
    public String getRichTextResponsibilities() {
        return richTextResponsibilities;
    }

    public void setRichTextResponsibilities(String richTextResponsibilities) {
        this.richTextResponsibilities = richTextResponsibilities;
    }

    @Basic
    @Column(name = "rich_text_assessment")
    public String getRichTextAssessment() {
        return richTextAssessment;
    }

    public void setRichTextAssessment(String richTextAssessment) {
        this.richTextAssessment = richTextAssessment;
    }

    @Basic
    @Column(name = "team_management_level")
    public String getTeamManagementLevel() {
        return teamManagementLevel;
    }

    public void setTeamManagementLevel(String teamManagementLevel) {
        this.teamManagementLevel = teamManagementLevel;
    }

    @Basic
    @Column(name = "ebo_system_role")
    public String getEboSystemRole() {
        return eboSystemRole;
    }

    public void setEboSystemRole(String eboSystemRole) {
        this.eboSystemRole = eboSystemRole;
    }

    @Basic
    @Column(name = "superior")
    public String getSuperior() {
        return superior;
    }

    public void setSuperior(String superior) {
        this.superior = superior;
    }

    @Basic
    @Column(name = "ocompile")
    public Integer getOcompile() {
        return ocompile;
    }

    public void setOcompile(Integer ocompile) {
        this.ocompile = ocompile;
    }

    @Basic
    @Column(name = "odelete")
    public Integer getOdelete() {
        return odelete;
    }

    public void setOdelete(Integer odelete) {
        this.odelete = odelete;
    }



    @Basic
    @Column(name = "age")
    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }



    @Basic
    @Column(name = "sex")
    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    @Basic
    @Column(name = "management_supervisor")
    public String getManagementSupervisor() {
        return managementSupervisor;
    }

    public void setManagementSupervisor(String managementSupervisor) {
        this.managementSupervisor = managementSupervisor;
    }
    @Basic
    @Column(name = "open_id")
    public String getOpenId() {
        return openId;
    }

    public void setOpenId(String openId) {
        this.openId = openId;
    }
    @Basic
    @Column(name = "nick_name")
    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BosUserModel that = (BosUserModel) o;
        return id == that.id &&
                Objects.equals(parentId, that.parentId) &&
                Objects.equals(userId, that.userId) &&
                Objects.equals(name, that.name) &&
                Objects.equals(adName, that.adName) &&
                Objects.equals(password, that.password) &&
                Objects.equals(mobile, that.mobile) &&
                Objects.equals(power, that.power) &&
                Objects.equals(department, that.department) &&
                Objects.equals(email, that.email) &&
                Objects.equals(position, that.position) &&
                Objects.equals(gender, that.gender) &&
                Objects.equals(status, that.status) &&
                Objects.equals(entryTime, that.entryTime) &&
                Objects.equals(zhanghao, that.zhanghao) &&
                Objects.equals(avatar, that.avatar) &&
                Objects.equals(groupId, that.groupId) &&
                Objects.equals(loginType, that.loginType) &&
                Objects.equals(departmentName, that.departmentName) &&
                Objects.equals(loginStatus, that.loginStatus) &&
                Objects.equals(rank, that.rank) &&
                Objects.equals(isDel, that.isDel) &&
                Objects.equals(updateTime, that.updateTime) &&
                Objects.equals(userDataSource, that.userDataSource) &&
                Objects.equals(post, that.post) &&
                Objects.equals(centralizedBusinessUnit1, that.centralizedBusinessUnit1) &&
                Objects.equals(centralizedBusinessUnit2, that.centralizedBusinessUnit2) &&
                Objects.equals(centralizedBusinessUnit3, that.centralizedBusinessUnit3) &&
                Objects.equals(centralizedBusinessType1, that.centralizedBusinessType1) &&
                Objects.equals(centralizedBusinessType2, that.centralizedBusinessType2) &&
                Objects.equals(centralizedBusinessType3, that.centralizedBusinessType3) &&
                Objects.equals(idNumber, that.idNumber) &&
                Objects.equals(bornDate, that.bornDate) &&
                Objects.equals(majorStudied, that.majorStudied) &&
                Objects.equals(highestAcademic, that.highestAcademic) &&
                Objects.equals(professionalLevel, that.professionalLevel) &&
                Objects.equals(graduationTime, that.graduationTime) &&
                Objects.equals(workingLife, that.workingLife) &&
                Objects.equals(dateEntry, that.dateEntry) &&
                Objects.equals(workingDays, that.workingDays) &&
                Objects.equals(workingMonths, that.workingMonths) &&
                Objects.equals(workingYears, that.workingYears) &&
                Objects.equals(eboPermissions, that.eboPermissions) &&
                Objects.equals(woringGroup, that.woringGroup) &&
                Objects.equals(responsibilityContent, that.responsibilityContent) &&
                Objects.equals(phoneCompany, that.phoneCompany) &&
                Objects.equals(teamWorkRole, that.teamWorkRole) &&
                Objects.equals(teamTechnologyMajor, that.teamTechnologyMajor) &&
                Objects.equals(openingBank, that.openingBank) &&
                Objects.equals(bankCardNumber, that.bankCardNumber) &&
                Objects.equals(isMarry, that.isMarry) &&
                Objects.equals(createTime, that.createTime) &&
                Objects.equals(entryCompany, that.entryCompany) &&
                Objects.equals(yearsLaborContract, that.yearsLaborContract) &&
                Objects.equals(richTextResponsibilities, that.richTextResponsibilities) &&
                Objects.equals(richTextAssessment, that.richTextAssessment) &&
                Objects.equals(teamManagementLevel, that.teamManagementLevel) &&
                Objects.equals(eboSystemRole, that.eboSystemRole) &&
                Objects.equals(superior, that.superior) &&
                Objects.equals(ocompile, that.ocompile) &&
                Objects.equals(odelete, that.odelete);
    }

    @Override
    public int hashCode() {

        return Objects.hash(id, parentId, userId, name, adName, password, mobile, power, department, email, position, gender, status, entryTime, zhanghao, avatar, groupId, loginType, departmentName, loginStatus, rank, isDel, updateTime, userDataSource, post, centralizedBusinessUnit1, centralizedBusinessUnit2, centralizedBusinessUnit3, centralizedBusinessType1, centralizedBusinessType2, centralizedBusinessType3, idNumber, bornDate, majorStudied, highestAcademic, professionalLevel, graduationTime, workingLife, dateEntry, workingDays, workingMonths, workingYears, eboPermissions, woringGroup, responsibilityContent, phoneCompany, teamWorkRole, teamTechnologyMajor, openingBank, bankCardNumber, isMarry, createTime, entryCompany, yearsLaborContract, richTextResponsibilities, richTextAssessment, teamManagementLevel, eboSystemRole, superior, ocompile, odelete);
    }
}

企业微信通讯录同步就做好了,其中一些类和我上一篇发表的扫码登陆中的类一样。

第六步:QiWeiXinParamesUtil

    /**
     * 获取access_token的url
     */
    public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}";

    public static String getDepartmentUserDetailsUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD";

    /**
     * 查出企业微信通讯录中所有成员(DEPARTMENT_ID==1 && FETCH_CHILD==1)
     */
    public static String getUser_url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={access_token}&department_id=1&fetch_child=1";

 private  static  String getDepartmentList_url="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=ID"; 
 /**
     * 获得各种access_token
     *
     * @param type
     * @return
     */
    public static String getAccessToken(String type) {
        String url = "";
        if ("department".equals(type)) {
            url = access_token_url.replace("{corpId}", corpId).replace("{corpsecret}", contactsSecret);
        } 
        JSONObject departmentJson = SendRequest.sendGet(url);
        return departmentJson.getString("access_token");
    }

SendRequest

 /**
     * 发送GET请求
     * @param url
     * @return
     */
    public static JSONObject sendGet(String url) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        JSONObject jsonObject = null;
        StringBuffer sb = new StringBuffer();
        BufferedReader in = null;
        try {
            String urlName = url;
            URL realUrl = new URL(urlName);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            //针对群晖NAS请求,加一个Cookie
            if (session.getAttribute("sid") != null) {
                conn.addRequestProperty("Cookie", "id=" + session.getAttribute("sid"));
            }
            conn.setConnectTimeout(10000);
            // 建立实际的连接
            conn.connect();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            jsonObject = JSON.parseObject(sb.toString());
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
        } finally {
            // 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return jsonObject;
    }

 

  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值