WXBizDataCrypt.php 1.5 KB

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