Groovy实现微信公众号消息推动

Groovy实现微信公众号的消息推送,推送给用户

请求方法:

 /**
     * POST form请求
     * @param params body参数
     */
    static RestResponse post(url, params) {
        def rest = new RestBuilder(), rsp, convertParams = new LinkedMultiValueMap();
        try {
            params?.each { key, value ->
                convertParams.add(key, value as String)
            }
            rsp = rest.post(url) {
                contentType('application/x-www-form-urlencoded')
                body(convertParams)
            }
        } catch (e) {
            e.printStackTrace()
        }
        return (RestResponse) rsp
    }

 

工具类

 

class WechatUtils {


    static def APPID = "";
    static def APPSECRET = "";

    static Logger log = LoggerFactory.getLogger(WechatUtils.class)
    static Integer time = Const.CACHE_EXPIRETIME.WECHAT_ACCESS_TOKEN_SETTLE_TIME
    static String ACCESS_TOKEN_KEY = Const.CACHE_KEYS.WECHAT_ACCESS_TOKEN
    static String TICKET_KEY = Const.CACHE_KEYS.TICKET_KEY

    static {
        println("初始化token_初始化AppId_初始化AppSecret"+new Date())
        APPID = SystemConfigRead.weixinH5AppId();
        APPSECRET = SystemConfigRead.weixinH5Secret();
    }

    /**
     *
     * @param touser 接收者openid  不为空
     * @param templateId 模板ID  不为空
     * @param url 模板跳转链接 不需设置为null
     * @param miniprogram 跳小程序所需数据,不需跳小程序参数设置为null
     * "miniprogram":{"appid":"xiaochengxuappid12345","pagepath":"index?foo=bar"},
     * @param data 模板数据  不为空
     * data 数据格式: def  data =[name:[value:'你的内容'],remark:[value: '你的内容']];
     * @return 是否发送成功
     */
    static boolean sendingMessagesToUserByOpenId(touser, templateId, url, miniprogram, data) {

        if (touser != null && templateId != null && data != null) {
            def messagesMap = ['touser': touser, 'template_id': templateId, 'data': data];
                if(url != null){
                    messagesMap.put('url',url);
                }else if(miniprogram != null){
                    messagesMap.put('miniprogram', miniprogram);
                }
            def URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getWechatToken();
            def result = RestBuilderUtils.postJSON(URL, messagesMap).json;

            if (result.getAt("errcode") == 0) {
                return true;
            }else if (result.getAt("errcode") == 40001){
                updateToken()
            }else {
            }
        }
        return false;

    }

    /**
     * 获取系统中当前token
     * @return
     */
    static String getWechatToken() {
        def token = JedisClient.get(ACCESS_TOKEN_KEY)
        if(token){
            return  token
        }else {
           def newToken = getNewWechatToken()
            JedisClient.set(ACCESS_TOKEN_KEY,newToken,time)
            return newToken
        }



      /*  long createTokenDate = (long)token.get("createTokenDate");
        long newDate = System.currentTimeMillis();
        if (newDate > createTokenDate) {
            token.put("createTokenDate", (newDate + 5400000l));//1.5小时
            token.put("token", getNewWechatToken());
        }
        return token.get("token");*/
    }

    /**
     * 从服务器获取新的token 不更新原token
     * @return
     */
    static String getNewWechatToken() {
        def tokenStr = RestBuilderUtils.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET)

        if(tokenStr.json.getAt("errcode") != null){
            //token.put("createTokenDate", 0);//7200000
        }
        if (tokenStr == null) {
            println("获取Token失败")
        }
        return tokenStr.json.getAt("access_token");
    }

     static updateToken(){
        def newToken = getNewWechatToken()
        JedisClient.set(ACCESS_TOKEN_KEY,newToken,time)
    }



    /**
     * 获取系统中当前token
     * @return
     */
    static String getTicket() {

        def token = JedisClient.get(TICKET_KEY)
        if (token) {
            return token
        } else {
            return updateTicket()
        }
    }

 

 

 

 

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页