WechatAccessToken.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Com;
  3. use App\Models\AccountWechat;
  4. use App\Models\OperatorsUser;
  5. use App\Com\Redis;
  6. use EasySwoole\EasySwoole\Logger;
  7. class WechatAccessToken
  8. {
  9. protected $redis = null; //redis客户端
  10. protected $url = "https://api.weixin.qq.com/cgi-bin/token"; //接口请求URL
  11. protected $appid = null; //appid
  12. protected $secret = null; //秘钥
  13. protected $redis_save_key = 'wechat_access_token'; //redis中的缓存键值
  14. protected $operators_id = 0; //运营商ID
  15. //构造函数
  16. function __construct($operators_id = 0)
  17. {
  18. $set = AccountWechat::create()->get()->toArray();
  19. if ($operators_id) {
  20. //获取运营商数据
  21. $this->operators_id = $operators_id;
  22. $operators_res = OperatorsUser::create()->where('id', $operators_id)->get()->toArray();
  23. $set = isset($operators_res['wechat_appid']) && $operators_res['wechat_appid'] && isset($operators_res['wechat_secret']) && $operators_res['wechat_secret'] ? $operators_res : $set;
  24. $this->redis_save_key = isset($operators_res['wechat_appid']) && $operators_res['wechat_appid'] && isset($operators_res['wechat_secret']) && $operators_res['wechat_secret'] ? $this->redis_save_key . '_' . $operators_id : $this->redis_save_key;
  25. }
  26. $this->appid = $set['wechat_appid'];
  27. $this->secret = $set['wechat_secret'];
  28. }
  29. /**
  30. * @param $operators_id 运营商ID,无运营商则为0
  31. * 获取Access_token
  32. * @return String 返回小程序授权码,获取失败可能会返回空
  33. */
  34. public function getAccess_token()
  35. {
  36. //加载redis
  37. $this->redis = Redis::getInstance()->getConnect();
  38. //获取redis存储
  39. $result = json_decode($this->redis->get($this->redis_save_key), true);
  40. //判断access_token不为空,且过期时间大于当前时间(去掉最后60秒防止时间误差)
  41. if ($result['access_token'] && $result['expires_time'] > (time() - 60)) {
  42. return $result['access_token'];
  43. } else { //否者获取最新的access_token
  44. $response = file_get_contents($this->url . "?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret);
  45. $result = json_decode($response, true);
  46. //记录微信服务器返回值
  47. Logger::getInstance()->info('小程序Access_token接口返回值:' . $response);
  48. //缓存到Redis中
  49. $this->redis->set($this->redis_save_key, json_encode(array('access_token' => $result['access_token'], 'expires_time' => time() + $result['expires_in'])));
  50. return $result['access_token'];
  51. }
  52. }
  53. }