最近微信公众平台强烈推荐我们使用消息加密,即服务器采用安全模式,

PHP的demo给了一对加密解密的例子,不是很清楚,

根据常用的php格式

其实加密方式很简单,代码如下

$postStr = file_get_contents ( "php://input" );


// 第三方发送消息给公众平台
	$encodingAesKey = xxxxx;//自己服务器信息里的密钥
	$token = xxx;//自己服务器信息里的token
	$timeStamp =$_GET["timestamp"];
	$nonce = $_GET["nonce"];
	$appId = xxxx;//自己的APPid

	
	$msg_sign = $_GET["msg_signature"];


	$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);


	// 第三方收到公众号平台发送的消息
	$msg = '';
	$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $postStr, $msg);
		// 获取参数


	$postObj = simplexml_load_string ($msg, 'SimpleXMLElement', LIBXML_NOCDATA );

然后$postObj就是我们需要的解密后的xml数据。


加密也很简单

$encryptMsg = '';
	$errCode = $pc->encryptMsg($retStr, $timeStamp, $nonce, $encryptMsg);
	echo $encryptMsg;
$retStr为需要加密的数据,$encryptMsg为加密后的数据。