关键字:微信公众平台 消息体签名 消息体加解密 EncodingAESKey 安全模式
原文 http://www.cnblogs.com/txw1958/p/weixin-aes-encrypt-decrypt.html
一、消息体加解密微信公众平台在配置服务器时,提供了3种加解密的模式供开发者选择,即明文模式、兼容模式、安全模式,选择兼容模式和安全模式前,需在开发者中心填写消息加解密密钥EncodingAESKey。
什么是EncodingAESKey?
加解密的详细技术方案可以参考官方文档 http://mp.weixin.QQ.com/wiki/index.php?title=%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88
二、开发实现及数据分析1. 配置假设本次的开发配置中URL为
http://www.fangbei.org/index.php
接口程序中需要配置以下三项参数
/* 方倍工作室 http://www.cnblogs.com/txw1958/ CopyRight 2014 All Rights Reserved*/define("TOKEN", "weixin");define("AppID", "wxbad0b45542aa0b5e");define("EncodingAESKey", "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG");require_once('wxBizMsgCrypt.php');2. 加解密实现
当用户向公众账号发送消息时,微信公众账号将会在URL中带上signature、timestamp、nonce、encrypt_type、msg_signature等参数,如下所示
http://www.fangbei.org/index.php?signature=35703636de2f9df2a77a662b68e521ce17c34db4×tamp=1414243737&nonce=1792106704&encrypt_type=aes&msg_signature=6147984331daf7a1a9eed6e0ec3ba69055256154
同时向该接口推送如下xml消息 ,即一个已加密的消息
<xml> <ToUserName><![CDATA[gh_680bdefc8c5d]]></ToUserName> <Encrypt><![CDATA[MNn4+jJ/VsFh2gUyKAaOJArwEVYCvVmyN0iXzNarP3O6vXzK62ft1/KG2/XPZ4y5bPWU/jfIfQxODRQ7sLkUsrDRqsWimuhIT8Eq+w4E/28m+XDAQKEOjWTQIOp1p6kNsIV1DdC3B+AtcKcKSNAeJDr7x7GHLx5DZYK09qQsYDOjP6R5NqebFjKt/NpEl/GU3gWFwG8LCtRNuIYdK5axbFSfmXbh5CZ6Bk5wSwj5fu5aS90cMAgUhGsxrxZTY562QR6c+3ydXxb+GHI5w+qA+eqJjrQqR7u5hS+1x5sEsA7vS+bZ5LYAR3+PZ243avQkGllQ+rg7a6TeSGDxxhvLw+mxxinyk88BNHkJnyK//hM1k9PuvuLAASdaud4vzRQlAmnYOslZl8CN7gjCjV41skUTZv3wwGPxvEqtm/nf5fQ=]]></Encrypt></xml>
这时,程序需要从url中获得以下参数
$timestamp = $_GET['timestamp'];$nonce = $_GET["nonce"];$msg_signature = $_GET['msg_signature'];$encrypt_type = $_GET['encrypt_type'];
这些参数将用于加解密过程
收到消息后,先进行解密,解密部分代码如下
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];if ($encrypt_type == 'aes'){ $pc = new WXBizMsgCrypt(TOKEN, EncodingAESKey, AppID); $this->logger(" D \r\n".$postStr); $decryptMsg = ""; //解密后的明文 $errCode = $pc->DecryptMsg($msg_signature, $timestamp, $nonce, $postStr, $decryptMsg); $postStr = $decryptMsg;}
解密完成后,把解密内容又返回给$postStr,这是为了保证将消息中解密后的内容和明文模式时的消息统一,方便后续处理,解密后的XML如下
<xml> <ToUserName><![CDATA[gh_680bdefc8c5d]]></ToUserName> <FromUserName><![CDATA[oIDrpjpQ8j8mBuQ8nM26HWzNEZgg]]></FromUserName> <CreateTime>1414243737</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[?]]></Content> <MsgId>6074130599188426998</MsgId></xml>
对消息在自己的原来代码中处理,完成之后,要回复的消息如下
<xml> <ToUserName><![CDATA[oIDrpjpQ8j8mBuQ8nM26HWzNEZgg]]></ToUserName> <FromUserName><![CDATA[gh_680bdefc8c5d]]></FromUserName> <CreateTime>1414243733</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[2014-10-25 21:28:53技术支持 方倍工作室http://www.fangbei.org/]]></Content></xml>
把上述消息进行加密,返回给微信公众账号
//加密if ($encrypt_type == 'aes'){ $encryptMsg = ''; //加密后的密文 $errCode = $pc->encryptMsg($result, $timeStamp, $nonce, $encryptMsg); $result = $encryptMsg; $this->logger(" E \r\n".$result);}
加密后的内容如下
<xml> <Encrypt><![CDATA[pE6gp6qvVBMHwCXwnM7illFBrh9LmvlKFlPUDuyQo9EKNunqbUFMd2KjiYoz+3K1B+93JbMWHt+19TI8awdRdyoPRS4oUNg5M2jwpwXTmc6TtafkKNjvqlvPXIWmutw0tuMXke1hDgsqz0SC8h/QjNLxECuwnczrfCMJlt+APHnX2yMMaq/aYUNcndOH387loQvl2suCGucXpglnbxf7frTCz9NQVgKiYrvKOhk6KFiVMnzuxy6WWmoe3GBiUCPTtYf5b1CxzN2IHViEBm28ilV9wWdNOM9TPG7BSSAcpgY4pcwdIG5+4KhgYmnVU3bc/ZJkk42TIdidigOfFpJwET4UWVrLB/ldUud4aPexp3aPCR3Fe53S2HHcl3tTxh4iRvDftUKP3svYPctt1MlYuYv/BZ4JyzUQV03H+0XrVyDY2tyVjimgCrA2c1mZMgHttOHTQ6VTnxrMq0GWlRlH0KPQKqtjUpNQzuOH4upQ8boPsEtuY3wDA2RaXQPJrXon]]></Encrypt> <MsgSignature><![CDATA[6c46904dc1f58b2ddf2dd0399f1c6cf41f33ecb9]]></MsgSignature> <TimeStamp>1414243733</TimeStamp> <Nonce><![CDATA[1792106704]]></Nonce></xml>
这样,一个安全模式下的加解密消息就完成了。
三、完整代码1 <?php 2 /* 3 方倍工作室 http://www.cnblogs.com/txw1958/ 4 CopyRight 2014 All Rights Reserved 5 */ 6 define("TOKEN", "weixin"); 7 define("AppID", "wxbad0b45542aa0b5e"); 8 define("EncodingAESKey", "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"); 9 require_once('wxBizMsgCrypt.php'); 10 11 $wechatObj = new wechatCallbackapiTest(); 12 if (!isset($_GET['echostr'])) { 13 $wechatObj->responseMsg(); 14 }else{ 15 $wechatObj->valid(); 16 } 17 18 class wechatCallbackapiTest 19 { 20 //验证签名 21 public function valid() 22 { 23 $echoStr = $_GET["echostr"]; 24 $signature = $_GET["signature"]; 25 $timestamp = $_GET["timestamp"]; 26 $nonce = $_GET["nonce"]; 27 $tmpArr = array(TOKEN, $timestamp, $nonce); 28 sort($tmpArr); 29 $tmpStr = implode($tmpArr); 30 $tmpStr = sha1($tmpStr); 31 if($tmpStr == $signature){ 32 echo $echoStr; 33 exit; 34 } 35 } 36 37 //响应消息 38 public function responseMsg() 39 { 40 $timestamp = $_GET['timestamp']; 41 $nonce = $_GET["nonce"]; 42 $msg_signature = $_GET['msg_signature']; 43 $encrypt_type = (isset($_GET['encrypt_type']) && ($_GET['encrypt_type'] == 'aes')) ? "aes" : "raw"; 44 45 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 46 if (!empty($postStr)){ 47 //解密 48 if ($encrypt_type == 'aes'){ 49 $pc = new WXBizMsgCrypt(TOKEN, EncodingAESKey, AppID); 50 $this->logger(" D \r\n".$postStr); 51 $decryptMsg = ""; //解密后的明文 52 $errCode = $pc->DecryptMsg($msg_signature, $timestamp, $nonce, $postStr, $decryptMsg); 53 $postStr = $decryptMsg; 54 } 55 $this->logger(" R \r\n".$postStr); 56 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 57 $RX_TYPE = trim($postObj->MsgType); 58 59 //消息类型分离 60 switch ($RX_TYPE) 61 { 62 case "event": 63 $result = $this->receiveEvent($postObj); 64 break; 65 case "text": 66 $result = $this->receiveText($postObj); 67 break; 68 } 69 $this->logger(" R \r\n".$result); 70 //加密 71 if ($encrypt_type == 'aes'){ 72 $encryptMsg = ''; //加密后的密文 73 $errCode = $pc->encryptMsg($result, $timeStamp, $nonce, $encryptMsg); 74 $result = $encryptMsg; 75 $this->logger(" E \r\n".$result); 76 } 77 echo $result; 78 }else { 79 echo ""; 80 exit; 81 } 82 } 83 84 //接收事件消息 85 private function receiveEvent($object) 86 { 87 $content = ""; 88 switch ($object->Event) 89 { 90 case "subscribe": 91 $content = "欢迎关注方倍工作室 "; 92 break; 93 } 94 95 $result = $this->transmitText($object, $content); 96 return $result; 97 } 98 99 //接收文本消息100 private function receiveText($object)101 {102 $keyWord = trim($object->Content);103 if (strstr($keyword, "文本")){104 $content = "这是个文本消息";105 }else if (strstr($keyword