下面我就以同步企业微信通讯录为例演示一下整个流程

1.创建企业微信账号

这一步就不演示了

2.获取access_token

获取access_token是调用企业微信API接口的第一步,相当于创建了一个登录凭证,其它的业务API接口,都需要依赖于access_token来鉴权调用者身份。
因此开发者,在使用业务接口前,要明确access_token的颁发来源,使用正确的access_token。

请求方式: GET(HTTPS)

请求地址: https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET

注:此处标注大写的单词ID和SECRET,为需要替换的变量,根据实际获取值更新。其它接口也采用相同的标注,不再说明。

参数

必须

说明

corpid


企业ID

corpsecret


应用的凭证密钥

2.1 corpid :

企业微信群如何对接Java 企业微信接口对接_微信

2.2 corpsecret:

corpsecret是根据你具体需要干什么来给的,比如你要同步企业微信的通讯录那就需要拿同步通讯录的secret,如果你要用某个应用的功能则需要取这个应用的secret。

比如我们拿同步通讯录的secret:

企业微信群如何对接Java 企业微信接口对接_微信_02


企业微信群如何对接Java 企业微信接口对接_微信_03

权限说明:

每个应用有独立的secret,获取到的access_token只能本应用使用,所以每个应用的access_token应该分开来获取

返回结果:

{
   "errcode": 0,
   "errmsg": "ok",
   "access_token": "accesstoken000001",
   "expires_in": 7200
}

参数说明:

参数

说明

errcode

出错返回码,为0表示成功,非0表示调用失败

errmsg

返回码提示语

access_token

获取到的凭证,最长为512字节

expires_in

凭证的有效时间(秒)

注意事项:

不能频繁调用gettoken接口,否则会受到频率拦截
有效期正常情况下为7200秒(2小时),有效期内重复获取返回相同结果,过期后获取会返回新的access_token。

3.调用相关接口

刚才我们已经拿到了通讯录同步相关接口的access_token,现在可以开始调用它的一些接口了。

3.1打开API文档

打开之后找到“通讯录管理”,在概述里详细的说了通讯录同步的一些事项。

企业微信群如何对接Java 企业微信接口对接_微信_04

3.2发起请求

以创建成员为例

企业微信群如何对接Java 企业微信接口对接_javascript_05


按照微信提供的请求方式、请求地址、请求包体发起请求就可以了。

需要注意的是请求地址最后的access_token的有效期。

完整实例:
下面写一下完整实例,并且会有一个方法来保证access_token一直在有效期内。
下面代码中的请求可能存在跨域的问题,这里只做示范,具体请求就不演示了。如果你只想试试玩,你可以直接打开请求的链接在链接的页面中f12控制台中输入这些代码。

定义全局变量

//登录凭证
let access_token
//记录access_token的上一次请求时间
let access_token_time

获取的access_token方法

//获取apaas应用的access_token(微信API)
async function get_access_token(corpid,corpsecret) {
  /*
  *  corpid:企业id
  *  corpsecret:应用的凭证密钥
  */
  //请求url
  let requestUrl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
  //当前时间
  let currentTime = new Date().getTime()
  //如果请求时间未定义,或者当前时间减去请求时间大于或等于7200毫秒则重新获取
  if (!access_token_time || currentTime - access_token_time >= 7200) {
	  access_token_time = new Date().getTime();
      let xhr = new XMLHttpRequest();
      xhr.open("get", requestUrl);
      xhr.send();
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
          //获取到的json数据
            let jsonData = xhr.responseText;
            //转换json数据,并重新赋值给全局变量access_token 
            access_token = JSON.parse(jsonData).access_token;
          }
        }
      };
  }
}

创建成员方法

