美文网首页架构
spring项目结构设计-微信工具类

spring项目结构设计-微信工具类

作者: jinelei | 来源:发表于2020-05-13 17:37 被阅读0次

注意:这里依赖于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"))
    }
}

相关文章

网友评论

    本文标题:spring项目结构设计-微信工具类

    本文链接:https://www.haomeiwen.com/subject/ppkonhtx.html