微信自动回复-安全模式-消息加解密方式
public function WxToken(Request $request)
{
if (!empty($request->echostr)) {
$nonce = $request->input('nonce');
$echostr = $request->input('echostr');
$token = config('type.wechat.Token');
$timestamp = $request->input('timestamp');
$signature = $request->input('signature');
$array = array($token, $timestamp, $nonce);
sort($array, SORT_STRING);
$str = sha1(implode($array));
echo $echostr;
} else {
$msg_signature = $request->input('msg_signature');
$nonce = $request->input('nonce');
$timestamp = $request->input['timestamp'];
$postStr = file_get_contents("php://input");
$postArr = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
$encryptData = $postArr['Encrypt'];
//自动回复
$this->AutoResponseMsg($msg_signature, $timestamp, $encryptData, $nonce);
}
}
/**
* 自动回复
*/
public function AutoResponseMsg($msg_signature, $timestamp, $encryptData, $nonce)
{
$token = config('type.wechat.Token');
$encodingAesKey = config('type.wechat.EncodingAESKey');
$appId = config('type.wechat.AppID');
$pc = new WXBizMsgCryptTool($token, $encodingAesKey, $appId);
$decryptData = '';
$errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $encryptData, $decryptData);
Logger::info('code', ['code' => $errCode], 'code');
if ($errCode == 0) {
// 解密成功,处理消息
$res = json_decode(json_encode(simplexml_load_string($decryptData, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
$FromUserName = $res['FromUserName']; //获取发送方帐号(OpenID)
$ToUserName = $res['ToUserName']; //获取接收方账号
$html = "自定义回复文本";
echo $this->txt($html, $FromUserName, $ToUserName);
exit();
// TODO: 处理消息
} else {
exit('Decrypt error');
}
}
public function txt($content, $FromUserName, $ToUserName)
{
$time = time();
$xml = "<xml>
<ToUserName><![CDATA[{$FromUserName}]]></ToUserName>
<FromUserName><![CDATA[{$ToUserName}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$content}]]></Content>
</xml>";
return $xml;
}
WXBizMsgCryptTool文件
链接:https://pan.baidu.com/s/1iSCpbXI7mf7kZ7G3Er_fAg
提取码:prv0
本作品采用《CC 协议》,转载必须注明作者和本文链接