mitao
2025-01-14 4ea102e9177923f091412bd0c261d651c51725b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.ruoyi.goods.utils;
 
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
 
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author mitao
 * @date 2025/1/10
 */
@Slf4j
public class WeChatSubscribeMessageSender {
    private static final String ACCESS_TOKEN_HOST = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
 
    private static final String WX_APPID = "wxb7f0ea286fc4e535";
 
    private static final String WX_SECRET = "852a2512a6ab559cafc68bae5d4160ac";
    private static final String TEMPLATE_ID = "EFeu75n2GMmOg33PxL1HNoyftp16ukco5DUbBfNBytE";
 
    /**
     *发送消息
     * @param touser  接收者(用户)的 openid
     * @param title  直播主题
     * @param shopName 直播间名称
     * @param aliveStartAt 直播时间
     */
    public static void push(String touser, String title, String shopName, Date aliveStartAt) {
 
        //1,获取access_token
        String accessToken = getAccessTokenByWX();
        String url = API_URL + "?access_token=" + accessToken;
        Map<String, Object> params = new HashMap<>();
        params.put("template_id", TEMPLATE_ID);
        params.put("page", null);
        params.put("touser", touser);
        // 构建订阅消息内容的JSON对象
        JSONObject messageData = new JSONObject();
        messageData.put("thing1", createDataItem("直播主题", title));
        messageData.put("thing4", createDataItem("直播间名称", shopName));
        messageData.put("time5", createDataItem("直播时间", DateUtil.format(aliveStartAt, "MM-dd HH:mm:ss")));
        params.put("data", messageData.toJSONString());
        params.put("miniprogram_state", "trial");
        params.put("lang", "zh_CN");
        try {
            String post = HttpUtil.post(url, JSONObject.toJSONString(params));
            log.info("发送消息返回结果:{}", post);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 获取access_token
     * @return
     */
    public static String getAccessTokenByWX() {
        String host = ACCESS_TOKEN_HOST + "?appid=" + WX_APPID + "&secret=" + WX_SECRET + "&grant_type=client_credential";
        log.info("host:{}", host);
        return HttpUtil.get(host);
    }
    private static Map<String, Object> createDataItem(String name, String value) {
        Map<String, Object> item = new HashMap<>();
        item.put("value", value);
        return item;
    }
 
    public static void main(String[] args) throws Exception {
        push("oL-gp5Fn7BobtFZCsQ3ZTY7QGU84", "直播推送", "鸿瑞堂", new Date());
    }
}