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

一、登陆微信公众号,选中模板消息,添加需要的模板,
在这里插入图片描述

二、在 .properties 配置文件中,记录模板ID
在这里插入图片描述
三、模板文件配置,
-SendTemplateMessageController



public class SendTemplateMessageController {
    /**
     * 发送模板消息sendTemplateMessage
     * 小程序模板消息,发送服务通知
     * @param touser 接收者(用户)的 openid
     * @param template_id 所需下发的模板消息的id
     * @param page 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
     * @param formid 表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
     * @return
     * @throws UnsupportedEncodingException 
     */
    public static JSONObject sendTemplateMessage(String touser, String template_id, 
    		String page, String formid, Map<String, TemplateData> map) {
        String accessToken = getAccessToken();
        SendTemplateMessage sendTemplateMessage = new SendTemplateMessage();
        //拼接数据
        sendTemplateMessage.setTouser(touser);
        sendTemplateMessage.setTemplate_id(template_id);
        sendTemplateMessage.setPage(page);
        sendTemplateMessage.setForm_id(formid);
        sendTemplateMessage.setData(map);
        sendTemplateMessage.setEmphasis_keyword("");
        String json =  JSONObject.toJSONString(sendTemplateMessage);
        String ret = sendPost(MyJwtConfigurer.geSend_template_message()+accessToken, json);
        return JSON.parseObject(ret);
    }
    public static String getAccessToken(){
        String param = "grant_type=client_credential&appid="+MyJwtConfigurer.getAppid()+"&secret="+MyJwtConfigurer.getAppsecret();
        String result = UrlUtils.sendGet(MyJwtConfigurer.geAccess_token(),param);
        JSONObject demoJson = JSONObject.parseObject(result);
        String accessToken = demoJson.getString("access_token");
        String expiresIn = demoJson.getString("expires_in");
        Token token = Token.getInstance();
        token.setAccessToken(accessToken);
        //过期时间的毫秒数
        token.setExpiryTime(System.currentTimeMillis()+1000*60*100L);
        return accessToken;
    }

    /**
     * 发送post请求 json格式
     * @param url
     * @param param
     * @return
     */
    public static String sendPost(String url, String param) {
    	BufferedWriter out = null;     //也可以使用  PrintWriter 但是没有编码设置(字符流)  1-用PrintWriter在服务器上可能消息乱码,《用 -PrintWriter --本地测试正常,发布到服务器就乱码》
        BufferedReader in = null;   //同样为设置编码,获取传回的JSON格式或是文件
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接    
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流    2
//            out = new PrintWriter(conn.getOutputStream());     -----PrintWriter
              out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
            // 发送请求参数     3------PrintWriter
//            out.print(param);
              out.write(param);
              
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

  
}

TemplateData 文件

package com.association.domain;

public class TemplateData {

	private String value;

	   public String getValue() {
	      return value;
	   }

	   public void setValue(String value) {
	      this.value = value;
	   }

	   public TemplateData(String value) {
	      this.value = value;
	   }

	   public TemplateData() {
	   }
}

SendTemplateMessage 文件

package com.association.domain;

import java.util.Map;


/**
 * 发送模板消息
 * @title:SendTemplateMessage
 *  
 * @author juekf
 * @data 2019年9月19日下午3:46:50
 */
public class SendTemplateMessage {

    private String touser; //接收者(用户)的 openid
    private String template_id; //所需下发的模板消息的id
    private String page  = "pages/start/start"; //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
    private String form_id; //表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id
    private Map<String,TemplateData> data; //模板内容,不填则下发空模板
    private String emphasis_keyword; //模板需要放大的关键词,不填则默认无放大
    public String getTouser() {
        return touser;
    }

    public void setTouser(String touser) {
        this.touser = touser;
    }

    public String getTemplate_id() {
        return template_id;
    }

    public void setTemplate_id(String template_id) {
        this.template_id = template_id;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public String getForm_id() {
        return form_id;
    }

    public void setForm_id(String form_id) {
        this.form_id = form_id;
    }

    public Map<String, TemplateData> getData() {
        return data;
    }

    public void setData(Map<String, TemplateData> data) {
        this.data = data;
    }

    public String getEmphasis_keyword() {
        return emphasis_keyword;
    }

    public void setEmphasis_keyword(String emphasis_keyword) {
        this.emphasis_keyword = emphasis_keyword;
    }
}


四、最后在 业务需要的地方:

	/**
					 * 绑定成功 发送微信服务通知
					 */
					Map<String, TemplateData> map = new HashMap<>();
					map.put("keyword1", new TemplateData(account.getLoginName()));
					map.put("keyword2", new TemplateData(account.getLoginName()));
					map.put("keyword3", new TemplateData("绑定成功"));
					map.put("keyword5", new TemplateData("账号 :" + account.getLoginName() + " 与此微信号绑定成功!"));
					Date currentTime = new Date();
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String dateString = formatter.format(currentTime);
					map.put("keyword4", new TemplateData(dateString));

					SendTemplateMessageController.sendTemplateMessage(openid, MyJwtConfigurer.geBinding_success(), "",
							formId, map);

一张是之前的 乱码
在这里插入图片描述

修改后正常了
在这里插入图片描述

到此结束。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

無飞

叠码不易,鼓励鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值