注意:这里依赖于spring的RestTemplate
object WeChatUtils {
/***
* 获取微信小程序 用户认证 access_token
*
* @param appid 是 小程序的唯一标识
* @param secret 是 小程序的appSecret
* @param js_code 是 登录时获取的code
* @param grant_type 是 填写为authorization_code
* @return
*/
@Throws(Exception::class)
fun accessToken(restTemplate: RestTemplate, appid: String, secret: String, js_code: String, grant_type: String): String {
val url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$js_code&grant_type=$grant_type"
return restTemplate.getForObject(url, String::class.java)!!
}
@Throws(Exception::class)
fun accessToken(restTemplate: RestTemplate, appid: String, secret: String): String {
val url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"
return restTemplate.getForObject(url, String::class.java)!!
}
/**
* 发送消息
*
* @param accessToken
* @param body
* @return
* @throws Exception
*/
@Throws(Exception::class)
fun sendTemplateMessage(restTemplate: RestTemplate, accessToken: String, body: String?): Boolean {
val url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$accessToken"
val result = restTemplate.postForObject(url, body, String::class.java)!!
return result.matches(Regex("errcode:\\s?0"))
}
}
网友评论