• 官方教程
    官方教程

  • 开通一下服务号公众号

  • 超级管理员登录服务号公众号后台
    登录地址

  • 开通模板消息

  • 申请一个模板消息,获取模板ID

    注意此处的参数,后续接口需要使用

  • 绑定公众号与小程序
    官方教程
    1.登录微信公众号后台
    2.点击小程序管理

    3.关联小程序

  • 获取微信公众号APPID
    1.登录微信公众号后台
    2.点击基本配置

  • 导入HTTP依赖

     <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.3.6</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.15</version></dependency>
  • http请求工具类
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
/*** 发送请求工具类*/
public class HttpUtils {private static CloseableHttpClient httpClient;static {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(100);cm.setDefaultMaxPerRoute(20);cm.setDefaultMaxPerRoute(50);httpClient = HttpClients.custom().setConnectionManager(cm).build();}public static String get(String url) {CloseableHttpResponse response = null;BufferedReader in = null;String result = "";try {HttpGet httpGet = new HttpGet(url);RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();httpGet.setConfig(requestConfig);httpGet.setConfig(requestConfig);httpGet.addHeader("Content-type", "application/json; charset=utf-8");httpGet.setHeader("Accept", "application/json");response = httpClient.execute(httpGet);in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));StringBuffer sb = new StringBuffer("");String line = "";String NL = System.getProperty("line.separator");while ((line = in.readLine()) != null) {sb.append(line + NL);}in.close();result = sb.toString();} catch (IOException e) {e.printStackTrace();} finally {try {if (null != response) {response.close();}} catch (IOException e) {e.printStackTrace();}}return result;}public static String post(String url, String jsonString) {CloseableHttpResponse response = null;BufferedReader in = null;String result = "";try {HttpPost httpPost = new HttpPost(url);RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();httpPost.setConfig(requestConfig);httpPost.setConfig(requestConfig);httpPost.addHeader("Content-type", "application/json; charset=utf-8");httpPost.setHeader("Accept", "application/json");httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));response = httpClient.execute(httpPost);in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));StringBuffer sb = new StringBuffer("");String line = "";String NL = System.getProperty("line.separator");while ((line = in.readLine()) != null) {sb.append(line + NL);}in.close();result = sb.toString();} catch (IOException e) {e.printStackTrace();} finally {try {if (null != response) {response.close();}} catch (IOException e) {e.printStackTrace();}}return result;}}
  • 配置类
/*** @Description: 参数配置*/
public class WxAppletConfig {/**小程序appid*/public static String APPLET_APPID="";/**小程序秘钥*/public static String APPLET_SECRET="";/**公众号appid*/public static String  OFFICIAL_ACCOUNT_APPID="";/**公众号模板id*/public static String OFFICIAL_ACCOUNT_TEMPLATE_ID="";}
  • 接口
package com.hk.frame.controller.push;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;import java.util.HashMap;
import java.util.Map;/*** @Description: 小程序推送公众号消息测试*/@Slf4j
@Controller
public class MsgPushTest {/*** 获取token* @return*/public String getAccessToken() {RestTemplate restTemplate = new RestTemplate();Map<String, String> params = new HashMap<>();params.put("APPID", WxAppletConfig.APPLET_APPID);params.put("APPSECRET", WxAppletConfig.APPLET_SECRET);params.put("grant_type", "client_credential");String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?appid={APPID}&secret={APPSECRET}&grant_type={grant_type}";ResponseEntity<String> responseEntity = restTemplate.getForEntity(tokenUrl, String.class, params);String body = responseEntity.getBody();JSONObject object = JSON.parseObject(body);String access_Token = object.getString("access_token");System.err.println("access_Token:"+access_Token);return access_Token;}/*** 推送* @param content* @return*/@ResponseBody@RequestMapping(value = "/testPush",  method = RequestMethod.POST,produces = "application/json;charset=UTF-8")public String push(@RequestBody Map<String, String> content) {//获取需要推送的用户openidString openid= content.get("openid");//获取用户tokenString token = getAccessToken();String resultStatus = "0";//0:失败,1:成功try {//小程序统一消息推送String path = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=" + token;//封装参数JSONObject jsonData = new JSONObject();//小程序用户的openidjsonData.put("touser", openid);JSONObject jsonObject = new JSONObject();//公众号APPIDjsonObject.put("appid", WxAppletConfig.OFFICIAL_ACCOUNT_APPID);//公众号模板IDjsonObject.put("template_id", WxAppletConfig.OFFICIAL_ACCOUNT_TEMPLATE_ID);//公众号模板消息所要跳转的urljsonObject.put("url", "https://blog.csdn.net/qq_46122292/article/details/124961251");//公众号模板消息所要跳转的小程序,小程序的必须与公众号具有绑定关系JSONObject miniprogram = new JSONObject();//小程序APPIDminiprogram.put("appid",WxAppletConfig.APPLET_APPID);//跳转到小程序的页面路径miniprogram.put("pagepath","pages/main_Page/mainPage");jsonObject.put("miniprogram", miniprogram);//公众号消息数据封装JSONObject data = new JSONObject();//此处的参数key,需要对照模板中的key来设置data.put("first", getValue("亲爱的王先生/女士您好,您于2022年07月25日新增加一个客户。"));data.put("keyword1", getValue(content.get("phone")));//联系方式data.put("keyword2", getValue(content.get("time")));//时间data.put("remark", getValue("请前往小程序查看!"));jsonObject.put("data", data);jsonData.put("mp_template_msg", jsonObject);System.out.println("请求参数:"+jsonData);String s = HttpUtils.post(path, jsonData.toJSONString());System.out.println("返回结果:"+s);resultStatus="1";} catch (Exception e) {log.error("微信公众号发送消息失败!",e.getMessage());resultStatus="0";}return resultStatus;}/*** 获取data* @param value* @return*/private JSONObject getValue(String value) {// TODO Auto-generated method stubJSONObject json = new JSONObject();json.put("value", value);json.put("color", "#173177");return json;}
}
  • 测试



注意:前提是该用户得先关注该服务号

微信小程序向公众号推送消息超详细教程相关推荐

