微信公衆平臺之發送模板消息

一.本篇要點:

1.首先這篇文章主要分爲倆部分,先是介紹服務號發送消息模板,後面接着是測試號發送消息模板!
 

二.整體思路:

1、先創建菜單,引導用戶進入授權頁面同意授權,獲取code 以及openId

2、通過code換取網頁授權access_token(與基礎支持中的access_token不同)

3、如果需要,開發者可以刷新網頁授權access_token,避免過期

4、通過網頁授權access_token和openid獲取用戶基本信息(支持UnionID機制)

三.代碼的實現

  -----------------------------------------服務號步驟--------------------------------------

1.創建自定義菜單,可以通過代碼的方式,也可以直接在服務號後臺中創建自定義菜單

頁面地址:是後臺用來處理 用戶點擊這個菜單獲取用的的code 以及openId

 

 

2. 接下來後臺用來處理數據的接口

  @RequestMapping(value = "/getNews")
    public String getNews(){
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        String REDIRECT_URI = "http://hgbcb.io/getOpenId";//你的回調頁
        url = url.replace("APPID",WeiXinParamesUtil.APPID);
        url = url.replace("STATE", "test");
        url = url.replace("REDIRECT_URI", REDIRECT_URI);
        return "redirect:"+url;
    }

    public static String OPENID;
    @RequestMapping(value = "/getOpenId")
    public String callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse response) throws Exception {
        String code = req.getParameter("code");
        OAuthInfo oat = GetOpenid.getOAuthOpenId(WeiXinParamesUtil.APPID, WeiXinParamesUtil.SECRET, code);
        String openId=oat.getOpenId();
        OPENID=openId;
        //在這裏查詢出客戶表中的openid是否存在
        BosCustomerModel customer=weiService.findBosCustomerModelByOpenId(openId);
        if(customer!=null) {
            return "sucess";
        }
        return "findName";

    }

