java后端实现小程序订阅消息

java后端实现小程序订阅消息

以下是实现步骤

1.先登录微信公众平台,选择你要做订阅消息的小程序https://mp.weixin.qq.com/

2.进入小程序后,看功能栏目,找到订阅消息在这里插入图片描述
之后选择模板
在这里插入图片描述
如果没有你要的模板,可以手动进行添加,但添加的模板有3到7个工作日的审核时间
在这里插入图片描述
选完模板后,现在正式编写代码

//touser接收的为用户unionid
@GetMapping("/push")
public String SubMessage(String touser, String pagePath) {
    try {
        String userId = getUrl(pagePath, "userId");//名片主键ID
        String id = getUrl(pagePath, "id");//文章ID
        Aicard aicard = aiCardService.selectAicardById(Integer.parseInt(userId));
        Article article = articleService.selectArticleById(Integer.parseInt(id));
        SysUser sysUser = sysUserService.selectUserById(aicard.getUserid().longValue());
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + PosterUtils.getAccess_token();

        WxMessage message = new WxMessage();
        message.setTemplate_id(template_id);//订阅消息模板
        message.setTouser(sysUser.getOpenId());//接收者用户的openId
        message.setPage(page);//跳转的页面pages/customer/customer
        Map<String, TemplateData> map = new HashMap<>(2);
        TemplateData templateData = new TemplateData();
        String title = null;
        if (article.getTitle().length() >= 8) {
            title = article.getTitle().substring(0, 8);
            title = title + "..." + "文章";
        } else {
            title = article.getTitle() + "文章";
        }
        templateData.setValue(title);
        map.put("thing1", templateData);

        TemplateData templateData2 = new TemplateData();
        WxuserVo wxuserVo = wxuserService.selectWxuser(touser, aicard.getUserid());
        templateData2.setValue(wxuserVo.getWxuser());
        map.put("thing2", templateData2);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        TemplateData templateData3 = new TemplateData();
        templateData3.setValue(format);
        map.put("time3", templateData3);//结束查看时间

        WxuserVo wxuser = wxuserService.selectArticle(touser, aicard.getUserid(), null, null);
        TemplateData templateData4 = new TemplateData();
        templateData4.setValue("文章总观看时长 " + tranMinute(wxuser.getDuration()));//观看文章时长;
        map.put("thing4", templateData4);//备注---阅读时长

        message.setData(map);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, message, String.class);
        return responseEntity.getBody();
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("无法订阅消息");
        return "无法订阅消息";
    }
}

这里的template_id就是你刚刚在小程序的订阅消息中选的模板ID,一般是存在配置文件
这里要说明一下模板参数:在这里插入图片描述
画红线的地方就是参数的key名,必须一模一样,具体参考微信文档https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html

这里写的可能不同于往常你们见到的订阅消息,类似于美团小程序,是自己订阅自己看,不同的是用户浏览我分享的朋友圈时,就会发送订阅消息给我,我能实时知道哪些人对我的文章有兴趣,是否能发展为我的客户

对了,我这里是小程序和公众号彼此关联,所以用的是unionid,openId通过另外的方式记录在数据库的

package com.gcs.api.wxDomain;

import lombok.Data;

import java.util.Map;

@Data
public class WxMessage {

    private String touser;//用户unionid
    private String template_id;//订阅消息模版id
    private String page;//默认跳到小程序首页
    //模板消息内容
    private Map<String,TemplateData> data;
}

//这是用于提取链接里的参数
public static String getUrl(String url, String name) {
        url += "&";
        String pattern = "(\\?|&){1}#{0,1}" + name + "=[a-zA-Z0-9]*(&{1})";
        Pattern r = Pattern.compile(pattern);
        Matcher matcher = r.matcher(url);
        if (matcher.find()) {
            return matcher.group(0).split("=")[1].replace("&", "");
        } else {
            return null;
        }
    }

之后是前端代码

methods: {
			message() {
				let that = this
				wx.requestSubscribeMessage({
					tmplIds: ['axeAQE52iPfI3RrlkGXAz28pmZ2sd94CczlQ6LulTGY', '8hzRLICmNJRYLqilrEN8FdZYt0N_ZdKDlxieNRYNRzY'],
						if (res["axeAQE52iPfI3RrlkGXAz28pmZ2sd94CczlQ6LulTGY"] == "accept") { //accept表示同意订阅
							that.isPush = true;
						}
					},
					fail(res) {
						console.log(res);
					},
					complete(res) {
						console.log(res);
					}
				})
			},

			pushMessage() {
				//订阅消息接口
				if (this.isPush == true) { //用户点击确定订阅时才发送
					minRequest.messagePush({
						touser: this.userUnionId,
						template_id: 'axeAQE52iPfI3RrlkGXAz28pmZ2sd94CczlQ6LulTGY',
						page: this.previewUrl,
						miniprogramState: 'developer',
						lang: 'zh_CN',
						data: {
							"thing1": {
								"value": "文章标题"
							},
							"thing2": {
								"value": "访客"
							},
							"time3": {
								"value": "访问时间"
							},
							"thing4": {
								"value": "备注/访问时间"
							}
						}
					}).then((res) => {
						console.log(res)
						return res;
					});
				}
			},

注意:订阅消息一定要点击才能订阅

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值