当前位置:首页 » 《随便一记》 » 正文

java发送公众号/服务通知模板消息到指定用户(完整流程|亲测可用)

8 人参与  2022年09月23日 13:43  分类 : 《随便一记》  评论

点击全文阅读


1、java发送服务通知模板消息到指定用户

准备:

获取当前微信小程序appId(小程序appId)获取当前小程序的秘钥secret
在这里插入图片描述新建模板消息
在这里插入图片描述
选用后勾选需要的字段并提交
一次订阅:
指用户订阅一次,服务号可不限时间地下发一条对应的订阅通知;
长期订阅:
指用户订阅一次,服务号可长期多次下发通知,长期订阅通知仅向政务民生、医疗,交通,金融等公共服务领域开放,比较难申请;
服务通知:
微信默认开启服务通知功能,在用户聊天列表中会出现橙色的服务通知
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

后端代码实现:

微信发送服务通知工具类

import com.alibaba.fastjson.JSONObject;import com.shop.cereshop.commons.utils.third.IdWorker;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Component;import org.springframework.web.client.RestTemplate;import java.io.*;import java.net.URL;import java.net.URLConnection;import java.text.SimpleDateFormat;import java.util.*;/** * @ClassName WechatUtil * @Version 1.0 */@Slf4j(topic = "WxchatSendUtil")@Componentpublic class WxchatSendUtil {   @Value("${bussiness.appId}")   private static String appId;   @Value("${bussiness.secret}")   private static String secret;   @Value("${bussiness.orderPlacementNoticeTemplateId}")   private static String orderPlacementNoticeTemplateId;   /**    * 获取小程序token    *    * @return    */   public static String getAccessToken() {      String url = "https://api.weixin.qq.com/cgi-bin/token?" +            "appid=" + appId + "&secret=" + secret + "&grant_type=client_credential";      PrintWriter out = null;      BufferedReader in = null;      String line;      StringBuffer stringBuffer = new StringBuffer();      try {         URL realUrl = new URL(url);         // 打开和URL之间的连接         URLConnection conn = realUrl.openConnection();         // 设置通用的请求属性 设置请求格式         //设置返回类型         conn.setRequestProperty("contentType", "text/plain");         //设置请求类型         conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");         //设置超时时间         conn.setConnectTimeout(1000);         conn.setReadTimeout(1000);         conn.setDoOutput(true);         conn.connect();         // 获取URLConnection对象对应的输出流         out = new PrintWriter(conn.getOutputStream());         // flush输出流的缓冲         out.flush();         // 定义BufferedReader输入流来读取URL的响应    设置接收格式         in = new BufferedReader(               new InputStreamReader(conn.getInputStream(), "UTF-8"));         while ((line = in.readLine()) != null) {            stringBuffer.append(line);         }         JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());         return jsonObject.getString("access_token");      } catch (Exception e) {         e.printStackTrace();      }      //使用finally块来关闭输出流、输入流      finally {         try {            if (out != null) {               out.close();            }            if (in != null) {               in.close();            }         } catch (IOException ex) {            ex.printStackTrace();         }      }      return null;   }   public static final String SEND_INFO_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";   public static void main(String[] args) throws IOException {      // 1、获取 接口调用凭证      RestTemplate restTemplate = new RestTemplate();      String url =  SEND_INFO_URL  + WxchatSendUtil.getAccessToken();      //拼接推送的模版      WxMssVO wxMssVo = new WxMssVO();      //用户的openId      wxMssVo.setTouser("oa4u44ukI8wbYO3it-ysAm_yNJSo");      //订阅消息模板id      wxMssVo.setTemplate_id(orderPlacementNoticeTemplateId);//    wxMssVo.setPage("pages/appointment/line_up?"+"shopId="+info.getShopId());      Map<String, TemplateData> m = new HashMap<>(4);      m.put("character_string36", new TemplateData(IdWorker.generSequeId()));      m.put("thing2", new TemplateData("用户下单通知啊"));      m.put("phrase28", new TemplateData("待付款"));      SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      m.put("time10", new TemplateData(simpleDateFormat.format(new Date())));      wxMssVo.setData(m);      ResponseEntity<String> responseEntity =            restTemplate.postForEntity(url, wxMssVo, String.class);      System.out.println(responseEntity.getBody());   }}

WxMssVO

import lombok.Data;import java.util.Map;/** * @author ys */@Datapublic class WxMssVO {    /**     * 用户openid     */    private String touser;    /**     * 订阅消息模版id     */    private String template_id;    /**     * 默认跳到小程序首页     */    private String page;    /**     * 推送文字     */    private Map<String, TemplateData> data;}

TemplateData

import lombok.AllArgsConstructor;import lombok.Data;/** * @author ys */@AllArgsConstructor@Datapublic class TemplateData {    private String value;}

前端代码实现:

用户在在开发者提供的 H5 页面中,通过 JSSDK 拉起订阅按钮
在这里插入图片描述
wx.requestSubscribeMessage

<button bindtap="getAuthority" type='primary'>获取订阅消息授权</button> //获取授权的点击事件 getAuthority() { wx.requestSubscribeMessage({//这里填入我们生成的模板idtmplIds: ['CFeSWarQL*************8V8bFLkBzTU'],success(res) { console.log('授权成功', res) }, fail(res) { console.log('授权失败', res) } })}

2、java发送


点击全文阅读


本文链接:http://zhangshiyu.com/post/45053.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1