123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- /**
- * Created by: PhpStorm
- * User: lytian
- * Date: 2020/2/27
- * Time: 14:04
- */
- namespace app\common\model;
- use app\common\library\Redis;
- use app\main\service\GdtService;
- use think\Log;
- use think\Model;
- class GdtAccount extends Model
- {
- // 表名
- protected $table = 'gdt_account';
- // 自动写入时间戳字段
- protected $autoWriteTimestamp = 'int';
- // 定义时间戳字段名
- protected $createTime = 'createtime';
- protected $updateTime = 'updatetime';
- // 追加属性
- protected $append = [
- ];
- /**
- * 获取account_id 和 access_token
- * @param $admin_id
- * @param bool $fromDb
- * @return array
- * @throws \think\Exception
- */
- public function getInfoByAdminId($admin_id, $fromDb = false)
- {
- $redisKey = "GDTI:".$admin_id;
- $result = [
- 'account_id' => 0,
- 'access_token' => '',
- ];
- if ($fromDb == false) {
- $data = Redis::instance()->hMGet($redisKey, ['account_id', 'access_token', 'access_token_expire_time']);
- if ($data['account_id'] !== false) {
- if ($data['account_id'] > 0) {
- if ($data['access_token_expire_time'] <= time()) {
- $fromDb = true;
- } else {
- $result['account_id'] = $data['account_id'];
- $result['access_token'] = $data['access_token'];
- }
- }
- } else {
- $fromDb = true;
- }
- }
- if ($fromDb) {
- $row = $this->where('admin_id', 'eq', $admin_id)->find();
- if ($row) {
- $data = $row->toArray();
- //需要检测token有效期
- if ($data['access_token_expire_time'] <= time()) {
- $access_token = GdtService::instance()->apiUpdateAccessToken($data['account_id'], $data['refresh_token'], ['admin_id' => $data['admin_id']]);
- if (is_null($access_token)) {
- Log::error("GDT刷新access_token失败:admin_id:{$admin_id}");
- $result = [
- 'account_id' => 0,
- 'access_token' => '',
- ];
- } else {
- //更新数据库
- $this->update(['access_token' => $access_token, 'access_token_expire_time' => time() + 85400, 'updatetime' => time()], ['id' => $data['id']]);
- $data['access_token'] = $access_token;
- $data['access_token_expire_time'] = time() + 85400;
- $result = [
- 'account_id' => $data['account_id'],
- 'access_token' => $access_token,
- ];
- }
- } else {
- $result = [
- 'account_id' => $data['account_id'],
- 'access_token' => $data['access_token'],
- ];
- }
- } else {
- $data = [
- 'admin_id' => $admin_id,
- 'account_id' => 0,
- 'access_token' => '',
- 'access_token_expire_time' => 0,
- ];
- }
- Redis::instance()->hMSet($redisKey, $data);
- Redis::instance()->expire($redisKey, 3600);
- }
- return $result;
- }
- }
|