ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-02-25 01:02:10  阅读:388  来源: 互联网

标签:return 16 微信 content text str appid PHP SDK


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有