原来程序一直使用thinkphp官方的WeChat包,在使用php5.6时,消息发送正常,升级成php7.2后,发送不了消息。一番排查发现php7.2不在支持 MCrypt 加解密,PHP手册在7.1迁移页面给出了替代方案,就是用OpenSSL取代MCrypt。
只需用以下代码替换原WechatCrypt.class.php 文件响应 方法即可,前提是服务器要开通openssl模块
/**
* 对明文进行加密
* @param string $text 需要加密的字符串
* @return string 密文字符串
*/
public function encrypt($text){
try {
//获得16位随机字符串,填充到明文之前
$random = self::getRandomStr(16);
$text = $random . pack("N", strlen($text)) . $text . $this->appId;
$iv = substr($this->cyptKey, 0, 16);
$text = self::PKCS7Encode($text, 32);
$encrypted = openssl_encrypt($text, 'AES-256-CBC', substr($this->cyptKey, 0, 32), OPENSSL_ZERO_PADDING, $iv);
return $encrypted;
} catch (Exception $e) {
throw new \Exception("aes 加密失败");
}
}
/**
* 对密文进行解密
* @param string $encrypt 密文
* @return string 明文
*/
public function decrypt($encrypt){
try {
$iv = substr($this->cyptKey, 0, 16);
$decrypt = openssl_decrypt($encrypt, 'AES-256-CBC', substr($this->cyptKey, 0, 32), OPENSSL_ZERO_PADDING, $iv);
} catch (Exception $e) {
throw new \Exception("解密失败");
}
$decrypt = self::PKCS7Decode($decrypt, 32);
if (strlen($decrypt) < 16) {
throw new \Exception("非法密文字符串!");
}
$content = substr($decrypt, 16, strlen($decrypt));
$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);
//验证APP_ID
if($from_appid !== $this->appId){
throw new \Exception("非法APP_ID!");
}
return $xml_content;
}
本文收集于网络,仅供技术交流使用,本站不拥有所有权,不承担相关法律责任。如果发现本站有涉嫌抄袭的内容, 欢迎发送邮件至 admin@webse.cn 举报,一经查实,本站将立刻删除涉嫌侵权内容,本文链接:https://webse.cn/10552.html