PHP实现发送企业微信消息的完整指南**
在企业信息化和团队协作中,企业微信已成为不可或缺的工具,它不仅方便内部沟通,还能通过API接口实现与业务系统的深度集成,例如发送重要的通知、警报、报表等,本文将详细介绍如何使用PHP语言调用企业微信API,实现向企业微信应用或指定用户发送消息的功能。
准备工作:获取企业微信必要参数
在开始编写PHP代码之前,我们需要先获取一些关键参数,这些参数是企业微信认证我们身份和发送消息的凭证:
- 企业ID (CorpID):在企业微信管理后台获取,唯一标识你的企业。
- 应用的AgentId与Secret:
- 登录企业微信管理后台,进入“应用管理” -> “自建应用”,创建一个自建应用(或使用已有的应用)。
- 获取该应用的AgentId和Secret,Secret是调用应用接口的密钥,务必妥善保管。
- 接收人的用户ID (userid):在企业微信中,每个用户都有一个唯一的
userid,可以通过通讯录获取,或通过企业微信API同步获取,如果要发送给多个用户,用分隔,例如user1|user2。@all表示发送给所有人。 - 部门ID (partyid):可选,如果需要发送给整个部门,可以使用部门ID,多个部门用分隔。
核心原理:获取Access Token
调用企业微信绝大多数API接口,都需要一个Access Token作为凭证,Access Token具有时效性(通常为2小时,过期需重新获取),并且一个企业下的所有应用共享Access Token(但不同应用Secret不同,所以获取时需指定)。
获取Access Token的API地址为:
https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CorpID&corpsecret=Secret
其中CorpID和Secret就是我们在准备工作中获取的。
返回的JSON数据中,access_token字段就是我们需要的,expires_in字段表示有效期(秒)。
PHP实现发送消息
企业微信支持发送多种类型的消息,如文本、图片、文件、卡片、图文等,这里我们以最常用的文本消息为例,介绍PHP的实现方法。
获取Access Token的PHP函数
我们编写一个函数来获取Access Token:
<?php
/**
* 获取企业微信Access Token
* @param string $corpID 企业ID
* @param string $corpSecret 应用Secret
* @return string|false 成功返回access_token,失败返回false
*/
function getWeChatWorkAccessToken($corpID, $corpSecret) {
$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpID}&corpsecret={$corpSecret}";
$response = file_get_contents($url);
if ($response === false) {
return false;
}
$result = json_decode($response, true);
if (isset($result['access_token'])) {
return $result['access_token'];
} else {
return false;
}
}
?>
注意:file_get_contents在禁用allow_url_fopen的服务器上可能无法使用,更推荐使用cURL扩展,它更灵活和健壮,下面是使用cURL的版本:
<?php
function getWeChatWorkAccessToken($corpID, $corpSecret) {
$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpID}&corpsecret={$corpSecret}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过SSL证书验证,生产环境建议开启
$response = curl_exec($ch);
curl_close($ch);
if ($response === false) {
return false;
}
$result = json_decode($response, true);
if (isset($result['access_token'])) {
return $result['access_token'];
} else {
return false;
}
}
?>
发送文本消息的PHP函数
获取到Access Token后,我们就可以调用发送消息的API了,文本消息的API地址为:
https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
发送POST请求,消息体为JSON格式,文本消息的JSON结构如下:
{
"touser": "user1|user2|@all",
"toparty": "party1|party2",
"totag": "tag1|tag2",
"msgtype": "text",
"agentid": 1000002,
"text": {
"content": "你的消息内容"
},
"safe": 0,
"enable_id_trans": 0,
"enable_duplicate_check": 0
}
参数说明:
touser: 接收消息的用户ID列表,多个用分隔。@all表示所有成员。toparty: 接收消息的部门ID列表,多个用分隔,与touser同时存在时,优先取touser。totag: 接收消息的标签ID列表,多个用分隔。msgtype: 消息类型,这里固定为text。agentid: 企业微信应用的AgentId。text: 消息内容对象,content。safe: 表示是否是保密消息,0表示否,1表示是,默认0。enable_id_trans: 表示是否开启id转译,0表示否,1表示是,默认0。enable_duplicate_check: 表示是否开启重复消息检查,0表示否,1表示是,默认0,重复时间默认1800秒。
下面是发送文本消息的PHP函数:
<?php
/**
* 发送企业微信文本消息
* @param string $accessToken Access Token
* @param int $agentId 应用AgentId
* @param string $content 消息内容
* @param string $toUser 接收用户ID,多个用|分隔,@all表示所有人
* @param string $toParty 接收部门ID,多个用|分隔 (可选)
* @param string $toTag 接收标签ID,多个用|分隔 (可选)
* @param int $safe 是否保密消息,0否1是 (可选)
* @return array|false 成功返回API响应数组,失败返回false
*/
function sendWeChatWorkTextMessage($accessToken, $agentId, $content, $toUser = '', $toParty = '', $toTag = '', $safe = 0) {
$url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$accessToken}";
$postData = [
'touser' => $toUser,
'toparty' => $toParty,
'totag' => $toTag,
'msgtype' => 'text',
'agentid' => intval($agentId),
'text' => [
'content' => $content
],
'safe' => intval($safe)
];
// 过滤空值,避免发送无效参数
$postData = array_filter($postData, function($value) {
return $value !== '' && $value !== null;
});
$postDataJson = json_encode($postData, JSON_UNESCAPED_UNICODE);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过SSL证书验证,生产环境建议开启
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($postDataJson)
]);
$response = curl_exec($ch);
curl_close($ch);
if ($response === false) {
return false;
}
return json_decode($response, true);
}
?>
完整示例与调用
将上述函数整合,我们可以得到一个完整的示例:
<?php // ===== 配置信息 ===== $corpID = 'your_corp_id'; // 替换为你的企业ID $corpSecret = 'your_app_secret'; // 替换为你的应用Secret $agentId = 'your_agent_id'; // 替换为你的应用AgentId,注意是整数 $toUser = 'user1|user2'; // 替换为接收人的userid,@all表示所有人 $messageContent = '这是一条来自PHP的测试消息,请查收!



还没有评论,来说两句吧...