微信小程序推送功能最新版本(推送到服务通知java+微信小程序代码块) - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

微信小程序推送功能最新版本(推送到服务通知java+微信小程序代码块)

发表时间:2020-9-29

发布人:葵宇科技

浏览次数:224

     微信小程序的消息推送简单的说就是发送一条微信通知给用户,用户点开消息可以查看消息内容,可以链接进入到小程序的指定页面。

一、准备工作
首先,在微信公众平台开通消息推送功能,并添加消息模板。可以从模板库选择模板也可以创建一个模板,模板添加之后,模板ID我们接下来要用的。
在这里插入图片描述
然后拿到小程序的APPID和秘钥 在这里插入图片描述
二~打开微信开发工具
加一个按钮就可以,用这个按钮去触发这个函数方法

,//记得添加逗号哦。
  sendDYMsg: function(e) {
    wx.requestSubscribeMessage({
      tmplIds: ['ooaZWfK6liHpqDAcnR2hgObdQuh2JqQP2Z_UR6vvraU'],
      success(res) {
        console.log("可以给用户推送一条中奖通知了。。。");
      }
    })
  }

tmplIds是你小程序的模板id,触发这个函数会弹出下面的方框
在这里插入图片描述
三、服务端(java)代码开发:
1、老规矩先查看官网腾讯api文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html

在这里插入图片描述
2、给大家介绍一个关于微信开发的工具类(个人感觉非常优秀,可以自己去看看。):

git地址:https://github.com/Wechat-Group/WxJava

小程序文档地址:http://binary.ac.cn/weixin-java-miniapp-javadoc/

3.集成pom文件:

 <!-- 小程序开发包-->
        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-miniapp</artifactId>
            <version>3.6.0</version>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
 
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.1.21</version>
        </dependency>

4.根据code获取openid:
code:(重点)只能使用一次,并且只有5分钟有效期
在这里插入图片描述

/*
获取openid
 */

    private static  String getOpenid(String code){
        //临时登录凭证
        String URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID1+"&secret="+AppSecret1+"&js_code="+code+"&grant_type=authorization_code";
        String openId=interfaceUtil(URL, "");
        return openId;
    };

这个openid必须是小程序的openid其他的openid不可以
5.最终环节进行小程序订阅消息推送

订阅消息传参和模板消息是不一样的,需要根据人家规则进行填写,加了正则校验了
在这里插入图片描述
在这里插入图片描述
推送代码

 /**
     * 微信小程序推送订阅消息
     * create By KingYiFan>@GetMapping(value = "/messagePush")
    @ResponseBody
    public Object sendDYTemplateMessage(String openId) throws Exception {

        System.err.println("openId:"+openId);
        wxsmallTemplate tem = new wxsmallTemplate();
        //跳转小程序页面路径
        tem.setPage("pages/index/index");
        //模板消息id
        tem.setTemplate_id("-UBAuupYlK2RAbxYvhk6UvK48ujQD72RpEOdkF-sJ2s");
        //给谁推送 用户的openid (可以调用根据code换openid接口)
        tem.setToUser(openId);
        //==========================================创建一个参数集合========================================================

        List<wxsmallTemplateParam> paras = new ArrayList<wxsmallTemplateParam>();
        //这个是满参构造 keyword1代表的第一个提示  红包已到账这是提示 #DC143C这是色值不过废弃了
      wxsmallTemplateParam templateParam = new wxsmallTemplateParam(
                "thing2", "红包已到账", "#DC143C");

        paras.add(templateParam);
        paras.add(new wxsmallTemplateParam("phrase3", "刘骞", ""));
        tem.setData(paras);
        //模板需要放大的关键词,不填则默认无放大
        tem.setToken(getAccessToken());
        //=========================================封装参数集合完毕========================================================
        try {
            //进行推送
            //获取微信小程序配置:
            if(sendTemplateMsg1(getAccess_token(APPID1,AppSecret1), tem)){
                return "推送成功";
            }else{
                JSONObject jsonObject = new JSONObject();   //返回JSON格式数据
                jsonObject.put("buTie",tem);
                return jsonObject;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "推送失败";
    }

    public static boolean sendTemplateMsg1(String token,wxsmallTemplate template) {
        System.err.println("token:"+token);
        boolean flag = false;

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

        requestUrl = requestUrl.replace("ACCESS_TOKEN", token);
        JSONObject jsonResult =JSON.parseObject(post(JSON.parseObject(template.toJSON()) ,requestUrl)) ;
        if (jsonResult != null) {
            Integer errorCode = jsonResult.getInteger("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
            } else {
                System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        }
        return flag;
    }

    public String getAccess_token(String appid, String appsecret) {
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret;
//                      https://api.weixin.qq.com/cgi-bin/token.
        JSONObject jsonObject = doGet1(url);
        System.out.println(jsonObject.toString());
        String errCode = jsonObject.getString("expires_in");
        if (!StringUtils.isEmpty(errCode)  && !StringUtils.isEmpty(jsonObject.getString("access_token").toString())) {
            String token = jsonObject.get("access_token").toString();
            return token;
        } else {
            return null;
        }
    }

    public static JSONObject doGet1(String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        try {
            HttpResponse httpResponse = client.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //        释放连接
                httpGet.releaseConnection();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }
    //post请求
public static String post(JSONObject json,String URL) {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        String result = "";

        try {

            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);

            // 发送请求
            HttpResponse httpResponse = client.execute(post);

            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();

            result = strber.toString();
            System.out.println(result);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功,做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }

        return result;
    }

在这里插入图片描述
到现在微信小程序订阅消息推送就到此结束了,是不是超级简单那种。

给大家分享一个,只给用户提示一次,下次就不用提示就可以一直发送通知的方案: 微信设置了总是保持以上选择,不在询问按钮,只要把这对勾给点击上。下次点击通知函数,就不会给用户提示哦。 我给点击了按钮,到现在我都没找到从哪能开启这个提示。

在这里插入图片描述

相关案例查看更多