function createMember() {
  //检查access_token是否过期
  await get_access_token(corpid, corpsecret)
  // 请求包体
  let body = {
    "userid": "zhangsan",
    "name": "张三",
    "alias": "jackzhang",
    "mobile": "+86 13800000000",
    "department": [1, 2],
    "order": [10, 40],
    "position": "产品经理",
    "gender": "1",
    "email": "zhangsan@gzdev.com",
    "is_leader_in_dept": [1, 0],
    "enable": 1,
    "avatar_mediaid": "2-G6nrLmr5EC3MNb_-zL1dDdzkd0p7cNliYu9V5w7o8K0",
    "telephone": "020-123456",
    "address": "广州市海珠区新港中路",
    "main_department": 1,
    "extattr": {
      "attrs": [
        {
          "type": 0,
          "name": "文本名称",
          "text": {
            "value": "文本"
          }
        },
        {
          "type": 1,
          "name": "网页名称",
          "web": {
            "url": "http://www.test.com",
            "title": "标题"
          }
        }
      ]
    },
    "to_invite": true,
    "external_position": "高级产品经理",
    "external_profile": {
      "external_corp_name": "企业简称",
      "external_attr": [
        {
          "type": 0,
          "name": "文本名称",
          "text": {
            "value": "文本"
          }
        },
        {
          "type": 1,
          "name": "网页名称",
          "web": {
            "url": "http://www.test.com",
            "title": "标题"
          }
        },
        {
          "type": 2,
          "name": "测试app",
          "miniprogram": {
            "appid": "wx8bd8012614784fake",
            "pagepath": "/index",
            "title": "my miniprogram"
          }
        }
      ]
    }
  }
  // 请求地址
  let url = 'https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=' + access_token
  //发送请求
  let xhr = new XMLHttpRequest()
  xhr.open('post', url)
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  xhr.send('query=4&em=0')
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        console.log(xhr.responseText);
      }
    }
  }
}

完整代码
在使用时就直接调用createMember创建成员

//登录凭证
let access_token
//记录access_token的上一次请求时间
let access_token_time 
//获取apaas应用的access_token(微信API)
async function get_access_token(corpid,corpsecret) {
  /*
  *  corpid:企业id
  *  corpsecret:应用的凭证密钥
  */
  //请求url
  let requestUrl = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret
  //当前时间
  let currentTime = new Date().getTime()
  //如果请求时间未定义,或者当前时间减去请求时间大于或等于7200毫秒则重新获取
  if (!access_token_time || currentTime - access_token_time >= 7200) {
	  access_token_time = new Date().getTime();
      let xhr = new XMLHttpRequest();
      xhr.open("get", requestUrl);
      xhr.send();
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
          //获取到的json数据
            let jsonData = xhr.responseText;
            //转换json数据,并重新赋值给全局变量access_token 
            access_token = JSON.parse(jsonData).access_token;
          }
        }
      };
  }
}
//创建成员
function createMember() {
  //检查access_token是否过期
  await get_access_token(corpid, corpsecret)
  // 请求包体
  let body = {
    "userid": "zhangsan",
    "name": "张三",
    "alias": "jackzhang",
    "mobile": "+86 13800000000",
    "department": [1, 2],
    "order": [10, 40],
    "position": "产品经理",
    "gender": "1",
    "email": "zhangsan@gzdev.com",
    "is_leader_in_dept": [1, 0],
    "enable": 1,
    "avatar_mediaid": "2-G6nrLmr5EC3MNb_-zL1dDdzkd0p7cNliYu9V5w7o8K0",
    "telephone": "020-123456",
    "address": "广州市海珠区新港中路",
    "main_department": 1,
    "extattr": {
      "attrs": [
        {
          "type": 0,
          "name": "文本名称",
          "text": {
            "value": "文本"
          }
        },
        {
          "type": 1,
          "name": "网页名称",
          "web": {
            "url": "http://www.test.com",
            "title": "标题"
          }
        }
      ]
    },
    "to_invite": true,
    "external_position": "高级产品经理",
    "external_profile": {
      "external_corp_name": "企业简称",
      "external_attr": [
        {
          "type": 0,
          "name": "文本名称",
          "text": {
            "value": "文本"
          }
        },
        {
          "type": 1,
          "name": "网页名称",
          "web": {
            "url": "http://www.test.com",
            "title": "标题"
          }
        },
        {
          "type": 2,
          "name": "测试app",
          "miniprogram": {
            "appid": "wx8bd8012614784fake",
            "pagepath": "/index",
            "title": "my miniprogram"
          }
        }
      ]
    }
  }
  // 请求地址
  let url = 'https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=' + access_token
  //发送请求
  let xhr = new XMLHttpRequest()
  xhr.open('post', url)
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  xhr.send('query=4&em=0')
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        console.log(xhr.responseText);
      }
    }
  }
}