日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

微信公眾號--根據用戶的opneId發送模版消息

作者:象走日 更新時間: 2022-08-13 編程語言

一、配置模版消息

1、在微信公眾號測試平臺中添加模版消息,注意模版消息有格式要求:
(1)模板中參數內容必須以".DATA"結尾,否則視為保留字;
(2)模板保留符號"{{ }}"

2、獲取template_id(非常重要)


二、使用步驟

1、微信消息推送模版參數類(注意:屬性名寫死的不能改變)

public class WeChatTemplate {
    /**
     * 發送模版消息的openId
     */
    private String touser;
    /**
     * 消息模版id
     */
    private String template_id;
    /**
     * 跳轉的鏈接
     */
    private String url;
    /**
     * 推送的模板內容
     */
    private Map<String, TemplateData> data;

    public String getTouser() {
        return touser;
    }

    public void setTouser(String touser) {
        this.touser = touser;
    }

    public String getTemplate_id() {
        return template_id;
    }

    public void setTemplate_id(String template_id) {
        this.template_id = template_id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Map<String, TemplateData> getData() {
        return data;
    }

    public void setData(Map<String, TemplateData> data) {
        this.data = data;
    }

    public WeChatTemplate(){
    }
}

2、微信消息推送模版內容參數類

public class TemplateData<T> {
    /**
     * 參數內容
     */
    private T value;
    /**
     * 參數字體顏色
     */
    private String color;

    public T getValue() {
        return value;
    }

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

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

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

    public TemplateData() {
    }
}

?3、編寫獲取AccessToken工具類。
access_token是公眾號的全局唯一接口調用憑據,公眾號調用各接口時都需使用access_token。開發者需要進行妥善保存.access_token的有效期目前為2個小時,需定時刷新,重復獲取將導致上次獲取的access_token失效。
接口調用請求說明:

https請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

參數說明:

參數 是否必須 說明
grant_type 獲取access_token填寫client_credential
appid 第三方用戶唯一憑證
secret 第三方用戶唯一憑證密鑰,即appsecret
public class WaChatServiceUtil {

    private final Logger logger = LoggerFactory.getLogger(WaChatServiceUtil.class);

    private static AccessToken at;//token獲取的次數有限,有效期也有限,所以需要保存起來
    private static String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    private static final String APPID="appid";
    private static final String APPSECRET="appsecret";


    public static WaChatServiceUtil getInstance() {
        return WaChatServiceUtil.SingletonWaChatServiceUtil.instance;
    }

    public static String getAPPID() {
        return APPID;
    }

    public static String getAPPSECRET() {
        return APPSECRET;
    }

    private static class SingletonWaChatServiceUtil {
        static final WaChatServiceUtil instance = new WaChatServiceUtil();
    }

    private WaChatServiceUtil() {

    }
    
    /**
     * 發送get請求獲取AccessToken
     */
    private static void getToken() {
        String url = GET_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        //調用工具類發get請求
        String tokenStr = WeChatUtils.sendGet(url);
        System.out.println(tokenStr);
        JSONObject jsonObject = JSONObject.parseObject(tokenStr);
        String token = jsonObject.getString("access_token");
        String expiresIn = jsonObject.getString("expires_in");
        at = new AccessToken(token, expiresIn);
    }

    /**
     * 獲取AccessToken  向外提供
     */
    public static String getAccessToken() {
        //過期了或者沒有值再去發送請求獲取
        if(at == null || at.isExpire()) {
            getToken();
        }
        return at.getToken();
    }
}

?4、編寫請求工具類,用于發模版消息和獲取AccessToken。

public class WeChatUtils {

    private static Logger log = Logger.getLogger(WeChatUtils.class);

    // 1.httpClient發送get
    public static String sendGet(String url) {
        String result = "";
        CloseableHttpResponse response = null;
        try {
            // 根據地址獲取請求
            HttpGet request = new HttpGet(url);// 這里發送get請求
            // 獲取當前客戶端對象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 通過請求對象獲取響應對象
            response = httpClient.execute(request);
            // 判斷網絡連接狀態碼是否正常(0--200都數正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    // 2.httpClient發送post請求 攜帶json數據格式
    public static String sendPost(String url, String jsonStr) {
        CloseableHttpResponse httpResponse = null;
        String result = "";
        try {
            // 1.創建httpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 2.創建post請求方式實例
            HttpPost httpPost = new HttpPost(url);

            // 2.1設置請求頭 發送的是json數據格式
            httpPost.setHeader("Content-type", "application/json;charset=utf-8");
            httpPost.setHeader("Connection", "Close");

            // 3.設置參數---設置消息實體 也就是攜帶的數據
            StringEntity entity = new StringEntity(jsonStr.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8"); // 設置編碼格式
            // 發送Json格式的數據請求
            entity.setContentType("application/json");
            // 把請求消息實體塞進去
            httpPost.setEntity(entity);

            // 4.執行http的post請求
            // 4.執行post請求操作,并拿到結果
            httpResponse = httpClient.execute(httpPost);
            // 獲取結果實體
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "UTF-8");
            } else {
                EntityUtils.consume(httpEntity); 如果httpEntity為空,那么直接消化掉即可
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

5、發送模版消息(注意:Map<String,TemplateDate>中put進去的key必須和模版消息中配置的一致)

public static void followMessage(String openId) {
        try {
            // 發送消息的時間
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateFormat = simpleDateFormat.format(new Date());
            // 獲取AccessToken的值
            String accessToken = WaChatServiceUtil.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            // 獲取消息模版id
            String Message = MessageTemplateEnum.FOLLOW_MESSAGE_TEMPLATE.getKey();
           
            // 設置模版消息的內容
            WeChatTemplate wc = new WeChatTemplate();
            wc.setTouser(openId);
            wc.setTemplate_id(Message);
            wc.setUrl(empowerUrl);
            Map<String, TemplateData> m = new HashMap<>();
            m.put("first", new TemplateData("歡迎關注mamain,點擊下方進行授權", "#000000"));
            m.put("time", new TemplateData(dateFormat, "#000000"));
            m.put("url", new TemplateData("點擊進行授權,獲取您的微信名。", "#173177"));
            m.put("remark", new TemplateData("有疑問請聯系客服!", "#FF0000"));
            wc.setData(m);
            //post發送授權消息模版
            String rString = WeChatUtils.sendPost(url, JSON.toJSONString(wc));
            logger.info("發送授權模版消息結果為:{}", rString);
        } catch (Exception e) {
            logger.error("發送授權模版消息失敗!", e);
        }
    }

6、配置消息模版id枚舉(可不配置?直接寫消息模版id)

public enum MessageTemplateEnum {
    FORM_MESSAGE_TEMPLATE("XB06BH9WC4cy20SQXwpCasS3dOYGQBcCtz1FgzUjsm8", "消息模版1"),
    FOLLOW_MESSAGE_TEMPLATE("JrvIj-h0DHXj7iobo-3kN1a4Gn-suAWA3rFAFkVE9Mg", "消息模版2");

    private String key;

    private String value;

    MessageTemplateEnum(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getDesc() {
        return value;
    }

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

原文鏈接:https://blog.csdn.net/qq_45278588/article/details/126270398

欄目分類
最近更新