小程序订阅消息步骤

官司链接

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html
 

一、开通订阅号权限,再找个模板练手

二、后台写发送模板方法

1、获取接口调用凭证  access_token

	public String  getAccessToken() {
		MY_LOGGER.info("  getAccessToken ");
		MY_LOGGER.info(xcxAppId);
		MY_LOGGER.info(xcxAppSecret);
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + xcxAppId
				+ "&secret=" + xcxAppSecret;
		String rt = HttpTookit.doGet(url, "", "utf-8", false);
		if (rt.length() > 0) {
			JSONObject jsStr = JSONObject.fromObject(rt);
			MY_LOGGER.info(jsStr.toString());
			return (String) jsStr.get("access_token");
		}
		return "";
	}

 2、根据模板Id,封装模板内容

package com.superPdf.web.util;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

/**
 * 小程序消息推送模板
 *
 */
public class TemplateMessageUtil {
	//视频会议通知
	private static String  VEDIO_TEMP_ID = "3rIR_YjvsztlbV8JgehsWE7N4H8es9XLYioMtlgF9RI";
	/**
	 * 根据模板号返回data数据格式
	 * @param tempId  模板号 
	 * @param str1     参数1
	 * @param str2 	参数2
	 * @param str3	参数3
	 * @return
	 */
	public static JSONObject queyDataByTempId(String tempId,String jsonObjstr){
		JSONObject rs = null;
		if(tempId.equals(VEDIO_TEMP_ID)) {
			rs = queryVedioTemp(jsonObjstr);
		}
		return rs;
	}
	/**视频会议通知
	 * 详细内容
		发起人		{{name1.DATA}}
		发起时间		{{date2.DATA}}
		会议内容		{{thing3.DATA}}
		参与人		{{thing4.DATA}}
}
订阅消息参数值
	 * @return
	 */
	private static JSONObject queryVedioTemp(String jsonObjstr) {
		String name1 = "公司";
		String date2 = JrjbxUtils.getCurrentTime();
		String thing3 = "会议";
		String thing4 = "全体员工";
		if(jsonObjstr!=null && !"".equals(jsonObjstr)) {
			JSONObject jo = JSONObject.fromObject(jsonObjstr);
			if(jo != null) {
				if( jo.has("name1") &&  (jo.get("name1")!=null && !"".equals(jo.get("name1")) ) ) {
					name1 = (String) jo.get("name1");
				}
				if( jo.has("date2") &&  (jo.get("date2")!=null && !"".equals(jo.get("date2")) ) ) {
					name1 = (String) jo.get("date2");
				}
				if( jo.has("thing3") &&  (jo.get("thing3")!=null && !"".equals(jo.get("thing3")) ) ) {
					name1 = (String) jo.get("thing3");
				}
				if( jo.has("thing4") &&  (jo.get("thing4")!=null && !"".equals(jo.get("thing4")) ) ) {
					name1 = (String) jo.get("thing4");
				}
			}
		}
		Map<String,String> temp = new HashMap<>();
		temp.put("value", name1);
		JSONObject jsonObj = new JSONObject();
        jsonObj.put("name1",JSONObject.fromObject(temp));
        temp.put("value", date2);
        jsonObj.put("date2",JSONObject.fromObject(temp));
        temp.put("value", thing3);
        jsonObj.put("thing3",JSONObject.fromObject(temp));
        temp.put("value", thing4);
        jsonObj.put("thing4",JSONObject.fromObject(temp));
		return jsonObj;
	}
	

}

3、获取参数发送请求

    /**
     * 发送订阅消息sendTemplateMessage
     * 小程序订阅消息,发送服务通知
     * @param touser     接收者(用户)的 openid
     * @param templateId 所需下发的模板消息的id
     * @param page       点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例    index?foo=bar)。该字段不填则模板无跳转。
     * @param jsonObj    模板里的信息,不传则用默认值
     * @throws Exception 
     * @throws URISyntaxException 
     * @throws ClientProtocolException 
     */
	@RequestMapping(value = "/sendTemplateMessage")
    public  void sendTemplateMessage(HttpServletRequest request, HttpServletResponse response)  {
    	String touser = ServletRequestUtils.getStringParameter(request, "touser", "");
    	String templateId = ServletRequestUtils.getStringParameter(request, "templateId", "");
    	String page = ServletRequestUtils.getStringParameter(request, "page", "1");
    	String jsonObj = ServletRequestUtils.getStringParameter(request, "jsonObj", "");
    	try {
    	     String accessToken = getAccessToken();
    	        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken;
    	        JSONObject data = TemplateMessageUtil.queyDataByTempId(templateId,jsonObj);
    	        MY_LOGGER.info("data  "+data.toString());
    	        Map<String, Object>  params = new HashMap<>();
    	        params.put("touser", touser);
    	        params.put("template_id", templateId);
    	        params.put("page", page);
    	        params.put("data", data);
    	        params.put("miniprogram_state", "trial");
    	        JSONObject jo = JSONObject.fromObject(params);
    	        String rs = HttpTookit.call(url, jo.toString(), "utf-8");
    	        MY_LOGGER.info("rs  "+rs);
		} catch (Exception e) {
			e.printStackTrace();
			MY_LOGGER.error(e.getMessage());
		}
    }

 三、小程序触发推送

1、调起客户端小程序订阅消息界面。tempId为模板Id

			sendMsgSubscribe(){
				let that = this;
				wx.getSetting({
				  withSubscriptions: true,
				  success (res) {
				    console.log(res.subscriptionsSetting)
					if(res.subscriptionsSetting.mainSwitch){
						 that.sendMsg();
					}else if(res.subscriptionsSetting.mainSwitch.itemSettings){
						var itemSettings = res.subscriptionsSetting.mainSwitch.itemSettings;
						var tempId = "3rIR_YjvsztlbV8JgehsWE7N4H8es9XLYioMtlgF9RI";
						if(itemSettings.tempId){
								that.sendMsg();
						}
					}else{
						wx.requestSubscribeMessage({
						  tmplIds: ['3rIR_YjvsztlbV8JgehsWE7N4H8es9XLYioMtlgF9RI'],
						  success (res) { 
							 that.sendMsg();
						  }
						})
					}
				  }
				})
			},
			sendMsg(){
				let that = this;
				const res = that.$myRequest({
					url:'api/sendTemplateMessage',
					data:{
						touser:that.userInfo.wx_open_id,
						templateId:'3rIR_YjvsztlbV8JgehsWE7N4H8es9XLYioMtlgF9RI'
					}
				});
			},

注意:点击订阅消息推送的消息,跳转只能跳转到正式版。体验版本和开发版本都不行

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值