微信公眾號(hào)發(fā)送模板消息

1、添加模板消息插件
      登錄微信公眾平臺(tái),點(diǎn)擊添加插件,把模板消息添加到功能中
添加插件
2、添加我的模板

點(diǎn)擊模板消息之后呢會(huì)出現(xiàn)我的模板和模板庫(kù),我們點(diǎn)擊模板庫(kù)在模板庫(kù)中選擇自己想要的模板或者提交申請(qǐng)自己新建的模板(點(diǎn)擊完善模板庫(kù)),微信要審核比較慢,一個(gè)月只能提交3次,模板庫(kù)就沒(méi)有限制

點(diǎn)擊詳情,添加即可

添加之后就可以在我的模板庫(kù)中看到你添加的模板,點(diǎn)擊詳情


可以看到模板ID和模板需要的參數(shù)
3、請(qǐng)求接口發(fā)送模板消息

點(diǎn)擊模板消息文檔可以看到微信提供的文檔,查看需要請(qǐng)求的接口


需要一個(gè)參數(shù)access_token

繼續(xù)看需要封裝的參數(shù),是一個(gè)json

{
    "touser": "OPENID",
    "template_id": "ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
    "url": "http://weixin.qq.com/download",
    "topcolor": "#FF0000",
    "data": {
        "User": {
            "value": "黃先生",
            "color": "#173177"
        },
        "Date": {
            "value": "06月07日 19時(shí)24分",
            "color": "#173177"
        },
        "CardNumber": {
            "value": "0426",
            "color": "#173177"
        },
        "Type": {
            "value": "消費(fèi)",
            "color": "#173177"
        },
        "Money": {
            "value": "人民幣260.00元",
            "color": "#173177"
        },
        "DeadTime": {
            "value": "06月07日19時(shí)24分",
            "color": "#173177"
        },
        "Left": {
            "value": "6504.09",
            "color": "#173177"
        }
    }
}

構(gòu)建發(fā)送消息模板對(duì)象

/** 跟上圖json對(duì)應(yīng) */
public class WechatTemplateReq {
    /**  openId */
    private String touser;
    /** 模板Id */
    private String template_id;
    /** 跳轉(zhuǎn)url */
    private String url;
    /** 參數(shù) key為參數(shù)名 --- value為參數(shù)值和顏色 */
    private Map<String, FirstBean> data;
}
public class FirstBean {
    /** 值 */
    private String value;
    /** 顏色 */
    private String color;
}

發(fā)送請(qǐng)求

//導(dǎo)入需要發(fā)送請(qǐng)求的jar包
  <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpclient</artifactId>
       <version>4.5.2</version>
  </dependency>
public String sendTemplateMessage(){
    //自己替換成自己項(xiàng)目的accessToken,具體可參照微信的獲取accesstoken的方法
    String accessToken = "";
    //替換成自己公眾號(hào)用戶(hù)的openId
    String openId = "";
    //自己的模板Id
    String templateId = "";
    //點(diǎn)擊模板之后跳轉(zhuǎn)的地址
    String toUrl = "";
    //拼接url
    String url= "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
    String requestUrlWithToken = String.format(url, accessToken);
    //構(gòu)建模板對(duì)象
    WechatTemplateReq wechatTemplateReq = new WechatTemplateReq();
    wechatTemplateReq.setTouser(openId);
    wechatTemplateReq.setTemplate_id(templateId);
    wechatTemplateReq.setUrl(toUrl);
    Map<String,FirstBean> map = new HashMap<>(5);
    map.put("first",new FirstBean("模板頭部參數(shù)","#173177"));
    map.put("keyword1",new FirstBean("模板key1參數(shù)","#173177"));
    map.put("keyword2",new FirstBean("模板key2參數(shù)","#173177"));
    map.put("keyword3",new FirstBean("模板key3參數(shù)","#173177"));
    map.put("remark",new FirstBean("模板注釋參數(shù)","#173177"));
    wechatTemplateReq.setData(map);
    //轉(zhuǎn)化為json
    String body = JsonUtils.jsonFromObject(wechatTemplateReq);
    //發(fā)送模板消息
    String result = HttpRequestUtils.httpPostJson(requestUrlWithToken, body);
    logger.info("向公眾號(hào)發(fā)送模板消息返回值httpPostJson result:{}", result);
}
//發(fā)送消息工具類(lèi)
public static String httpPostJson(String url, String jsonParam) {
        HttpPost method = new HttpPost(url);
        String response = "";
        if (null != jsonParam) {
            StringEntity entity = new StringEntity(jsonParam, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            method.setEntity(entity);
        }
        try (CloseableHttpClient client = HttpClients.createDefault();
                CloseableHttpResponse result = client.execute(method)) {
            url = URLDecoder.decode(url, "UTF-8");
            /** 請(qǐng)求發(fā)送成功,并得到響應(yīng) **/
            if (result.getStatusLine().getStatusCode() == 200) {
                try {
                    /** 讀取服務(wù)器返回過(guò)來(lái)的json字符串?dāng)?shù)據(jù) **/
                    response = EntityUtils.toString(result.getEntity());
                    logger.debug("response from url:{} ,response:{}", url, response);
                } catch (Exception e) {
                    logger.error("post請(qǐng)求提交異常:" + url, e);
                }
            } else {
                logger.error("Request url:" + url + ",and response:" + result.toString());
            }
        } catch (IOException e) {
            logger.error("post請(qǐng)求提交失敗:" + url, e);
        }

        return response;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容