微信发送模板消息

 

1. 在微信公众号上添加模板

在模板库添加自己需要的模板,得到模板ID

我用的模板

 

 2. 获取access_token

private static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    public String getAccessToken() throws Exception {
        String appid = wxConfig.getAppid();//微信公众号申请是获得
        String secret = wxConfig.getSecret();//微信公众号申请是获得
        String url = String.format(URL_ACCESS_TOKEN, appid, secret);
        String body = HttpHelper.doGet(url);//这里使用的是OkHttp轻量级框架
        JSONObject response = JSONObject.fromObject(body);
     String token="";
if(!response.containsKey("errcode")){ token=response.getString("access_token");return token; }else{ throw new Exception(body); } }

3.推送模板消息

模板消息实体类

package com.wqq.test.weixin.frame.oo;

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

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

public class WxTMessage{
    /**接收者openid**/
    private String touser;
    /**模板ID**/
    private String template_id;
    /**模板跳转链接**/
    private String url;
    /**模板数据**/
    private Map<String,Map<String,String>> data = new HashMap<String, Map<String,String>>();
    /**模板内容字体颜色,不填默认为黑色**/
    private String color;
    
    
    /**
     * 添加模板value值
     * @param key
     * @param value
     */
    public void addValue(String key, String value){
        this.addData(key, "value", value);
    }
    
    /**
     * 添加模板color值
     * @param key
     * @param color
     */
    public void addColor(String key, String color){
        this.addData(key, "color", color);
    }
    
    /**
     *  添加模板元素值:value,color
     * @param key
     * @param item
     */
    public void addParams(String key, Item item){
        this.addParams(key, item.value, item.color);
    }
    
    /**
     * 添加模板数据
     * @param key
     * @param hkey
     * @param hvalue
     */
    public void addData(String key, String hkey, String hvalue){
        Map<String,String> hmap = data.get(key);
        if(hmap == null){
            hmap = new HashMap<String,String>();
            data.put(key, hmap);
        }
        hmap.put(hkey, hvalue);
    }
    
    /**
     * 添加模板元素值:value,color
     * @param key
     * @param value
     * @param color
     */
    public void addParams(String key, String value, String color){
        Map<String,String> hmap = data.get(key);
        if(hmap == null){
            hmap = new HashMap<String,String>();
            data.put(key, hmap);
        }
        hmap.put("value", value);
        hmap.put("color", color);
    }
    
    /**
     * 转化为JSON字符串
     * @return
     */
    public String toJSONString(){
        JsonConfig config = new JsonConfig();
        config.setJsonPropertyFilter(new PropertyFilter() {
            @Override
            public boolean apply(Object source, String name, Object value) {
                return value == null || StringUtils.isBlank(value.toString());
            }
        });
        return JSONObject.fromObject(this, config).toString();
    }
    
    //---------------------------------------------------------------------------
    // getter/setter
    //---------------------------------------------------------------------------

    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, Map<String, String>> getData() {
        return data;
    }

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

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
   public static class Params{
        String value;
        String color;
        
        public Params(String value, String color) {
            super();
            this.value = value;
            this.color = color;
        }
    }
}

 

 发送消息

private static final String SEND_TEMPLATE_MESSAGE="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
public void testMessage(){
        WxTMessage message=new WxTMessage();
        
        message.setTemplate_id("EzJ1LYo-PeBwDpBB8gG4NeWTdv2gmqExY304UTWAGco");
        message.setTouser("xxxxxxxxxxxx");//接受者的openID
        message.setUrl("https://www.baidu.com/");
        
        message.addParams("first", "测试:用来测试的呀", "");
        message.addParams("content", "没了", "#4895de");
        message.addParams("occurtime", "2018-04-27 11:14:52", "#666666");
        message.addParams("remark", "请随时关注处理!","");

        String token=getAccessToken();
      
        String url = String.format(SEND_TEMPLATE_MESSAGE, token);
        String body = HttpHelper.doPost(url, message.toJSONString());//使用OkHttp框架
        JSONObject response = JSONObject.fromObject(body);
        if(null!=response){
            if("0".equals(response.getString("errcode"))){
                System.out.println("发送模板消息成功");
                return true;
            }else{
                throw new Exception("发送模板消息失败: "+response.getString("errcode"));
            }
        }else{
            throw new Exception("response为空");
        }
    }    

 

 测试结果

 

 ps:模板消息中可以拼接"\n"来控制行

 

最近一直在做微信相关的东西,为防止以后自己忘记,先记下一些基础的功能,今天发的是关于微信发送模板消息,哎,字数不够,这句话是用来凑字数

 

posted on 2018-05-23 11:04  背着核的桃子  阅读(1470)  评论(0编辑  收藏  举报

导航