WXBizDataCrypt.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\library\wechat;
  13. class WXBizDataCrypt
  14. {
  15. private $appid;
  16. private $sessionKey;
  17. /**
  18. * 构造函数
  19. * @param string $appid string 小程序的appid
  20. * @param string $sessionKey string 用户在小程序登录后获取的会话密钥
  21. */
  22. public function __construct(string $appid, string $sessionKey)
  23. {
  24. $this->sessionKey = $sessionKey;
  25. $this->appid = $appid;
  26. }
  27. /**
  28. * 检验数据的真实性,并且获取解密后的明文.
  29. * @param string $encryptedData 加密的用户数据
  30. * @param string $iv 与用户数据一同返回的初始向量
  31. * @param mixed $content 解密后的原文
  32. * @return int 成功0,失败返回对应的错误码
  33. */
  34. public function decryptData(string $encryptedData, string $iv, &$content): int
  35. {
  36. if (strlen($this->sessionKey) != 24) {
  37. return ErrorCode::$IllegalAesKey;
  38. }
  39. if (strlen($iv) != 24) {
  40. return ErrorCode::$IllegalIv;
  41. }
  42. $aesKey = base64_decode($this->sessionKey);
  43. $aesIV = base64_decode($iv);
  44. $aesCipher = base64_decode($encryptedData);
  45. $result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV);
  46. if (empty($result)) {
  47. return ErrorCode::$IllegalBuffer;
  48. }
  49. $resultArr = json_decode($result, true);
  50. if (empty($resultArr)) {
  51. return ErrorCode::$IllegalBuffer;
  52. }
  53. if ($resultArr['watermark']['appid'] != $this->appid) {
  54. return ErrorCode::$IllegalBuffer;
  55. }
  56. $content = $resultArr;
  57. return ErrorCode::$OK;
  58. }
  59. }