微信模板消息推送(java實現)

1、獲取Access_token-微信開發文檔
2、模板消息接口-微信開發文檔

首先需要在微信公衆號後臺模板消息中申請模板id,申請好以後可以在模板消息–>我的模板–>模板詳情中查看到具體模板id和模板樣式
例如:
在這裏插入圖片描述

下面就可以開始寫代碼了(就是封裝好具體參數然後,調用微信開放的接口即可):

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
 
import com.google.gson.Gson;
import com.phjr.service.huifu.util.HttpClientUtil;
 
 
import weixn.Demo;
 
 
public class TuiSongTest {
 
 
	private static Logger logger = LoggerFactory.getLogger(TuiSongTest.class);
 
 
	//微信模板接口
	private final String SEND_TEMPLAYE_MESSAGE_URL ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	
	private final String APPID = "";
	private final String SECRET = "";
	//獲取微信ACCESS_TOKEN接口
	private final String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID
	+ "&secret=" + SECRET;
	//openId
	private static  String fromUserName="";
	//模板ID
	private static String template_id="";
	//模板消息詳情跳轉URL
	private static String url="";
	
	
	public static void main(String[] args) {
		TuiSongTest tuiSongTest = new TuiSongTest();
		
		Demo demo = tuiSongTest.getAccess_token();
		String access_token=demo.getAccess_token();
		
		logger.info("爲模板消息接口獲取的accessToken是"+access_token);  
		
		WechatTemplate wechatTemplate = new WechatTemplate();  
		wechatTemplate.setTemplate_id(template_id);  
		wechatTemplate.setTouser(fromUserName);  //此處是用戶的OpenId
		wechatTemplate.setUrl(url); 

	private static Logger logger = LoggerFactory.getLogger(TuiSongTest.class);
 
 
	//微信模板接口
	private final String SEND_TEMPLAYE_MESSAGE_URL ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	
	private final String APPID = "";
	private final String SECRET = "";
	//獲取微信ACCESS_TOKEN接口
	private final String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID
	+ "&secret=" + SECRET;
	//openId
	private static  String fromUserName="";
	//模板ID
	private static String template_id="";
	//模板消息詳情跳轉URL
	private static String url="";
	
	
	public static void main(String[] args) {
		TuiSongTest tuiSongTest = new TuiSongTest();
		
		Demo demo = tuiSongTest.getAccess_token();
		String access_token=demo.getAccess_token();
		
		logger.info("爲模板消息接口獲取的accessToken是"+access_token);  
		
		WechatTemplate wechatTemplate = new WechatTemplate();  
		wechatTemplate.setTemplate_id(template_id);  
		wechatTemplate.setTouser(fromUserName);  //此處是用戶的OpenId
		wechatTemplate.setUrl(url); 

<strong><span style="color:#ff0000">             //根據不同模板 拼寫不同數據</span></strong>

 Map<String,TemplateData> m = new HashMap<String,TemplateData>();  
        TemplateData first = new TemplateData();   
        first.setColor("#000000"); 
        first.setValue("您的一位好友完成了註冊");  
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setColor("#000000");
        keyword1.setValue("136****1234");
        m.put("keyword1", keyword1);  
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor("#000000");
        keyword2.setValue("2018-06-10 10:23:00");
        m.put("keyword2", keyword2);
        TemplateData remark = new TemplateData();
        remark.setColor("#000000");
        remark.setValue("用戶136****1234是您的直接推薦好友");
        m.put("remark", remark);
        wechatTemplate.setData(m);
        try {   
            tuiSongTest.sendTemplateMessage(access_token, wechatTemplate);  
            } catch (Exception e) {       
                logger.info("異常"+e.getMessage());  
        }  
        }
 
    public void sendTemplateMessage(String accessToken, WechatTemplate wechatTemplate) {           String jsonString = new Gson().toJson(wechatTemplate).toString();          String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);        logger.info("請求參數",jsonString);     //發送 post請求 發送json數據     String json = HttpClientUtil.sendHttpPostJson(requestUrl, jsonString);           WeiXinResponse weiXinResponse = new Gson().fromJson(json, WeiXinResponse.class);     logger.info("jsonObject="+weiXinResponse);     if (null != weiXinResponse) {           int errorCode = weiXinResponse.getErrcode();            if (0 == errorCode) {               logger.info("模板消息發送成功");           } else {               String errorMsg = weiXinResponse.getErrmsg();             logger.info("模板消息發送失敗,錯誤是 "+errorCode+",錯誤信息是"+ errorMsg);           }       }   }   public Demo getAccess_token() { try { String access_token = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(aturl); HttpResponse response = client.execute(request); String httpGet = HttpClientUtil.sendHttpGet(aturl); Gson gson=new Gson(); Demo jsonResult=new Demo(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String strResult = EntityUtils.toString(response.getEntity());      System.out.println("get請求結果:" + strResult);         System.out.println("結果回調" +response.getStatusLine().getStatusCode() );          jsonResult = gson.fromJson(strResult, Demo.class); access_token = jsonResult.getAccess_token(); String expires_in =jsonResult.getExpires_in(); logger.info("access_token{}:  expires_in{}:",access_token,expires_in); } return jsonResult; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
        
        
    }

相關實體如下:

public class Demo {
 
	private String access_token;
	
	private String expires_in;
 
	public String getAccess_token() {
		return access_token;
	}
 
	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}
 
	public String getExpires_in() {
		return expires_in;
	}
 
	public void setExpires_in(String expires_in) {
		this.expires_in = expires_in;
	}
	
	
}

import java.util.Map;
 
public class WechatTemplate {
 
	
	private String touser;
	
	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 class TemplateData {
    private String value;  
    private String color;  
  
    public String getValue() {  
        return value;  
    }  
  
    public void setValue(String value) {  
        this.value = value;  
    }  
  
    public String getColor() {  
        return color;  
    }  
  
    public void setColor(String color) {  
        this.color = color;  
    }  
}
public class WeiXinResponse {
 
	private Integer  errcode;
	
	private String errmsg;
	
	private String msgid;
 
	public Integer getErrcode() {
		return errcode;
	}
 
	public void setErrcode(Integer errcode) {
		this.errcode = errcode;
	}
 
	public String getErrmsg() {
		return errmsg;
	}
 
	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}
 
	public String getMsgid() {
		return msgid;
	}
 
	public void setMsgid(String msgid) {
		this.msgid = msgid;
	}
	
	
	
}
 /**
     * 發送 post請求 發送json數據
     * 
     * @param httpUrl
     *            地址
     * @param paramsJson
     *            參數(格式 json)
     * 
     */
    public static String sendHttpPostJson(String httpUrl, String paramsJson) {
        HttpPost httpPost = new HttpPost(httpUrl);// 創建httpPost
        try {
            // 設置參數
            if (paramsJson != null && paramsJson.trim().length() > 0) {
                StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
                stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
                httpPost.setEntity(stringEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

 /**
     * 發送Post請求
     * 
     * @param httpPost
     * @return
     */
    private static String sendHttpPost(HttpPost httpPost) {
 
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        // 響應內容
        String responseContent = null;
        try {
            // 創建默認的httpClient實例.
            httpClient = getHttpClient();
            // 配置請求信息
            httpPost.setConfig(requestConfig);
            // 執行請求
            response = httpClient.execute(httpPost);
            // 得到響應實例
            HttpEntity entity = response.getEntity();
 
 
            // 判斷響應狀態
            if (response.getStatusLine().getStatusCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
            }
 
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
                EntityUtils.consume(entity);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章