微信公众号消息推送-模板消息发送
生活随笔
收集整理的這篇文章主要介紹了
微信公众号消息推送-模板消息发送
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先注冊一個微信公眾號;或者申請接口測試號來進行開發;
接口測試號申請鏈接:
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
這里先介紹測試號的開發;
點擊鏈接進入頁面,會看到y一個二維碼,用微信掃描后就會分配給你一個微信公眾測試賬號;
然后找到如下這個位置,點擊“新增測試模板”按鈕,填寫
?
下面是相關代碼;
@Testpublic void sendTemplate(){postTemplateMsg("appid","appSecret", "openId");//這里替換成你自己的信息}public String sendTemplateMessage(String openId){TemplateMsg tm=new TemplateMsg();tm.setTouser(openId);tm.setTemplate_id("模板Id");tm.setUrl("https://wwww.baidu.com");//about data startMap<String,Object> m = new HashMap<String,Object>(); TemplateData first = new TemplateData(); first.setColor("#000000"); first.setValue("您好,您有一個流程待辦需要處理:"); m.put("first", first); TemplateData keyword1 = new TemplateData(); keyword1.setColor("#000000"); keyword1.setValue("11111111111111"); m.put("keyword1", keyword1); TemplateData keyword2 = new TemplateData(); keyword2.setColor("#000000"); keyword2.setValue("愛你一萬年"); m.put("keyword2", keyword2); TemplateData keyword3 = new TemplateData(); keyword3.setColor("#000000"); keyword3.setValue("2018.04.27 09:51:30"); m.put("keyword3", keyword3); TemplateData keyword4 = new TemplateData(); keyword4.setColor("#000000"); keyword4.setValue("不夠"); m.put("keyword4", keyword4); TemplateData remark = new TemplateData(); remark.setColor("#000000"); remark.setValue("再加一萬年"); m.put("remark", remark); //about data endtm.setData(m);String jsonString = JSONObject.fromObject(tm).toString();System.out.println("jsonString:"+jsonString);return jsonString;}/*** 發送模板消息* appId 公眾賬號的唯一標識* appSecret 公眾賬號的密鑰* openId 用戶標識*/public void postTemplateMsg(String appId, String appSecret, String openId){Token token = CommonUtil.getToken(appId, appSecret);String access_token = token.getAccessToken();String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;System.out.println("requestUrl:"+requestUrl);String jsonString = sendTemplateMessage(openId);JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "POST", jsonString);System.out.println("jsonObject="+jsonObject); if (null != jsonObject) { int errorCode = jsonObject.getInt("errcode"); if (0 == errorCode) { System.out.println("模板消息發送成功!"); } else { String errorMsg = jsonObject.getString("errmsg"); System.out.println("模板消息發送失敗,錯誤碼是:"+errorCode+",錯誤信息是:"+errorMsg); } } }/** * 類名: CommonUtil </br> * 描述: 通用工具類 </br> * 發布版本:V1.0 </br>*/ public class CommonUtil {// 憑證獲取(GET)public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";/*** 發送https請求* * @param requestUrl 請求地址* @param requestMethod 請求方式(GET、POST)* @param outputStr 提交的數據* @return JSONObject(通過JSONObject.get(key)的方式獲取json對象的屬性值)*/public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {JSONObject jsonObject = null;try {// 創建SSLContext對象,并使用我們指定的信任管理器初始化TrustManager[] tm = { new MyX509TrustManager() };SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");sslContext.init(null, tm, new java.security.SecureRandom());// 從上述SSLContext對象中得到SSLSocketFactory對象SSLSocketFactory ssf = sslContext.getSocketFactory();URL url = new URL(requestUrl);HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();conn.setSSLSocketFactory(ssf);conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);// 設置請求方式(GET/POST)conn.setRequestMethod(requestMethod);// 當outputStr不為null時向輸出流寫數據if (null != outputStr) {OutputStream outputStream = conn.getOutputStream();// 注意編碼格式outputStream.write(outputStr.getBytes("UTF-8"));outputStream.close();}// 從輸入流讀取返回內容InputStream inputStream = conn.getInputStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String str = null;StringBuffer buffer = new StringBuffer();while ((str = bufferedReader.readLine()) != null) {buffer.append(str);}// 釋放資源bufferedReader.close();inputStreamReader.close();inputStream.close();inputStream = null;conn.disconnect();jsonObject = JSONObject.fromObject(buffer.toString());} catch (ConnectException ce) {System.out.println("連接超時:"+ ce);} catch (Exception e) {System.out.println("https請求異常:"+ e);}return jsonObject;}/*** 獲取接口訪問憑證* * @param appid 憑證* @param appsecret 密鑰* @return*/public static Token getToken(String appid, String appsecret) {Token token = null;String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);System.out.println("requestUrl:"+requestUrl);// 發起GET請求獲取憑證JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);if (null != jsonObject) {try {token = new Token();token.setAccessToken(jsonObject.getString("access_token"));token.setExpiresIn(jsonObject.getInt("expires_in"));} catch (JSONException e) {token = null;// 獲取token失敗System.out.println("獲取token失敗 errcode:"+jsonObject.getInt("errcode")+"errmsg:"+jsonObject.getString("errmsg"));}}return token;}/*** URL編碼(utf-8)* @param source* @return*/public static String urlEncodeUTF8(String source) {String result = source;try {result = java.net.URLEncoder.encode(source, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}public static void main(String args[]) {//https://1d488f5d.ngrok.io/WeiXinProject/String source="https://565b4dad.ngrok.io/WeChatPublicNumber/oauthServlet";System.out.println(CommonUtil.urlEncodeUTF8(source));} }
over!
轉載于:https://www.cnblogs.com/YLQBL/p/8961224.html
總結
以上是生活随笔為你收集整理的微信公众号消息推送-模板消息发送的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 正则介绍_grep上 grep中 g
- 下一篇: jboss 反序列化 getshel