WXBizDataCrypt.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * 对微信小程序用户加密数据的解密示例代码.
  4. *
  5. * @copyright Copyright (c) 1998-2014 Tencent Inc.
  6. */
  7. declare (strict_types = 1);
  8. namespace app\common\library\weixin;
  9. class WXBizDataCrypt
  10. {
  11. private $appid;
  12. private $sessionKey;
  13. /**
  14. * 构造函数
  15. * @param $sessionKey string 用户在小程序登录后获取的会话密钥
  16. * @param $appid string 小程序的appid
  17. */
  18. public function __construct( $appid, $sessionKey)
  19. {
  20. $this->sessionKey = $sessionKey;
  21. $this->appid = $appid;
  22. }
  23. /**
  24. * 检验数据的真实性,并且获取解密后的明文.
  25. * @param $encryptedData string 加密的用户数据
  26. * @param $iv string 与用户数据一同返回的初始向量
  27. * @param $data string 解密后的原文
  28. *
  29. * @return int 成功0,失败返回对应的错误码
  30. */
  31. public function decryptData( $encryptedData, $iv, &$data )
  32. {
  33. if (strlen($this->sessionKey) != 24) {
  34. return ErrorCode::$IllegalAesKey;
  35. }
  36. $aesKey=base64_decode($this->sessionKey);
  37. if (strlen($iv) != 24) {
  38. return ErrorCode::$IllegalIv;
  39. }
  40. $aesIV=base64_decode($iv);
  41. $aesCipher=base64_decode($encryptedData);
  42. $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
  43. $dataObj=$result ? json_decode( $result ) : null;
  44. if( $dataObj == NULL )
  45. {
  46. return ErrorCode::$IllegalBuffer;
  47. }
  48. if( $dataObj->watermark->appid != $this->appid )
  49. {
  50. return ErrorCode::$IllegalBuffer;
  51. }
  52. $data = $result;
  53. return ErrorCode::$OK;
  54. }
  55. }