java 后台给微信小程序给服务号发模板信息

登录自己的微信公众号,获取自己的appId,appSecret,


通过小程序ID和秘钥获取access_token

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

返回的map,

在访问发送模板的接口

https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN

需要传几个参数 post提交,代码如下:

//写一个共通的post提交方法

public String httpsRequest(String requestUrl, String requestMethod, String outputStr){
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时:{}");
        } catch (Exception e) {
            System.out.println("https请求异常:{}");
        }
        return null;

    }


返回获取accessToken,一天能获取200次,一次有效时间2小时,所有最好写个定时器,定时获取,这块代码没有写,需要你们自己写

 /**
     * 获取accessToken
     * @return
     */
    public  String getAccessToken(){
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        
        String url = tmpurl.replace("APPID", appId);
        url = url.replace("APPSECRET", appSecret);
        JSONObject resultJson =null;
        String result = httpsRequest(url, "POST", null);
         try {
             resultJson = JSON.parseObject(result);
             String errmsg = (String) resultJson.get("errmsg");
             if(!"".equals(errmsg) && errmsg != null){  //如果为errmsg为ok,则代表发送成功,公众号推送信息给用户了。
                 logger.error("获取access_token失败:"+errmsg);
                 return "error";
             }
         } catch (JSONException e) {
             e.printStackTrace();
         }
         System.err.println((String) resultJson.get("access_token"));
         return (String) resultJson.get("access_token");

    }


调用发送小程序接口,传个json

json格式:

touser:“xxxxxxxxxxx” //用户openID

template_id:“*******”//模板Id

url:“************”//跳转路径

data:{

    keyword1:{

        value:“”,

        color:“”

    },

 keyword1:{

        value:“”,

        color:“”

    }

}  //模板信息


    /**
     * 发送小程序
     * @param token
     * @param template
     * @return
     */
    @RequestMapping(value = "/sendTemplateMsg")
    public  boolean sendTemplateMsg(JSONObject json){  
        boolean flag=false;  
        /*String requestUrl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";  */
        String requestUrl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";
       String token =this.getAccessToken();
        requestUrl=requestUrl.replace("ACCESS_TOKEN", token);  
        
        String  result=this.httpsRequest(requestUrl, "POST", json.toJSONString());  
        if(result!=null){  
            JSONObject jsonResult = JSON.parseObject(result);
            int errorCode=jsonResult.getInteger("errcode");  
            String errorMessage=jsonResult.getString("errmsg");  
            if(errorCode==0){  
                flag=true;  
            }else{  
                System.out.println("模板消息发送失败:"+errorCode+","+errorMessage);  
                flag=false;  
            }  
        }  
        return flag;  
          


你可能感兴趣的:(java 后台给微信小程序给服务号发模板信息)