Crypt.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace app\extra\weMini;
  3. use app\extra\weMini\crypt\wxBizDataCrypt;
  4. use WeChat\Exceptions\InvalidDecryptException;
  5. use WeChat\Exceptions\InvalidResponseException;
  6. use yzh52521\EasyHttp\Http;
  7. class Crypt extends BasicWeChat
  8. {
  9. /**
  10. * 数据签名校验
  11. * @param string $iv
  12. * @param string $sessionKey
  13. * @param string $encryptedData
  14. * @return bool|array
  15. */
  16. public function decode($iv, $sessionKey, $encryptedData)
  17. {
  18. $pc = new WXBizDataCrypt($this->config->get('appid'), $sessionKey);
  19. $errCode = $pc->decryptData($encryptedData, $iv, $data);
  20. if ($errCode == 0) {
  21. return json_decode($data, true);
  22. }
  23. return false;
  24. }
  25. /**
  26. * 登录凭证校验
  27. * @param string $code 登录时获取的 code
  28. * @return array
  29. * @throws \WeChat\Exceptions\LocalCacheException
  30. */
  31. public function session($code)
  32. {
  33. $appid = $this->config->get('appid');
  34. $secret = $this->config->get('appsecret');
  35. $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
  36. return Http::get($url)->array();
  37. }
  38. /**
  39. * 换取用户信息
  40. * @param string $code 用户登录凭证(有效期五分钟)
  41. * @param string $iv 加密算法的初始向量
  42. * @param string $encryptedData 加密数据( encryptedData )
  43. * @return array
  44. * @throws \WeChat\Exceptions\InvalidDecryptException
  45. * @throws \WeChat\Exceptions\InvalidResponseException
  46. * @throws \WeChat\Exceptions\LocalCacheException
  47. */
  48. public function userInfo($code, $iv, $encryptedData)
  49. {
  50. $result = $this->session($code);
  51. if (empty($result['session_key'])) {
  52. throw new InvalidResponseException('Code 换取 SessionKey 失败', 403);
  53. }
  54. $userinfo = $this->decode($iv, $result['session_key'], $encryptedData);
  55. if (empty($userinfo)) {
  56. throw new InvalidDecryptException('用户信息解析失败', 403);
  57. }
  58. return array_merge($result, $userinfo);
  59. }
  60. }