微信公众号后台的运维,虽然一般只是纯后台形式的,一般人发现不了你的地址,但也不能掉以轻心,同学运维的一个公众号不仅没有任何防注入的措施,还使用了明文传输,我拿到他公众号后台地址之后,一个模拟请求提交构造好的xml数据就可以把他的服务器干掉。在你不清楚具体怎么防注入的时候,加密通讯不失为一种简单使用的手段,最起码限制了你处理的用户信息均来自粉丝微信号。
微信开启加密通信其实也很简单,加密的过程微信提供文件,直接引入就好,但是在不改变自己项目结构的同时又怎样变成加密通讯呐?也就在外面包一层加密解密的代码就好,下面给出我封装的代码。
<?php
/**
* Created by Soon
*/
//error_reporting(0);
define('TOKEN','你的token');
define('ENCODINGAESKEY','你的加密密钥');
define('APPID','你的appid');
define('NONCE','随机的字符串,可以指定,可以每次都随机生成,这个随意写');
include_once('./EncodingAESKey/wxBizMsgCrypt.php');//微信提供的加密文件
include_once('./event.php');//你的微信后台之前的入口文件
$wechatObj = new wechat();
$wechatObj->responseMsg();
class wechat
{
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
$pc = new WXBizMsgCrypt(TOKEN,ENCODINGAESKEY,APPID);
$timestamp = $_GET['timestamp'];
$nonce = $_GET["nonce"];
$msg_sign = $_GET['msg_signature'];
$encrypt_type = (isset($_GET['encrypt_type']) && ($_GET['encrypt_type'] == 'aes')) ? "aes" : "raw";
if (!empty($postStr)) {
$msg = '';
$errCode = $pc->decryptMsg($msg_sign, $timestamp, $nonce, $postStr, $msg);
if ($errCode == 0) {
$postStr = $msg;//解密以后的数据
$event = new event();//event类负责处理消息
$event_result = $event->event_response($postStr);//传入解密后的数据,event需要有返回值,把之前的echo变成return,去掉exit就好
echo $this->send_msg($event_result);//加密发送消息
} else {
echo "";//解密失败
}
exit;
}
}
private function send_msg($text)
{
$pc = new WXBizMsgCrypt(TOKEN,ENCODINGAESKEY,APPID);
$encryptMsg = '';
$timeStamp = time();
$errCode = $pc->encryptMsg($text, $timeStamp,NONCE, $encryptMsg);
if ($errCode == 0) {
return $encryptMsg;
} else {
return '';
}
}
}
实例代码下载地址:http://download.csdn.net/detail/wwwwse/9538516