You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace LaneWeChat\Core\Aes;
include_once "wxBizMsgCrypt.php";
// 第三方发送消息给公众平台
$encodingAesKey = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
$token = "pamtest";
$timeStamp = "1409304348";
$nonce = "xxxxxx";
$appId = "wxb11529c136998cb6";
$text = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>";
// 初始化WXBizMsgCrypt对象
$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
$encryptMsg = '';
// 加密消息
$errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
if ($errCode == 0) {
print("加密后: " . $encryptMsg . "\n");
} else {
print($errCode . "\n");
}
// 解析加密后的XML消息
$xml_tree = new DOMDocument();
$xml_tree->loadXML($encryptMsg);
$array_e = $xml_tree->getElementsByTagName('Encrypt');
$array_s = $xml_tree->getElementsByTagName('MsgSignature');
$encrypt = $array_e->item(0)->nodeValue;
$msg_sign = $array_s->item(0)->nodeValue;
// 构造解密的XML格式
$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
$from_xml = sprintf($format, $encrypt);
// 解密消息
$msg = '';
$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
if ($errCode == 0) {
print("解密后: " . $msg . "\n");
} else {
print($errCode . "\n");
}
命名空间声明namespace LaneWeChat\Core\Aes; 定义了类的命名空间表明这个脚本属于LaneWeChat模块的Aes部分。
引入类库include_once "wxBizMsgCrypt.php"; 引入用于消息加密和解密的类库。
初始化参数:定义了用于加密和解密的参数,包括 encodingAesKey、token、timeStamp、nonce appId。
初始化WXBizMsgCrypt对象创建 WXBizMsgCrypt 对象,用于消息的加密和解密。
加密消息:调用 encryptMsg 方法对消息进行加密,并输出加密后的结果。
解析加密后的XML消息使用 DOMDocument 解析加密后的XML消息提取 Encrypt MsgSignature 的值。
构造解密的XML格式构造用于解密的XML格式。
解密消息:调用 decryptMsg 方法对消息进行解密,并输出解密后的结果。