• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
axuuww
博客园    首页    新随笔    联系   管理    订阅  订阅
向关注公众号的所有用户发送公众号消息

需求: 简单的向关注公众号的用户发送消息(SpringBoot框架下使用)

1.首先获得公众号配置

注: 如果是测试,可申请测试公众号 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
申请之后会得到
配置信息

模板信息和用户列表

2.发送公众号信息

1.配置文件
wxsendmsg:
  #微信公众号appid
  appid: wx71eab5e698feb424sss
  #微信公众号appidsecret
  appidsecret: 7169487cd50d69c70a1bcsd92fafa5ssasv
  #微信公众号tokenurl
  gettokenurl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=
  #微信公众号发送消息
  sendrequesturl: https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=
  #微信公众号获得关注用户列表url
  getusersurl: https://api.weixin.qq.com/cgi-bin/user/get?access_token=
  #微信公众号消息模板id
  templateid: QKBbSrPNqeCb1NE14uE1ASuQQPSvoDijGJINIvvjY2Y

注意项: 对于获取token、获取用户、发送请求对应三个不同的路径,这个要区分开,不然容易高混乱

@Value(value = "${wxsendmsg.appid}")
private String appid;
@Value(value = "${wxsendmsg.appidsecret}")
private String appidsecret;
@Value(value = "${wxsendmsg.sendrequesturl}")
private String sendrequesturl;
@Value(value = "${wxsendmsg.templateid}")
private String templateid;
@Value(value = "${wxsendmsg.gettokenurl}")
private String gettokenurl;
@Value(value = "${wxsendmsg.getusersurl}")
private String getusersurl;
2.获得access_token
public String getAccessToken() {
  	//将access_token存入redis
        Object o = redisUtil.get(ACCESSTOKEN + appid);
        if (o != null) {
            log.info("access_token : {}", o.toString());
            return o.toString();
        }else {
            String requestUrl = gettokenurl + appid + "&secret=" + appidsecret;
            String res = HttpUtil.get(requestUrl);
            JSONObject jsonObject = JSONObject.fromObject(res);
            String accessToken = jsonObject.getString("access_token");
            redisUtil.set(ACCESSTOKEN + appid, accessToken);
            redisUtil.expire(ACCESSTOKEN + appid, JwtUtil.EXPIRE_TIME);
            log.info("access_token : {}", accessToken);
            return accessToken;
        }
    }
3.获得关注公众号的用户信息
//这里我将用户的信息都存入到列表中
public List<String> getOpenids(String accessToken) {
        RestTemplate restTemplate = new RestTemplate();
        String requestUrl = getusersurl + accessToken;
        ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, null, String.class);
        log.info("结果是: {}", response.getBody());
        com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
        com.alibaba.fastjson.JSONArray openIdJsonArray = result.getJSONObject("data").getJSONArray("openid");
        Iterator iterator = openIdJsonArray.iterator();
        List<String> openids = new ArrayList<>();
        while (iterator.hasNext()) {
            openids.add(iterator.next().toString());
        }
        return openids;
    }
4.配置消息类(样式+内容)
@Data
public class WeChatTemplateMsg {
    /**
     * 消息
     */
    private String value;
    /**
     * 消息颜色
     */
    private String color;

    public WeChatTemplateMsg(String value) {
        this.value = value;
        this.color = "#173177";
    }

    public WeChatTemplateMsg(String value, String color) {
        this.value = value;
        this.color = color;
    }
}

注: 此类必须要有get和set方法,不然会报转换错误

5.发送消息
 // 模板参数
        Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();
  	 sendMag.put("person", new WeChatTemplateMsg(wxMsg));
private void sendToOpenid(Map<String, WeChatTemplateMsg> sendMag, String openids, String templateid, String requestUrl) {
        RestTemplate restTemplate = new RestTemplate();
        //拼接base参数
        Map<String, Object> sendBody = new HashMap<>();
        sendBody.put("touser", openids);               // openId  用户id
        sendBody.put("url", "https://www.baidu.com");  //跳转网页url
        sendBody.put("data", sendMag);                   // 模板参数  
        sendBody.put("template_id", templateid);      // 模板Id
        ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, sendBody, String.class);
        log.info("结果是: {}", response.getBody());
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response.getBody());
        String messageCode = jsonObject.getString("errcode");
        String msgId = jsonObject.getString("msgid");
        log.info("messageCode : {},msgId : {}", messageCode, msgId);
    }
posted on 2024-02-01 17:38  雁来月~十一  阅读(147)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3