java開發微信模板消息推送


發布時間:2018-12-12
 
技術:springboot+maven
 

概述

該demo主要涉及微信模板消息推送功能,

詳細

概述

微信公眾平台開始支持前端網頁,大家可能看到很多網頁上都有分享到朋友圈,關注微信等按鈕,點擊它們都會彈出一個窗口讓你分享和關注,這個是怎么實現的呢?今天就給大家講解下如何在微信公眾平台前端網頁上添加分享到朋友圈,關注微信號等按鈕。

一、前言

 

(1)適合人群

1,JAVA服務端開發人員

2,初級人員開發人員

3,了解spring springboot + maven.

4,了解微信開發

(2)你需要准備什么?

 

1,積極主動學習

2,微信公眾號開發基本流程

3,java后端幾大框架掌握如(spring springboot maven )

二、前期准備工作

軟件環境:eclipse

官方下載:https://www.eclipse.org/downloads/

1 ,基本需求

微信模板消息推送訂單購買成功推送

三、項目結構

image.png

四、使用規則

  • 所有服務號都可以在功能->添加功能插件處看到申請模板消息功能的入口

  • 需要選擇公眾賬號服務所處的2個行業,每月可更改1次所選行業

  • 在所選擇行業的模板庫中選用已有的模板進行調用

  • 每個賬號可以同時使用25個模板

  • 當前每個賬號的模板消息的日調用上限為10萬次,單個模板沒有特殊限制,以公眾號MP后台開發者中心頁面中標明的數字為准

五、接口文檔規范

  • 模板消息調用時主要需要模板ID和模板中各參數的賦值內容

  • 模板中參數內容必須以".DATA"結尾,否則視為保留字

  • 模板保留符號"{{ }}"

     

  • 測試公眾號可以隨意定義,正式的必須用模板庫中的

以下是我使用的模板消息示例

package cn.demo.Template;

/**
 * 模板詳細信息 
 */
public class Data_first {

    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;
	}
}
	
	   /**
	    * 獲取acctoken
	    * @return
	    */
	   private String getAccessToken() {
	        if (access_token != null && (access_token_updateTime + 5400000) > new Date().getTime())
	            return access_token;
	        AccessTokenResult accessTokenResult = restTemplate.getForObject(String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, SECRET), AccessTokenResult.class);
	        if (accessTokenResult.getErrcode() == null || accessTokenResult.getErrcode().equals("0")) {
	            access_token_updateTime = new Date().getTime();
	            access_token = accessTokenResult.getAccess_token();
	        } else 
	        	System.out.println("error:" + accessTokenResult);
	        return accessTokenResult.getAccess_token();
	    
}
/**
 * 微信請求 - 信任管理器
 */
public class MyX509TrustManager implements X509TrustManager {
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}
    /**
     * 發送https請求
     * @param requestUrl 請求地址
     * @param requestMethod 請求方式(GET、POST)
     * @param outputStr 提交的數據
     * @return JSONObject(通過JSONObject.get(key)的方式獲取json對象的屬性值)
     */

public class WeixinUtil {

	 public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
	  {
	    JSONObject jsonObject = null;
	    StringBuffer buffer = new StringBuffer();
	    try
	    {
	      TrustManager[] tm = { new MyX509TrustManager() };
	      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
	      sslContext.init(null, tm, new SecureRandom());

	      SSLSocketFactory ssf = sslContext.getSocketFactory();

	      URL url = new URL(requestUrl);
	      HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
	      httpUrlConn.setSSLSocketFactory(ssf);

	      httpUrlConn.setDoOutput(true);
	      httpUrlConn.setDoInput(true);
	      httpUrlConn.setUseCaches(false);

	      httpUrlConn.setRequestMethod(requestMethod);

	      if ("GET".equalsIgnoreCase(requestMethod)) {
	        httpUrlConn.connect();
	      }

	      if (outputStr != null) {
	        OutputStream outputStream = httpUrlConn.getOutputStream();

	        outputStream.write(outputStr.getBytes("UTF-8"));
	        outputStream.close();
	      }

	      InputStream inputStream = httpUrlConn.getInputStream();
	      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
	      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

	      String str = null;
	      while ((str = bufferedReader.readLine()) != null) {
	        buffer.append(str);
	      }
	      bufferedReader.close();
	      inputStreamReader.close();

	      inputStream.close();
	      inputStream = null;
	      httpUrlConn.disconnect();
	      jsonObject = JSONObject.fromObject(buffer.toString());
	    } catch (ConnectException ce) {
	     // logger.error("Weixin server connection timed out.");
	    } catch (Exception e) {
	     // logger.error("https request error:{}", e);
	    }
	    return jsonObject;
	  }

}

下面請求微信發送模板消息

	/**
	 *  * 發送模板消息  
	 * appId 公眾賬號的唯一標識 
     * appSecret 公眾賬號的密鑰  
	 * openId 用戶標識     
	 */
	public void send_template_message(String appId, String openId) {
		String access_token = getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
		NewOrdersTemplate temp = new NewOrdersTemplate();
		Data data = new Data();
		Data_first first = new Data_first();
		Data_Day Day = new Data_Day();
		Data_orderId orderId = new Data_orderId();
		Data_orderType orderType = new Data_orderType();
		Data_customerName customerName = new Data_customerName();
		Data_customerPhone customerPhone = new Data_customerPhone();
		Data_remark remark = new Data_remark();

		first.setValue("收到一個新的訂單");
		first.setColor("#173177");
		Day.setValue("14時56分");
		Day.setColor("#173177");
		orderId.setValue("1002");
		orderId.setColor("#173177");
		orderType.setValue("訂位");
		orderType.setColor("#173177");
		customerName.setValue("陳丑丑");
		customerName.setColor("#173177");
		customerPhone.setValue("13222222222");
		customerPhone.setColor("#173177");
		remark.setValue("請及時處理您的訂單");
		remark.setColor("#173177");

		data.setFirst(first);
		data.setDay(Day);
		data.setOrderId(orderId);
		data.setOrderType(orderType);
		data.setCustomerName(customerName);
		data.setCustomerPhone(customerPhone);
		data.setRemark(remark);
		temp.setTouser(openId);
		temp.setTemplate_id("C0BHxo_YLQ9TV2XytzqucHI7dNJytq0aAxYkBkqZTiw");
		temp.setUrl("http://weixin.qq.com/download");
		temp.setTopcolor("#173177");
		temp.setData(data);

		String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
		JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonString);
		System.out.println(jsonObject);

		int result = 0;

		// logger.info("模板消息發送結果:"+result};

	}

 

下一步請求conterller因為我參數寫死在conterller里面

	@RequestMapping("/test")
	@ResponseBody
	public String testDemo() {
		String openId = "oJilVv4k-DXciUhIsC2wSXJs2J";
		String appId = "wx1ff244a71563c";
		send_template_message(appId, openId);
		return appId;

	}

六、運行效果

訪問這地址 http://localhost:8080/app/tetst 測試結果如圖

258615996887007042.jpg

 

注:本文著作權歸作者,由demo大師發表,拒絕轉載,轉載需要作者授權


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM