WeChat 개발 시 데이터 복호화에 대한 예제 튜토리얼 공유

零下一度
풀어 주다: 2017-05-20 16:19:52
원래의
2239명이 탐색했습니다.

최근에 WeChat 애플릿의 서버 측을 작성하기 위해 thinkphp 프레임워크를 사용하고 있습니다. 아마도 Virgo 때문일 것입니다. 공식 웹사이트에서 PHP WeChat 암호 해독 데모를 다운로드하여 많은 코드 없이도 클래스에 통합할 수 있습니다. 필요합니다. thinkphp 5.0 프레임워크가 확장 클래스 참조에 너무 고통스러워 보인다는 점을 고려하여 쉽게 호출할 수 있도록 하나의 클래스로 통합했습니다.

WeChat 개발 시 데이터 복호화에 대한 예제 튜토리얼 공유


Baidu 디스크 다운로드 주소:
pan.baidu.com/s/1kURMQ2b

<?php
/**
 * 对微信小程序用户加密数据的解密示例代码.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

class WXBizDataCrypt
{
    private $appid;
    private $sessionKey;
    private $blockSize = 16;

    private $OKs = 0;
    private $IllegalAesKey = -41001;
    private $IllegalIv = -41002;
    private $IllegalBuffer = -41003;
    private $DecodeBase64Error = -41004;

    /**
     * 检验数据的真实性,并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0,失败返回对应的错误码
     */
    public function decryptData($appid,$sessionKey,$encryptedData, $iv, &$data )
    {
        $this->sessionKey = $sessionKey;
        $this->appid = $appid;

        if (strlen($this->sessionKey) != 24) {
            return $this->IllegalAesKey;
        }
        $aesKey=base64_decode($this->sessionKey);

        if (strlen($iv) != 24) {
            return $this->IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result = $this->decrypt($aesKey,$aesCipher,$aesIV);

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

        $dataObj=json_decode( $result[1] );

        if( $dataObj  == NULL )
        {
            return $this->IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return $this->IllegalBuffer;
        }
        $data = $result[1];
        return $this->OKs;
    }

    /**
     * 对密文进行解密
     * @param string $aesCipher 需要解密的密文
     * @param string $aesIV 解密的初始向量
     * @return string 解密得到的明文
     */
    private function decrypt($key, $aesCipher, $aesIV )
    {
        try {

            $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, &#39;&#39;, MCRYPT_MODE_CBC, &#39;&#39;);

            mcrypt_generic_init($module, $key, $aesIV);

            //解密
            $decrypted = mdecrypt_generic($module, $aesCipher);
            mcrypt_generic_deinit($module);
            mcrypt_module_close($module);
        } catch (Exception $e) {
            return array($this->IllegalBuffer, null);
        }


        try {
            //去除补位字符
            $result = $this->decode($decrypted);

        } catch (Exception $e) {
            //print $e;
            return array($this->IllegalBuffer, null);
        }
        return array(0, $result);
    }

    /**
     * 对需要加密的明文进行填充补位
     * @param $text 需要进行填充补位操作的明文
     * @return 补齐明文字符串
     */
    private function encode( $text )
    {
        $block_size = $this->blockSize;
        $text_length = strlen( $text );
        //计算需要填充的位数
        $amount_to_pad = $this->blockSize - ( $text_length % $this->blockSize );
        if ( $amount_to_pad == 0 ) {
            $amount_to_pad = $this->blockSize;
        }
        //获得补位所用的字符
        $pad_chr = chr( $amount_to_pad );
        $tmp = "";
        for ( $index = 0; $index < $amount_to_pad; $index++ ) {
            $tmp .= $pad_chr;
        }
        return $text . $tmp;
    }

    /**
     * 对解密后的明文进行补位删除
     * @param decrypted 解密后的明文
     * @return 删除填充补位后的明文
     */
    private function decode($text)
    {

        $pad = ord(substr($text, -1));
        if ($pad < 1 || $pad > 32) {
            $pad = 0;
        }
        return substr($text, 0, (strlen($text) - $pad));
    }

}
로그인 후 복사

필요하시면 직접 다운로드해주세요. ps: 위챗 로그인 인증 과정이 헷갈리시면 메시지를 남겨주시면 상담 가능합니다.

[관련 추천]

1. 위챗 공개계정 플랫폼 소스코드 다운로드

PigCms 마이크로 전자상거래 시스템 운영 버전 (독립 WeChat 매장 몰 + 3단계 유통 시스템)

3. WeChat People Network v3.4.5 Advanced Business Edition WeChat Rubik's Cube 소스 코드

위 내용은 WeChat 개발 시 데이터 복호화에 대한 예제 튜토리얼 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!