设置接收事件服务器
登录企业微信管理界面,选择应用管理,首先需要自建一个应用。
设置接收消息的参数,点击“接收消息”的“设置API接收”按钮,进入配置页面。
URL、Token、EncodingAESKey三个参数
- URL是企业后台接收企业微信推送请求的访问协议和地址,支持http或https协议。
- Token可由企业任意填写,用于生成签名。
- EncodingAESKey用于消息体的加密,是AES密钥的Base64编码。
验证URL有效性
当点击“保存”提交以上信息时,企业微信会发送一条验证消息到填写的URL,发送方法为GET。
企业的接收消息服务器接收到验证请求后,需要作出正确的响应才能通过URL验证。
以下为PHP的校验代码
<?php
include_once "./WXBizMsgCrypt.php";
$url = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.urldecode($_SERVER['QUERY_STRING']);
$Url_data=Url_Get($url);
$jsonBody = file_get_contents('php://input');
$data = json_decode($jsonBody, true);
$corpId = "";
$token = "";
$encodingAesKey = "";
$sVerifyMsgSig = $_GET["msg_signature"];
$sVerifyTimeStamp = $_GET["timestamp"];
$sVerifyNonce = $_GET["nonce"];
$sVerifyEchoStr = $Url_data["echostr"];
$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $corpId);
$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
if ($errCode == 0) {
print($sEchoStr);
} else {
print($errCode);
}
function Url_Get($str){
$data = array();
$cs_str=explode('?',$str);
$parameter = explode('&',end($cs_str));
foreach($parameter as $val){
if(count(explode("msg_signature",$val))>1){
$data["msg_signature"] = str_replace("msg_signature=","",$val);
}
if(count(explode("timestamp",$val))>1){
$data["timestamp"] = str_replace("timestamp=","",$val);
}
if(count(explode("nonce",$val))>1){
$data["nonce"] = str_replace("nonce=","",$val);
}
if(count(explode("echostr",$val))>1){
$data["echostr"] = str_replace("echostr=","",$val);
}
}
return $data;
}
?>
验证成功后可以保存成功。
注意需要设置白名单。
以配置审批成功后的回调为例子:
1:需要在审批栏目配置需要通知的模版和可调用的应用(上面自建应用)。
2:以PHP为例进行回调数据接收和处理。
<?php
$encodingAesKey = "";
$token = "";
$corpId = "";
$sVerifyMsgSig = urldecode($_REQUEST['msg_signature']);
$sVerifyTimeStamp = urldecode($_REQUEST['timestamp']);
$sVerifyNonce = urldecode($_REQUEST['nonce']);
$xmldata=file_get_contents("php://input");
$sEchoStr = '';
$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $corpId);
$errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $xmldata, $sEchoStr);
$data=simplexml_load_string($sEchoStr,'SimpleXMLElement', LIBXML_NOCDATA);
$data = json_encode($data);
$data = json_decode($data,true);
dump($data)