WechatAccessToken.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. $set = AccountWechat::create()->get()->toArray();
  18. if($operators_id){
  19. //获取运营商数据
  20. $this->operators_id = $operators_id;
  21. $operators_res = OperatorsUser::create()->where('id',$operators_id)->get()->toArray();
  22. $set = $operators_res['wechat_appid']&&$operators_res['wechat_secret']?$operators_res:$set;
  23. $this->redis_save_key = $operators_res['wechat_appid']&&$operators_res['wechat_secret']?$this->redis_save_key.'_'.$operators_id:$this->redis_save_key;
  24. }
  25. $this->appid = $set['wechat_appid'];
  26. $this->secret = $set['wechat_secret'];
  27. }
  28. /**
  29. * @param $operators_id 运营商ID,无运营商则为0
  30. * 获取Access_token
  31. * @return String 返回小程序授权码,获取失败可能会返回空
  32. */
  33. public function getAccess_token(){
  34. //加载redis
  35. $this->redis = Redis::getInstance()->getConnect();
  36. //获取redis存储
  37. $result = json_decode($this->redis->get($this->redis_save_key),true);
  38. //判断access_token不为空,且过期时间大于当前时间(去掉最后60秒防止时间误差)
  39. if($result['access_token']&&$result['expires_time']>(time()-60)){
  40. return $result['access_token'];
  41. }else{ //否者获取最新的access_token
  42. $response = file_get_contents($this->url."?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret);
  43. $result = json_decode($response,true);
  44. //记录微信服务器返回值
  45. Logger::getInstance()->info('小程序Access_token接口返回值:'.$response);
  46. //缓存到Redis中
  47. $this->redis->set($this->redis_save_key,json_encode(array('access_token'=>$result['access_token'],'expires_time'=>time()+$result['expires_in'])));
  48. return $result['access_token'];
  49. }
  50. }
  51. }