/** * 生成用于回复的数据 * * @return array */ public function buildForReply() { if (!method_exists($this, 'toReply')) { throw new \Exception(__CLASS__ . '未实现此方法:toReply()'); } $base = array('ToUserName' => $this->to, 'FromUserName' => $this->from, 'CreateTime' => time(), 'MsgType' => $this->getDefaultMessageType()); return XML::build(array_merge($base, $this->toReply())); }
/** * 检验消息的真实性,并且获取解密后的明文. * <ol> * <li>利用收到的密文生成安全签名,进行签名验证</li> * <li>若验证通过,则提取xml中的加密消息</li> * <li>对消息进行解密</li> * </ol> * * @param string $msgSignature 签名串,对应URL参数的msg_signature * @param string $nonce 随机串,对应URL参数的nonce * @param string $timestamp 时间戳 对应URL参数的timestamp * @param string $postXML 密文,对应POST请求的数据 * * @return array */ public function decryptMsg($msgSignature, $nonce, $timestamp, $postXML) { //提取密文 $array = XML::parse($postXML); if (empty($array)) { echo 'Invalid xml.'; } $encrypted = $array['Encrypt']; //验证安全签名 $signature = $this->getSHA1($this->token, $timestamp, $nonce, $encrypted); if ($signature !== $msgSignature) { echo 'Invalid Signature.'; } return XML::parse($this->decrypt($encrypted, $this->appId)); }
/** * 初始化POST请求数据 * * @return Bag */ protected function prepareInput() { if ($this->input instanceof Bag) { return; } $input = array(); if ($_SERVER['REQUEST_METHOD'] == "POST") { $xmlInput = file_get_contents('php://input'); $array = XML::parse($xmlInput); if (isset($array['Encrypt'])) { $this->encryptStr = $array['Encrypt']; } $input = $this->getCrypt()->decryptMsg($_REQUEST['msg_signature'], $_REQUEST['nonce'], $_REQUEST['timestamp'], $xmlInput); } $this->input = new Bag(array_merge($_REQUEST, (array) $input)); }