栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

微信小程序订阅消息推送(附带后台java代码)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

微信小程序订阅消息推送(附带后台java代码)

官方文档:
小程序前端:点击进入
小程序服务端:点击进入

一,代码实现(后端)

①定义实体类

package com.saic.fin.system.sendInfo;

import lombok.Data;

import java.util.Map;

@Data
public class WxMsgVo {

    private String touser;//用户openId
    private String template_id;//模版id
    private Map data;//推送文字
    private String page="pages/index/index";//跳转路径 ,默认跳转到小程序首页

}
package com.saic.fin.system.sendInfo;

public class TemplateData {
    private String value;

    public TemplateData(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

②定义HttpUtil类(Get请求)

package com.saic.fin.system.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class HttpUtil {
    public static final String APPID = "";//小程序APPID(小程序ID)
    public static final String APPSECRET = "";//小程序APPSECRET(小程序秘钥)
    public static JSONObject doGetJson(String URL) throws IOException {
        JSONObject jsonObject = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            //创建远程url连接对象
            URL url = new URL(URL);
            //通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "application/json");
            //发送请求
            conn.connect();
            //通过conn取得输入流,并使用Reader读取
            if (200 == conn.getResponseCode()) {
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                    System.out.println(line);
                }
            } else {
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            conn.disconnect();
        }
        jsonObject = JSONObject.parseObject(result.toString());
        return jsonObject;
    }
}

③验证token过期时间

package com.saic.fin.system.OfficialAccounts;

import lombok.Data;

@Data
public class AccessToken {
    private String accessToken;
    //过期时间 当前系统时间+微信传来的过期时间
    private Long expiresTime;

    public AccessToken(String accessToken, String expiresIn) {
        this.accessToken = accessToken;
        this.expiresTime = System.currentTimeMillis()+Integer.parseInt(expiresIn)*1000;
    }

    
    public boolean isExpired(){
        return System.currentTimeMillis()>expiresTime;
    }
}

④小程序发送消息

package com.saic.fin.system.sendInfo;

import com.alibaba.fastjson.JSONObject;
import com.saic.fin.system.OfficialAccounts.AccessToken;
import com.saic.fin.system.util.AuthUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

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


public class SendWxMessage {

    public static final String APP_ACCESS_TOKEN_URL= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+HttpUtil.APPID+"&secret="+HttpUtil.APPSECRET;

    private static AccessToken at;
    public static String push(String openid) {
        RestTemplate restTemplate = new RestTemplate();
        String accessToken = getToken();
        //这里简单起见我们每次都获取最新的access_token(时间开发中,应该在access_token快过期时再重新获取)
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        //拼接推送的模版
        WxMsgVo wxMsgVo = new WxMsgVo();
        wxMsgVo.setTouser(openid);//用户的openid(要发送给那个用户)
        wxMsgVo.setTemplate_id("CFeSWarQLMPyPjwmiy6AV4eB-IZcipu48V8bFLkBzTU");//订阅消息模板id
        wxMsgVo.setPage("pages/index/index");

        Map m = new HashMap<>(3);
        m.put("thing1", new TemplateData("课程"));
        m.put("thing6", new TemplateData("大学"));
        m.put("thing7", new TemplateData("一节"));
        wxMsgVo.setData(m);
        ResponseEntity responseEntity =
                restTemplate.postForEntity(url, wxMsgVo, String.class);
        return responseEntity.getBody();
    }


    public static String getToken(){
        if (at == null || at.isExpired()){
            getAccessToken();
        }
        return at.getAccessToken();
    }

    
    private static void getAccessToken() {
        //发送请求获取token
        JSONObject token = null;
        try {
            token = AuthUtil.doGetJson(APP_ACCESS_TOKEN_URL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = token;
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        //创建token对象,并存储
        at = new AccessToken(accessToken,String.valueOf(expiresIn));
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/975998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号