Wxbizdatacrypt.php 1.5 KB

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