java微信小程序 发送模板消息

java发送模板消息 

1:微信开发平台上注册模板 获取模板from_id(from_id只能用一次)

2:获取用户的openid    获取自己的appid 和appsecret

3: 调试的时候 微信开发者工具获取的from_id不对  要用真机调试才能获取到正确格式的from_id

下面上代码CommUtil

@Autowired
HttpServletRequest httpsRequest;

public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//获取小程序token
public Token getToken(String appid, String appsecret) {

    final Logger log = LoggerFactory.getLogger(this.getClass());
    Token token = null;
    String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
    // 发起GET请求获取凭证
    JSONObject jsonObject = HttpUtil.httpsRequest(requestUrl, "GET", null);

    if (null != jsonObject) {
        try {
            token = new Token();
            token.setAccessToken(jsonObject.getString("access_token"));
            token.setExpiresIn(jsonObject.getInt("expires_in"));
        } catch (JSONException e) {
            token = null;
            // 获取token失败
            log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
        }
    }
    return token;
}



//发送模板消息
public static String sendTemplateMessage(WxMssVo wxMssVo) {
    PrintWriter out = null;
    String info = "";
    try {
        //创建连接
        URL url = new URL(wxMssVo.getRequest_url());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Type", "utf-8");
        connection.connect();
        //POST请求
        //DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        out =new PrintWriter(outputStreamWriter);
        JSONObject obj = new JSONObject();

        obj.put("access_token", wxMssVo.getAccess_token());
        obj.put("touser", wxMssVo.getTouser());
        obj.put("template_id", wxMssVo.getTemplate_id());
        obj.put("form_id", wxMssVo.getForm_id());
        obj.put("page", wxMssVo.getPage());

        JSONObject jsonObject = new JSONObject();

        for (int i = 0; i < wxMssVo.getParams().size(); i++) {
            JSONObject dataInfo = new JSONObject();
            dataInfo.put("value", wxMssVo.getParams().get(i).getValue());
            dataInfo.put("color", wxMssVo.getParams().get(i).getColor());
            jsonObject.put("keyword" + (i + 1), dataInfo);
        }

        obj.put("data", jsonObject);
        out.write(obj.toString());
        out.flush();
        out.close();

        //读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        StringBuffer sb = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        info = sb.toString();
        System.out.println(sb);
        reader.close();
        // 断开连接
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return info;
}

HttpUtil类
private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
/**
 * 发送https请求
 *
 * @param requestUrl 请求地址
 * @param requestMethod 请求方式(GET、POST)
 * @param outputStr 提交的数据
 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
 */
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    try {
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new BaseHttpSSLSocketFactory.MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL url = new URL(requestUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(ssf);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // 设置请求方式(GET/POST)
        conn.setRequestMethod(requestMethod);
        // 当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();
        //jsonObject = JSONObject.fromObject(buffer.toString());
        jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (ConnectException ce) {
        log.error("连接超时:{}", ce);
    } catch (Exception e) {
        log.error("https请求异常:{}", e);
    }
    return jsonObject;
}
Service实现类
CommonUtil commonUtil = new CommonUtil();
Token token = commonUtil.getToken("wx544ed79f3818e021","d2fe5bb194bf1929b47df7c82323e82c");
WxMssVo wxMssVo = new WxMssVo();
wxMssVo.setTemplate_id("KeFUCUMJZDEo_frO1SeVcIazsw_BtvCHSMhtq2TSj2g");
wxMssVo.setTouser(miniProgramTemplateInfoRequestDTO.getOpenId());
wxMssVo.setPage("pages/index/index");
wxMssVo.setRequest_url("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token.getAccessToken());
wxMssVo.setForm_id(miniProgramTemplateInfoRequestDTO.getFormId());

List<TemplateData> list = new ArrayList<>();
list.add(new TemplateData("通知","#ffffff"));
list.add(new TemplateData("测试数据","#ffffff"));
list.add(new TemplateData("发布成功","#ffffff"));
list.add(new TemplateData(DateFormatUtils.format(new Date(),"yyyy-MM-dd"),"#ffffff"));
wxMssVo.setParams(list);
CommonUtil.sendTemplateMessage(wxMssVo);
如果发送的模板中文乱码 发送请求的代码替换成下面即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值