微信公众号之模板消息跳转小程序

  • Post author:
  • Post category:小程序


公众号发送模板消息这里就不说了,详情可以去看我之前发的

微信公众号开发之模板消息



前几天因业务需求,需要点击模板消息跳转小程序,所以在此发篇博客记录一下。

在这里插入图片描述

代码如下:

public void textTemplate(String deptExt) throws Exception {
	// 将信息封装到实体类中
	TemplateMessage temp = new TemplateMessage();
	// 设置模板id
	temp.setTemplate_id("模板消息id");
	// 设置接受方的openid
	temp.setTouser("接收方的openid");
	// 设置点击跳转的路径
	temp.setUrl("http://mp.weixin.qq.com");
	// 主要是这里, 设置小程序的appid和转发的页面
	TreeMap<String, String> miniprograms = new TreeMap<String, String>();
	miniprograms.put("appid","小程序的appid");
	miniprograms.put("pagepath","pages/index/index?temp=1");// 注意,这里是支持传参的!!!
	temp.setMiniprogram(miniprograms);
	// 设置消息内容和对应的颜色
	TreeMap<String, TreeMap<String, String>> params = new TreeMap<String, TreeMap<String, String>>();
	// 设置消息内容,具体的按照你选择的模板消息来
	params.put("first", TemplateMessage.item("1", "#173177"));
	params.put("keyword1", TemplateMessage.item(“2”, "#173177"));
	params.put("keyword2", TemplateMessage.item(“3”, "#173177"));
	params.put("keyword3", TemplateMessage.item("4", "#173177"));
	params.put("remark", TemplateMessage.item("5", "#173177"));
	temp.setData(params);
	// 将实体类转换为json格式
	JSONObject data = JSONObject.fromObject(temp);
	System.out.println(data + "");
	// 调用WeChatUtil工具类发送模板消息
	WeChatUtil.sendTemplate(data + "");
}

WeChatUtil是一个工具类,详情可以看我之前发的博客,

微信公众号开发之模板消息



TemplateMessage 是一个封装模板消息的实体类。和之前的有所改变,增加了封装跳转小程序的属性。

import java.util.TreeMap;

public class TemplateMessage {
	private String touser; // 接收者openid

	private String template_id; // 模板ID

	private String url; // 模板跳转链接

	private TreeMap<String, TreeMap<String, String>> data; // data数据
	
	// 新增
	private TreeMap<String, String> miniprogram; // 跳小程序所需数据,不需跳小程序可不用传该数据
	
	/**
	 * 参数
	 * 
	 * @param value
	 * @param color
	 *            可不填
	 * @return
	 */
	public static TreeMap<String, String> item(String value, String color) {
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("value", value);
		params.put("color", color);
		return params;
	}

	//   get / set 已省略

在这里插入图片描述

我打感叹号的地方,有箭头的即为可点击的,也就是添加了点击跳转路径的。可以跳h5页面。设置了跳转小程序所需的参数后,点击就可以进入小程序了。

注意,

跳转的小程序必须是公众号关联的小程序!!!



版权声明:本文为qq_37253891原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。