3.在getOpenId這個接口得到了code,然後getOAuthOpenId這個方法去獲取用戶的openiD,然後就可以拿到點擊這個菜單的人的openid。

 public static OAuthInfo getOAuthOpenId(String appid, String secret, String code ) {
        OAuthInfo oAuthInfo = null;
        String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        String requestUrl = o_auth_openid_url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);

        JSONObject jsonObject = WeiXinUtil.httpRequest(requestUrl, "GET", null);

        //oAuthInfo是作者自己把那幾個屬性參數寫在一個類裏面了。
        // 如果請求成功
        if (null != jsonObject) {
            try {
                oAuthInfo = new OAuthInfo();
                oAuthInfo.setAccessToken(jsonObject.getString("access_token"));
                oAuthInfo.setExpiresIn(jsonObject.getInt("expires_in"));
                oAuthInfo.setRefreshToken(jsonObject.getString("refresh_token"));
                oAuthInfo.setOpenId(jsonObject.getString("openid"));
                oAuthInfo.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                oAuthInfo = null;
                // 獲取token失敗
                log.error("網頁授權獲取openId失敗 errcode:{} errmsg:{}", jsonObject
                        .getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return oAuthInfo;
    }

4.接下來是考慮模板的問題:發送模板最重要的就是拿到模板id

 服務號的模板是要申請的,前提是要選擇自己的行業,它會提供一些關於你選擇的那個行業的一些模板。(有審覈時間)

模板消息:點擊微信公衆平臺-->添加功能插件-->模板消息-->申請然後選擇適合的模板

5.發送模板的方法:(當中涉及的一些方法可以在測試號看到)

   //接下來給這個客戶發送模板消息
                //先給模板中設置參數
                Template tem=new Template();
                tem.setTemplateId(WeiXinParamesUtil.TEMPLATEID);  //模板id
                tem.setTopColor("#00DD00");
                tem.setToUser(customer.getOpenId());//得到用戶的openid
                tem.setUrl("");
                List<TemplateParam> paras = new ArrayList<TemplateParam>();
                paras.add(new TemplateParam("first", "我們將給您推送一些關於您項目進度的消息:", "#FF3333"));
                paras.add(new TemplateParam("keyword1", newModel.getwName(), "#0044BB"));//項目名稱
                paras.add(new TemplateParam("keyword2", message, "#0044BB"));//項目進度
                //paras.add(new TemplateParam("keyword3", newModel.getsTime(), "#0044BB"));//開始時間
                paras.add(new TemplateParam("keyword3", newModel.getLeader(), "#0044BB"));//項目負責人
                paras.add(new TemplateParam("remark", "感謝你對我們BIM項目的支持!!!!", "#AAAAAA"));
                tem.setTemplateParamList(paras);
                //將Accesstoken拿到
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
               /* String APPID = WeiXinParamesUtil.APPID;
                String SECRET = WeiXinParamesUtil.SECRET;*/
                url = url.replace("APPID", WeiXinParamesUtil.APPID);
                url = url.replace("APPSECRET",WeiXinParamesUtil. SECRET);
                String content = HttpUtil.httpUrlConnect(url, null, "GET");
                Map<String, Object> map = HttpUtil.getAccessTokenByJsonStr(content);
                String accessToken = (String) map.get("access_token");
                boolean result = SendMessage.sendTemplateMsg(accessToken, tem);

6.效果圖如下:

 

 

--------------------------------------------測試號步驟------------------------------------

1.在測試號網頁上拿到關注公衆號的人員信息,將其保存在數據庫中,注意:每個人的openid是唯一的

2.事先在公衆號中定義模板,那麼在後臺你就可以拿到模板id 將數據已模板的方式發送給客戶

3.  ProjectController

// 4.根據id修改數據
	@RequestMapping(value = "/updateProjectById", method = RequestMethod.POST)
	public String updateById(Model model, 
			
			) throws Exception {
		
	
			
				//根據bid去查詢出bos_customer中的數據
				Bos_customer customer=projectService.findCustomerByBid(bid);
				System.out.println("Bos_customer:"+customer.getCid()+"-------"+customer.getCname()+"-------"+customer.getOpenId());
				//接下來給這個客戶發送模板消息
				//先給模板中設置參數
				Template tem=new Template();  
				tem.setTemplateId("4JDGT8xdV-PQYbtiwJaeb352WoeUDHRtb29gn62olJk");  //模板id
				tem.setTopColor("#00DD00");  
				tem.setToUser(customer.getOpenId());//得到用戶的openid
				tem.setUrl("");  
				List<TemplateParam> paras=new ArrayList<TemplateParam>();  
				paras.add(new TemplateParam("first","我們將給您推送一些關於您項目進度的消息:","#FF3333"));  
				paras.add(new TemplateParam("keyword1",pro.getwName(),"#0044BB"));//項目名稱
				paras.add(new TemplateParam("keyword2",message,"#0044BB"));//項目進度
				paras.add(new TemplateParam("keyword3",pro.getsTime(),"#0044BB"));//開始時間
				paras.add(new TemplateParam("keyword4",pro.getLeader(),"#0044BB"));//項目負責人
				paras.add(new TemplateParam("remark","感謝你對我們BIM項目的支持!!!!","#AAAAAA")); 
				tem.setTemplateParamList(paras);  
				 //將Accesstoken拿到  
				String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
				String APPID = ConfigUtil.APPID;
				String SECRET = ConfigUtil.SECRET;
				url = url.replace("APPID", APPID);
				url = url.replace("APPSECRET", SECRET);
				String content = HttpUtil.httpUrlConnect(url, null, "GET");
				Map<String, Object> map=HttpUtil.getAccessTokenByJsonStr(content);
				String accessToken=(String) map.get("access_token");
				boolean result=SendMessage.sendTemplateMsg(accessToken,tem);  
				if(result==true){
					System.out.println("發送成功");
					
				}	
				
			}
		}
		return "redirect:showAll";
	}

4. Template類

package com.bos.pojo;

import java.util.List;

public class Template {
	//消息接收方
	private String toUser;
	//模板id
	private String templateId;
	//模板消息詳情鏈接
	private String url;
	//消息頂部的顏色
	private String topColor;
	//參數列表
	private List<TemplateParam> templateParamList;
	
	public Template() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Template(String toUser, String templateId, String url,
			String topColor, List<TemplateParam> templateParamList) {
		super();
		this.toUser = toUser;
		this.templateId = templateId;
		this.url = url;
		this.topColor = topColor;
		this.templateParamList = templateParamList;
	}
	public String getToUser() {
		return toUser;
	}
	public void setToUser(String toUser) {
		this.toUser = toUser;
	}
	public String getTemplateId() {
		return templateId;
	}
	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getTopColor() {
		return topColor;
	}
	public void setTopColor(String topColor) {
		this.topColor = topColor;
	}
	public List<TemplateParam> getTemplateParamList() {
		return templateParamList;
	}
	public void setTemplateParamList(List<TemplateParam> templateParamList) {
		this.templateParamList = templateParamList;
	}
	
