php视频号小店解密json

发布时间:2024-04-23作者:小灵龙点击:133

<?php

/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */


include_once "sha1.php";
include_once "xmlparse.php";
include_once "pkcs7Encoder.php";
include_once "errorCode.php";

/**
 * 1.第三方回复加密消息给公众平台;
 * 2.第三方收到公众平台发送的消息,验证消息的安全性,并对消息进行解密。
 */
class WXBizMsgCrypt
{
    private $token;
    private $encodingAesKey;
    private $appId;

    /**
     * 构造函数
     * @param $token string 公众平台上,开发者设置的token
     * @param $encodingAesKey string 公众平台上,开发者设置的EncodingAESKey
     * @param $appId string 公众平台的appId
     */
    public function __construct($token, $encodingAesKey, $appId)
    {
        $this->token = $token;
        $this->encodingAesKey = $encodingAesKey;
        $this->appId = $appId;
    }
/**
**注意!注意!注意!此文只针对json格式的解密**
![在这里插入图片描述](https://img-blog.csdnimg.cn/3041f415a4db4d58a54c9f45ec2a8980.png#pic_center)

出现问题场景,在对接微信视频号时发现加解密不在支持xml格式,仅支持json格式
本文仅针对json格式的类型解密,xml类型的消息可以直接前去微信官方下载demo关系不黏贴相关代码了可[前往微信官方文档](https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Message_encryption_and_decryption.html)


   /**
     * 检验消息的真实性,并且获取解密后的明文.
     * <ol>
     *    <li>利用收到的密文生成安全签名,进行签名验证</li>
     *    <li>若验证通过,则提取xml中的加密消息</li>
     *    <li>对消息进行解密</li>
     * </ol>
     *
     * @param $msgSignature string 签名串,对应URL参数的msg_signature
     * @param $timestamp string 时间戳 对应URL参数的timestamp
     * @param $nonce string 随机串,对应URL参数的nonce
     * @param $postData string 密文,对应POST请求的数据
     * @param &$msg string 解密后的原文,当return返回0时有效
     *
     * @return int 成功0,失败返回对应的错误码
     */
public function decryptMPrpcryptsg($msgSignature, $timestamp = null, $nonce, $postData, &$msg)    {
        $SHIPIN_Token = $this->token;
        $SHIPIN_EncodingAESKey = $this->encodingAesKey;
        if (strlen($SHIPIN_EncodingAESKey) != 43) {
            return false;
        }

        $array[] = 0;
        $array[] = $postData['Encrypt'];
        $array[] = $postData['ToUserName'];

        $ret = $array[0];

        if ($ret != 0) {
            return $ret;
        }

        if ($timestamp == null) {
            $timestamp = time();
        }

        $encrypt = $array[1];
        $touser_name = $array[2];

        //验证安全签名
        $array = $this->ShiPingetSHA1($SHIPIN_Token, $timestamp, $nonce, $encrypt);

        $ret = $array[0];

        if ($ret != 0) {
            return $ret;
        }

        $signature = $array[1];

        if ($signature != $msgSignature) {
            return false;
        }

        $result = $this->ShiPindecrypt($encrypt, $this->appId,$SHIPIN_EncodingAESKey);

        if ($result[0] != 0) {
            return $result[0];
        }
        $msg = $result[1];

        return $msg;
    }
/**
     * 用SHA1算法生成安全签名
     * @param string $token 票据
     * @param string $timestamp 时间戳
     * @param string $nonce 随机字符串
     * @param string $encrypt 密文消息
     */
    public function ShiPingetSHA1($token, $timestamp, $nonce, $encrypt_msg)    {
        //排序
        try {
            $array = array($encrypt_msg, $token, $timestamp, $nonce);
            sort($array, SORT_STRING);
            $str = implode($array);
            return array(0, sha1($str));
        } catch (Exception $e) {
           return false;
        }
    }
    /**
     * 对密文进行解密
     * @param string $encrypted 需要解密的密文
     * @return string 解密得到的明文
     */
    public function ShiPindecrypt($encrypted, $appid,$key)    {

        $key = base64_decode($key . "=");

        try {
            //使用BASE64对需要解密的字符串进行解码
            $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);
        } catch (Exception $e) {
           return false;
        }


        try {
            //去除补位字符
            $result = $this->ShiPindecode($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 false;
        }

        if ($from_appid != $appid)
            return false;
        return array(0, $xml_content);

    }
    /**
     * 对解密后的明文进行补位删除
     * @param decrypted 解密后的明文
     * @return 删除填充补位后的明文
     */
    function ShiPindecode($text)
    {
        $pad = ord(substr($text, -1));
        if ($pad < 1 || $pad > 32) {
            $pad = 0;
        }
        return substr($text, 0, (strlen($text) - $pad));
    }

}

标签:php