国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

wxBizDataCrypt.php 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. if (!defined('DEDEINC')) exit('dedebiz');
  3. /**
  4. * 对微信小程序用户加密数据的解密示例代码
  5. * Class WXBizDataCrypt
  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->appid = $appid;
  20. $this->sessionKey = $sessionKey;
  21. include_once __DIR__ . DIRECTORY_SEPARATOR . "errorCode.php";
  22. }
  23. /**
  24. * 检验数据的真实性,并且获取解密后的明文.
  25. * @param $encryptedData string 加密的用户数据
  26. * @param $iv string 与用户数据一同返回的初始向量
  27. * @param $data string 解密后的原文
  28. *
  29. * @return int 成功0,失败返回对应的错误码
  30. */
  31. public function decryptData($encryptedData, $iv, &$data)
  32. {
  33. if (strlen($this->sessionKey) != 24) {
  34. return ErrorCode::$IllegalAesKey;
  35. }
  36. $aesKey = base64_decode($this->sessionKey);
  37. if (strlen($iv) != 24) {
  38. return ErrorCode::$IllegalIv;
  39. }
  40. $aesIV = base64_decode($iv);
  41. $aesCipher = base64_decode($encryptedData);
  42. $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
  43. $dataObj = json_decode($result);
  44. if ($dataObj == null) {
  45. return ErrorCode::$IllegalBuffer;
  46. }
  47. // 兼容新版本无 watermark 的情况
  48. if (isset($dataObj->watermark) && $dataObj->watermark->appid != $this->appid) {
  49. return ErrorCode::$IllegalBuffer;
  50. }
  51. $data = $result;
  52. return ErrorCode::$OK;
  53. }
  54. }