  1. uniApp 微信小程序 授权 公众号推送信息

    准本工作 1.首先小程序  更公众号关联起来 2.配置相应的域名(也就是你请求后端接口的公共地址) 3.需要写一个h5 页面 用于跳板 公众号 的授权 公众号如何关联小程序? 打开微信公众号后台,选择 ...

  2. 小程序消息主动推送php,微信小程序有几种推送消息的方式

    微信小程序有5种推送消息的方式,分别为:1.小票机订单提醒,实现对商家的消息提醒:2.短信提醒:3.模板消息,各种动态可及时掌握:4.公众号订单提醒:5.消息主动推送,商家主动出击.推销自己的最好手段 ...

  3. 微信小程序通过服务号推送模板消息

    前言 公司要做一款新的微信小程序,因为业务需求要加入消息推送.因为之前APP是通过服务号推送给用户消息的,所以微信小程序要做消息推送也是首先想到了通过服务号推送.事实上在使用过程中服务号推送还是非常好 ...

  4. 小程序关联公众号推送公众号消息

    最近项目有个需求要把小程序和公众号关联到一起,发布商品,下单的时候的时候给用户推送消息 小程序要跟微信公众号(服务号认证300块,订阅号不行)绑定到一起,要先绑定到微信开放平台(需要认证300块) 绑 ...

  5. uniapp如何使用微信小程序的订阅信息推送消息给用户?

    1.首先获取小程序用户登录openId // 获取openidasync opid() {let self = thiswx.login({success(res) {if (res.code) { ...

  6. 关于微信小程序uniapp版的推送消息

    1.按钮触发推送消息 <button type="primary" size="mini" @tap="pushMesage"> ...

  7. 一图了解App跳转微信小程序关注公众号,推送消息

    一图了解App跳转微信小程序关注公众号,推送消息:

  8. wx小程序,前端公众号推送消息

    wx小程序,前端引导用户关注公众号推送消息 第一步: 在小程序登录后,请求后台得到返回是否关注公众号字段(如果有关注后台是有unionID的),将该字段存入storage中,在首页处拿来判断显隐' 引 ...

  9. 服务器和微信公众号的区别,微信小程序和公众号的区别,看这三点就懂了

    原标题:微信小程序和公众号的区别,看这三点就懂了 第一点就是定位不同,小程序主要用来面向产品和服务,而公众号则是用于销售和传递信息.小程序在功能上和公众号有本质的区别(不支持关注,没有粉丝体系.消息推 ...

最新文章

  1. Mac OS X安装Git
  2. android service是单例么,android 使用单例还是service?
  3. socket未读消息 如何设计_如何设计IM系统的消息架构?
  4. weblogic 的一些说明
  5. 高级计算机网络的基本知识
  6. IE、FF脚本兼容性问题
  7. Bootstrap系列 -- 36. 向上弹起的下拉菜单
  8. ​技术沙龙 | 移动云Teatalk(西安站)带你走进云网融合
  9. JSP 实现 之 读取数据库显示图片
  10. mysql同步一段时间后失败_mysql 主从同步失败后
  11. 《挑战程序设计竞赛》---算法高级篇
  12. java jpa面试题_jpa面试题解析,java面试题
  13. 2019五一建模A题思路
  14. 谷粒商城P46 gulimall-gateway刷新验证码出现503错误
  15. 数字化转型的必要性和意义
  16. A站APP acfun APP产品体验报告
  17. 伤害世界不显示服务器,伤害世界肿么开服务器
  18. 《通用数据保护条例》(GDPR)系列解读二:个人七大数据权利,企业违反或面临2000万罚款
  19. 网易python笔试题_2017秋季网易校园招聘编程题和个人解答(python)
  20. 好看的导航主页html,推荐|各种漂亮的网页导航,让浏览器靓起来

热门文章

  1. 【西瓜书】5-神经网络
  2. STT结构涡轮增压MRAM
  3. Vue(三)使用Vue脚手架
  4. 正则表达式、re函数
  5. 无法打开数据库‘XXXX’。恢复操作已将该数据库标记为SUSPECT或者打开Microsoft SQL Server Management Studio发现数据库被标为可疑的解决办法
  6. 多表的多种连接查询和事务ACID
  7. Python 520告白特技:隐藏在聊天记录里的珍贵礼物
  8. 声网Agora上市,只是云通信产业技术与商业爆发的前夜
  9. rabbitmq vhost
  10. 计算机windows7未能启动,win7开机启动u盘,windows7系统未能启动