package cn.flightfeather.supervision.common.net
|
|
import cn.flightfeather.supervision.common.wx.MessageWxVo
|
import cn.flightfeather.supervision.common.wx.WxConfig
|
import com.alibaba.fastjson.JSON
|
import com.alibaba.fastjson.JSONObject
|
import com.google.gson.Gson
|
import com.google.gson.JsonObject
|
import com.google.gson.JsonParser
|
|
/**
|
* @author riku
|
* Date: 2020/10/15
|
* 微信服务接口
|
*/
|
object WXHttpService {
|
|
private val httpMethod = HttpMethod("api.weixin.qq.com", 443, true)
|
|
/**
|
* 微信登录凭证校验
|
*/
|
fun code2Session(code: String): Pair<String, String>? {
|
val res =httpMethod.get(
|
"/sns/jscode2session", listOf(
|
Pair("appid", WxConfig.APP_ID), Pair("secret", WxConfig.SECRET), Pair("js_code", code), Pair("grant_type", "authorization_code")
|
)
|
)
|
return if (res.success) {
|
val json = JSONObject.parseObject(res.m.responseBodyAsString)
|
val errCode = json["errcode"]
|
if (errCode == 0 || errCode == null) {
|
val openid = json["openid"] as String
|
val unionid = json["session_key"] as String
|
Pair(openid, unionid)
|
} else {
|
null
|
}
|
} else {
|
null
|
}
|
}
|
|
/**
|
* 微信发送订阅消息
|
*/
|
fun sendMsg(accessToken:String, msgWxV0: MessageWxVo): Boolean {
|
val data = Gson().toJson(msgWxV0)
|
val response = httpMethod.post("/cgi-bin/message/subscribe/send?access_token=${accessToken}", data)
|
if (response.success) {
|
val json = JsonParser.parseString(response.m.responseBodyAsString)
|
if (json.isJsonObject) {
|
val jo = json.asJsonObject
|
val eMsg = jo["errmsg"]?.asString
|
when (jo["errcode"]?.asInt) {
|
40003 -> {
|
throw IllegalStateException("微信订阅消息,touser字段openid为空或者不正确,错误信息:${eMsg}")
|
}
|
40037 -> {
|
throw IllegalStateException("微信订阅消息,订阅模板id为空不正确,错误信息:${eMsg}")
|
}
|
43101 -> {
|
throw IllegalStateException("微信订阅消息,用户拒绝接收消息,错误信息:${eMsg}")
|
}
|
47003 -> {
|
throw IllegalStateException("微信订阅消息,模板参数不准确,具体错误:${eMsg}")
|
}
|
41030 -> {
|
throw IllegalStateException("微信订阅消息,page路径不正确,错误信息:${eMsg}")
|
}
|
}
|
}
|
return true
|
} else {
|
return false
|
}
|
}
|
|
/**
|
* 获取小程序全局后台接口调用凭据
|
*/
|
fun getAccessToken(): JsonObject? {
|
val res = httpMethod.get(
|
"/cgi-bin/token", listOf(
|
Pair("grant_type", "client_credential"),
|
Pair("appid", WxConfig.APP_ID),
|
Pair("secret", WxConfig.SECRET)
|
)
|
)
|
return if (res.success) {
|
val json = JsonParser.parseString(res.m.responseBodyAsString)
|
if (json.isJsonObject) {
|
json.asJsonObject
|
} else {
|
null
|
}
|
} else {
|
null
|
}
|
}
|
}
|