	public String toJSON() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("{");  
        buffer.append(String.format("\"touser\":\"%s\"", this.toUser)).append(",");  
        buffer.append(String.format("\"template_id\":\"%s\"", this.templateId)).append(",");  
        buffer.append(String.format("\"url\":\"%s\"", this.url)).append(",");  
        buffer.append(String.format("\"topcolor\":\"%s\"", this.topColor)).append(",");  
        buffer.append("\"data\":{");  
        TemplateParam param = null;  
        for (int i = 0; i < this.templateParamList.size(); i++) {  
             param = templateParamList.get(i);  
            // 判斷是否追加逗號  
            if (i < this.templateParamList.size() - 1){  
                  
                buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"},", param.getName(), param.getValue(), param.getColor()));  
            }else{  
                buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"}", param.getName(), param.getValue(), param.getColor()));  
            }  
          
        }  
        buffer.append("}");  
        buffer.append("}");  
        return buffer.toString();  
        }  
	
	
	
	
	
	
	
}

 

package com.bos.pojo;

public class TemplateParam {
		//模板消息由於模板選取不同,那麼就要封裝倆個實體類
	 // 參數名稱  
    private String name;  
    // 參數值  
    private String value;  
    // 顏色  
    private String color;  
      
    public TemplateParam() {
		super();
		// TODO Auto-generated constructor stub
	}
	public TemplateParam(String name,String value,String color){  
        this.name=name;  
        this.value=value;  
        this.color=color;  
    }  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    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;  
    }  
}

5.一些工具類

(1)HttpUtil

package com.wei.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;


public class HttpUtil {
	public static String httpUrlConnect(String httpUrl, String params,
			String method) throws Exception {

		URL url = new URL(httpUrl);
		HttpURLConnection urlConnection = (HttpURLConnection) url
				.openConnection();
		urlConnection.setRequestProperty("accept", "*/*");
		urlConnection.setRequestProperty("connection", "Keep-Alive");
		urlConnection.setRequestProperty("user-agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		urlConnection.setDoOutput(true);
		urlConnection.setDoInput(true);
		urlConnection.setRequestMethod(method);
		urlConnection.connect();
		PrintWriter out = null;
		BufferedReader in = null;
		if (null != params && !"".equals(params)) {
			out = new PrintWriter(new OutputStreamWriter(
					urlConnection.getOutputStream(), "utf-8"));
			out.print(params);
			out.flush();
		}
		in = new BufferedReader(new InputStreamReader(
				urlConnection.getInputStream(), "utf-8"));
		String line;
		String result = "";
		while ((line = in.readLine()) != null) {
			result += line;
		}
		return result;

	}
	/**
	* 根據字符串json數據解析access_token
	* @param jsonStr
	* @return map
	*/
	public static Map<String,Object> getAccessTokenByJsonStr(String jsonStr){
	Map<String,Object> map = new HashMap<String, Object>();
	JSONObject jsonObj = new JSONObject(jsonStr); 
	if(jsonObj.has("access_token")){
	   map.put("access_token", jsonObj.get("access_token")); 
	}
	 if(jsonObj.has("expires_in")){
	   map.put("expires_in", jsonObj.get("expires_in")); 
	}
	   return map;
	}
	
	
    
}

(2)發送模板消息的類

package com.wei.util;

import net.sf.json.JSONObject;

import com.bos.pojo.Template;

/*
 * 
 * 這是發送模板消息的類
 * 5.12
 * 
 * */
public class SendMessage {
	public static boolean sendTemplateMsg(String token,Template template){  
        
        boolean flag=false;  
          
        String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";  
        requestUrl=requestUrl.replace("ACCESS_TOKEN", token);  
      
        JSONObject jsonResult=CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());  
        if(jsonResult!=null){  
            int errorCode=jsonResult.getInt("errcode");  
            String errorMessage=jsonResult.getString("errmsg");  
            if(errorCode==0){  
                flag=true;  
            }else{  
                System.out.println("模板消息發送失敗:"+errorCode+","+errorMessage);  
                flag=false;  
            }  
        }  
        return flag;  
          
          
          
}  
}

最後給大家看一下簡單的微信公衆號的效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章