<?php
declare (strict_types=1);

namespace app\common\library\wxserver;

class WxBizMsgCrypt
{
    private string $appId;
    private string $token;

    private string $encodingAesKey;

    public function __construct(string $token, string $encodingAesKey, string $appId)
    {
        $this->token = $token;
        $this->encodingAesKey = $encodingAesKey;
        $this->appId = $appId;
    }

    /**
     * @notes:xml转数组
     * @param $xml
     * @return mixed
     * @author: wanghousheng
     */
    public function fromXml($xml)
    {
        // 禁止引用外部xml实体
        libxml_disable_entity_loader();
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    /**
     * @notes: 解密
     * @param $msg_encrypt
     * @return false|string
     * @author: wanghousheng
     */
    public function decryptMsg($msg_encrypt)
    {
        $EncodingAESKey = $this->encodingAesKey;
        $AESKey = base64_decode($EncodingAESKey . '=');
        $iv = substr($AESKey, 0, 16);
        $msg_decode = base64_decode($msg_encrypt);
        $msg = openssl_decrypt($msg_decode, 'AES-256-CBC', $AESKey, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
        $msg_len = unpack('N', substr($msg, 16, 4));
        $len = $msg_len[1];
        return substr($msg, 20, $len);
    }
}