WeCom is a communication tool developed for enterprise teams. It provides a robust set of APIs that support internal messaging, system notifications, and workflow alerts. By integrating WeCom’s message subscription functionality, businesses can push updates and notifications directly to employees or departments.
To begin, log in to the WeCom admin portal and create a custom application. Take note of the following required credentials:
To simplify HTTP requests and token generation, use Composer to install the following packages:
The WeCom API requires a specific structure for message payloads. Below is a sample JSON payload:
{
"touser": "UserID1|UserID2",
"agentid": 1,
"msgtype": "text",
"text": {
"content": "Your message content here"
},
"safe": 0
}
Explanation of key fields:
The following PHP script demonstrates how to build and send a message to WeCom’s API:
require 'path/to/vendor/autoload.php';
use GuzzleHttp\Client;
use Firebase\JWT\JWT;
// WeCom app configuration
$corpId = 'your_corp_id';
$agentId = 'your_agent_id';
$secret = 'your_secret_key';
function sendMsg($touser, $content) {
global $corpId, $agentId, $secret;
$data = [
'touser' => $touser,
'agentid' => $agentId,
'msgtype' => 'text',
'text' => [ 'content' => $content ],
'safe' => 0
];
// Generate JWT token
$time = time();
$payload = [
'iat' => $time,
'exp' => $time + 3600,
'iss' => $corpId
];
$token = JWT::encode($payload, $secret);
// Send request
$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;
}
You can now use the above function in your application logic to send targeted messages:
$touser = 'UserID1';
$content = 'You have a new message. Please check.';
$result = sendMsg($touser, $content);
if ($result) {
echo 'Message sent successfully';
} else {
echo 'Failed to send message';
}
This tutorial showed how to implement a WeCom message subscription system using PHP. You can enhance it further by:
With this approach, enterprises can build an efficient and scalable internal messaging system to improve operational communication.