appid = env('MP_APPID'); $this->encodingAesKey = env('MP_ENCODINGAESKEY'); $this->token = env('MP_TOKEN'); } public function xmlToArray($xml) { libxml_disable_entity_loader(true); $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $values; } public function arrayToXml(array $config) { $xml = ""; foreach ($config as $key=>$val) { if (is_numeric($val)){ $xml.="<".$key.">".$val.""; }else{ $xml.="<".$key.">"; } } $xml.=""; return $xml; } public function getSHA1($timestamp, $nonce, $encrypt_msg) { $array = array($encrypt_msg, $this->token, $timestamp, $nonce); sort($array, SORT_STRING); $str = implode($array); return sha1($str); } public function sendWxHttp($url, $content) { //转成微信需要的格式 $content = json_encode($content,JSON_UNESCAPED_UNICODE); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $content); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec($ch); if (curl_errno($ch)) { return curl_error($ch); } curl_close($ch); return json_decode($tmpInfo, true); } public function decryptMsg($array, $msgSignature, $timestamp, $nonce) { self::setLog(self::TYPENAME, $this->startTime(), ['array'=>$array, 'msgSignature'=>$msgSignature, 'timestamp'=>$timestamp, 'nonce'=>$nonce]); if (strlen($this->encodingAesKey) != 43) { return 'encodingAesKey 不等 43个'; } // 提取密文 if ($timestamp == null) { $timestamp = time(); } $encrypt = $array['Encrypt']; // 验证安全签名 $signature = $this->getSHA1($timestamp, $nonce, $encrypt); if ($signature != $msgSignature) { return '不相等 signature:'.$signature.' msgSignature:'.$msgSignature; } return $this->decrypt($encrypt, $this->appid); } public function decrypt($encrypted) { $key = $this->_makeKey(); $ciphertext_dec = base64_decode($encrypted); $iv = substr($key, 0, 16); $decrypted = openssl_decrypt($ciphertext_dec, 'AES-256-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv); $result = $this->decode($decrypted); $content = substr($result, 16, strlen($result)); $len_list = unpack("N", substr($content, 0, 4)); $xml_len = $len_list[1]; $xml_content = substr($content, 4, $xml_len); $from_appid = substr($content, $xml_len + 4); return self::xmlToArray($xml_content); } public function decode($text) { $pad = ord(substr($text, - 1)); if ($pad < 1 || $pad > 32) { $pad = 0; } return substr($text, 0, (strlen($text) - $pad)); } /** * 合并Key * * @return string */ private function _makeKey() { return base64_decode($this->encodingAesKey . "="); } }