企业微信 API 接口调用教程:从入门到精通

本文通过 access_token 凭证的方式来讲解怎么调用 企业微信 API,并一步步介绍如何获取企业微信 API 的 corpsecret、corpid、access_token 凭证以及怎么向企业微信的应用发送消息。 企业微信 API 在线地址为:https://qiyeweixin.apifox.cn/ ,这个在线地址的项目你可以克隆到 Apifox,以方便调试。话不多说,下面进入实操。

企业微信添加自建应用
1、如果你是企业微信的企业管理员,点击 “管理企业” 进入企业微信后台(不同版本可能不一样)

2、然后在 “应用管理” 下方,选择 “创建应用”

3、填写应用相关信息

4、创建成功后,即可看到 Secret 的信息,这个 Secret 就是等会儿要用的 corpsecret。

5、获取 corpid, 点击 “我的企业” 即可看到企业 ID ,这个企业 ID 就是 corpid。

企业微信获取 access_token 凭证
为方便企业微信 API 的调试,下面使用 Apifox 获取 access_token 凭证。企业微信 API 的 access_token 是应用调用 api 的凭证,由 corpid 和 corpsecret 换取。
请求方式: GET(HTTPS)
请求 URL: https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET
使用 Apifox 发送 GET 请求即可得到 access_token(请把截图中的 corpid、corpsecret 换为自己的 corpid(企业 ID)、应用 secret)。企业微信 API 在线地址为:https://qiyeweixin.apifox.cn/ ,这个在线地址的项目你可以克隆到 Apifox,以方便调试。

企业微信发送应用消息
企业微信的应用支持推送文本、图片、视频、文件、图文等类型。
请求方式: POST(HTTPS)
请求地址: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
企业微信的 touser
获取 touser,通讯录列表的成员账号就是 touser。

企业微信的 agentid
每个应用都有唯一的 agentid。在“管理后台”->“应用管理”->“应用”,点进某个应用,即可看到 agentid。

构造消息体
可以发送文本、图片、视频等多种类型的应用消息,这里以最简单的文本消息为例:(注意修改 touser、agentid 为自己想要的接收者 userid 列表、应用 id)
发送消息
如下图示,有了 access_token、touser、agentid 和消息体,在 Apifox 中发送 post 请求即可(红色箭头所指为需要注意的点)

如果报错返回"errcode": 60020
,那么你需要配置可信任域名。在“应用管理”->“企业可信 IP”下配置即可。这里需要你下载WW_verify_7x7IN1QfqcsOLA6J.txt
文件,并将其放到域名的根目录下,然后验证。

响应成功
如下图所示,在企业微信里,成功响应了消息回来。

使用 Apifox 调试、管理接口
Apifox 是一个比 Postman 更强大的接口测试工具,Apifox = Postman + Swagger + Mock + JMeter,Apifox 支持调试 http (s)、WebSocket、Socket、gRPC、Dubbo 等协议的接口,并且集成了 IDEA 插件。在开发完接口后,可以通过 Apifox 的 IDEA 插件一键生成接口文档,多端同步,非常方便测试和维护。


评论