wxBizDataCrypt.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * 对微信小程序用户加密数据的解密示例代码
  4. * Class WXBizDataCrypt
  5. * @copyright Copyright (c) 1998-2014 Tencent Inc.
  6. */
  7. class WXBizDataCrypt
  8. {
  9. private $appid;
  10. private $sessionKey;
  11. /**
  12. * 构造函数
  13. * @param $sessionKey string 用户在小程序登录后获取的会话密钥
  14. * @param $appid string 小程序的appid
  15. */
  16. public function __construct($appid, $sessionKey)
  17. {
  18. $this->appid = $appid;
  19. $this->sessionKey = $sessionKey;
  20. include_once __DIR__ . DIRECTORY_SEPARATOR . "errorCode.php";
  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. return ErrorCode::$IllegalBuffer;
  45. }
  46. // 兼容新版本无 watermark 的情况
  47. if (isset($dataObj->watermark) && $dataObj->watermark->appid != $this->appid) {
  48. return ErrorCode::$IllegalBuffer;
  49. }
  50. $data = $result;
  51. return ErrorCode::$OK;
  52. }
  53. }