编程语言
首页 > 编程语言> > 微信公众号PHP-SDK ( php8.0 版)

微信公众号PHP-SDK ( php8.0 版)

作者:互联网

PHP7 版本后,官方舍弃 mcrypt_module 系列的方法了。

比如 mcrypt_module_open, mcrypt_module_open , mcrypt_generic_deinit  ,mcrypt_generic 等。

改用 openssl_encrypt  和  openssl_decrypt  。

 

所以,在公众号的SKD中,修改 pkcs7Encoder.php文件中  pkcs7Encoder 类即可。

class Prpcrypt
{
    public $key;

     /**向量
     */
    public static  $IV = "12asd67890123412";//16位

    public  static $AES = 'AES-256-CBC';

    function __construct($k)
    {
        $this->key = base64_decode($k . "=");
    }


public function encrypt($text, $appid)
    {
        try {
            //获得16位随机字符串,填充到明文之前
            $random = $this->getRandomStr();
            $text = $random . pack("N", strlen($text)) . $text . $appid;
            $pkc_encoder = new PKCS7Encoder;
            $text = $pkc_encoder->encode($text);
            $encrypted = openssl_encrypt($text,self::$AES,$this->key,OPENSSL_RAW_DATA,self::$IV);
            return array(ErrorCode::$OK, base64_encode($encrypted));
        } catch (Exception $e) {
            //print $e;
            return array(ErrorCode::$EncryptAESError, null);
        }
    }


public function decrypt($encrypted, $appid)
    {
        $decrypted =  openssl_decrypt(base64_decode($encrypted),self::$AES,$this->key,OPENSSL_RAW_DATA,self::$IV);
        try {
            //去除补位字符
            $pkc_encoder = new PKCS7Encoder;
            $result = $pkc_encoder->decode($decrypted);
            //去除16位随机字符串,网络字节序和AppId
            if (strlen($result) < 16)
                return "";
            $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);
        } catch (Exception $e) {
            //print $e;
            return array(ErrorCode::$IllegalBuffer, null);
        }
        if ($from_appid != $appid)
            return array(ErrorCode::$ValidateAppidError, null);
        return array(0, $xml_content);

    }

function getRandomStr()
    {

        $str = "";
        $str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($str_pol) - 1;
        for ($i = 0; $i < 16; $i++) {
            $str .= $str_pol[mt_rand(0, $max)];
        }
        return $str;
    }

}
       

  

标签:return,16,微信,content,text,str,appid,PHP,SDK
来源: https://www.cnblogs.com/asp114/p/15934195.html