feiyu02
2022-11-15 23bd719cebe5feeff4e48fde925b0b39755eea93
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package cn.flightfeather.supervision.common.wx
 
import cn.flightfeather.supervision.common.net.WXHttpService
import org.springframework.stereotype.Component
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
 
/**
 * 小程序全局后台接口调用凭据管理
 */
@Component
class WxTokenManager {
 
    companion object {
        private const val TAG = "WxTokenManager"
    }
    private var schedule = Executors.newScheduledThreadPool(2)
 
    private var token = ""
 
    fun run(){
        if (token.isBlank()) {
            refreshToken(0)
        }
    }
 
    /**
     * 刷新接口调用凭证
     * @param delay 延迟执行时间,单位:秒
     * @param force 是否强制中断当前线程,重新执行
     */
    fun refreshToken(delay:Long, force:Boolean = false) {
        if (force) {
            schedule = closeThread(schedule)
        }
        schedule.schedule({
            getTokenTask()
        }, delay, TimeUnit.SECONDS)
    }
 
    fun getAccessToken(): String {
        if (token.isBlank()) {
            throw IllegalStateException("[${TAG}]获取小程序接口调用凭据,当前token还未获取到")
        }
        return token
    }
 
    private fun getTokenTask() {
        val res = WXHttpService.getAccessToken()
        if (res == null) {
            //请求失败,10s后重试
            refreshToken(10)
        } else {
            var nextDelay = 6900L//下一次获取凭证时间间隔(秒)
            when (res["errcode"]?.asInt) {
                //请求成功
                null, 0 -> {
                    val t = res["access_token"]?.asString
                    if (t == null) {
                        refreshToken(60)
                    } else {
                        token = t
                        res["expires_in"]?.asLong?.let { nextDelay = it - 300 }
                        refreshToken(nextDelay)
                    }
                }
                //微信服务器系统繁忙,稍后重试
                -1 -> {
                    refreshToken(60)
                }
                //AppSecret错误
                40001 -> {
                    throw IllegalStateException("[${TAG}]获取小程序接口调用凭据,AppSecret[${WxConfig.SECRET}]错误")
                }
                40002 -> {
                    throw IllegalStateException("[${TAG}]获取小程序接口调用凭据,请确保grant_type字段值为client_credential")
                }
                40003 -> {
                    throw IllegalStateException("[${TAG}]获取小程序接口调用凭据,AppID[${WxConfig.APP_ID}]错误")
                }
            }
        }
    }
 
    private fun closeThread(s: ScheduledExecutorService): ScheduledExecutorService {
        try {
            s.shutdown()
            if (s.awaitTermination(10, TimeUnit.SECONDS)) {
                s.shutdownNow()
            }
        } catch (e: InterruptedException) {
            e.printStackTrace()
            s.shutdownNow()
        }
        return Executors.newScheduledThreadPool(2)
    }
}