企业微信是一款面向企业组织的沟通工具,支持丰富的 API 接口,适合内部消息、业务提醒和系统通知的快速传达。通过集成企业微信的消息订阅功能,可以实现对员工或部门的定向消息推送。
首先需在企业微信后台创建一个自建应用,记录并保管好以下关键信息:
为了简化 HTTP 请求及 Token 生成过程,推荐通过 Composer 安装以下库:
企业微信的消息发送接口需遵循特定的数据结构。以下是一个标准的请求体示例:
{
"touser": "UserID1|UserID2",
"agentid": 1,
"msgtype": "text",
"text": {
"content": "消息内容"
},
"safe": 0
}
字段说明:
以下是一个使用 PHP 构建并调用企业微信接口发送消息的完整示例:
require 'path/to/vendor/autoload.php';
use GuzzleHttp\Client;
use Firebase\JWT\JWT;
// 企业微信配置
$corpId = '企业ID';
$agentId = '应用ID';
$secret = '应用密钥';
function sendMsg($touser, $content) {
global $corpId, $agentId, $secret;
$data = [
'touser' => $touser,
'agentid' => $agentId,
'msgtype' => 'text',
'text' => [ 'content' => $content ],
'safe' => 0
];
// 生成 JWT Token
$time = time();
$payload = [
'iat' => $time,
'exp' => $time + 3600,
'iss' => $corpId
];
$token = JWT::encode($payload, $secret);
// 发送 HTTP 请求
$client = new Client(['base_uri' => 'https://qyapi.weixin.qq.com']);
$response = $client->request('POST', '/cgi-bin/message/send', [
'query' => ['access_token' => $token],
'json' => $data
]);
$result = json_decode($response->getBody(), true);
return $result['errcode'] === 0;
}
在实际业务逻辑中,可以按需调用该接口:
// 示例:发送消息
$touser = 'UserID1';
$content = '您有新的消息,请及时查看。';
$result = sendMsg($touser, $content);
if ($result) {
echo '消息发送成功';
} else {
echo '消息发送失败';
}
本文介绍了如何通过 PHP 实现企业微信的消息订阅功能。开发者可根据实际需求进一步优化:
通过这一方案,企业可以构建起高效、可靠的内部消息通知系统,有效提升信息传达效率。