WXBizDataCrypt.php 1.8 KB

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