微信公众号消息推送
微信公眾號消息推送
- 公眾號相關配置
- 接口配置相關代碼
- 獲取access_token
- 消息模板推送
- 消息推送代碼
- 網頁授權
- 創建授權鏈接
- 最后總結
公眾號相關配置
這里暫時以測試界面展示,實際界面和測試界面出入不大。
登錄公眾號調試網址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
| appID | 應用ID |
| appsecret | 應用秘鑰 |
| URL | 應用的回調地址接口 |
| Token | 用來雙向加密 |
| JS域名 | 對哪些域名開放JS接口 |
接口配置相關代碼
/*** 接口信息配置* * @param request* @param response*/@RequestMapping("/interfaceConfiguration")public void interfaceConfiguration(HttpServletRequest request, HttpServletResponse response) {// 微信加密簽名String signature = request.getParameter("signature");// 時間戳String timestamp = request.getParameter("timestamp");// 隨機數String nonce = request.getParameter("nonce");// 隨機字符串String echostr = request.getParameter("echostr");// 安全認證String security = "";PrintWriter out = null;try {out = response.getWriter();// 注意一下,這里的token就是我們上面填的token要保持一直,再進行SHA1加密security = SHA1.getSHA1(token, timestamp, nonce,"");// 判斷是否是同一個請求if (! StrManager.isEmpty(security) && security.equals(signature)) {// 判斷是否接口配置事件if (! StrManager.isEmpty(echostr)) {logger.info("配置成功");out.print(echostr);} else {// 下面就自由發揮 根據不同的事件執行不同的邏輯// 事件參數都包含在Request請求中,遍歷參數即可//...... } }} catch (Exception e) {e.printStackTrace();logger.error("程序出錯", e);} finally {out.close();out = null;}}/*** SHA1加密* * @param token* @param timestamp* @param nonce* @param encrypt* @return*/public String getSHA1(String token, String timestamp, String nonce, String encrypt) {try {String[] array = new String[] { token, timestamp, nonce, encrypt };StringBuffer sb = new StringBuffer();// 字符串排序Arrays.sort(array);for (int i = 0; i < 4; i++) {sb.append(array[i]);}String str = sb.toString();// SHA1簽名生成MessageDigest md = MessageDigest.getInstance("SHA-1");md.update(str.getBytes());byte[] digest = md.digest();StringBuffer hexstr = new StringBuffer();String shaHex = "";for (int i = 0; i < digest.length; i++) {shaHex = Integer.toHexString(digest[i] & 0xFF);if (shaHex.length() < 2) {hexstr.append(0);}hexstr.append(shaHex);}return hexstr.toString();} catch (Exception e) {e.printStackTrace();return null;}}獲取access_token
科普一下access_token吧,它是我們調用公眾號接口的憑據,有效期只有兩個小時, 需要用戶定時去刷新。廢物不多了說直接上代碼。
/*** 更新AccessToken*/public void updateAccessToken() throws Exception { // 寫自己AppidString appId = "xxxxxxx";// 寫自己AppsecretString secret = "xxxxxxx";String endpoint = "https://api.weixin.qq.com/cgi-bin/token";Map<String, String> heads = new HashMap<String, String>(5);Map<String, String> params = new HashMap<>() ;params.put("grant_type", "client_credential");params.put("appid", appId);params.put("secret", secret);try {// 這是封裝的httpGet請求,請求方法需要你們自己寫。Map<String, String> ret = HttpMethodUtil.httpGetMethod(endpoint, heads, params);String retJson = ret.get(HttpMethodUtil.retKey);if (StrManager.isEmpty(retJson)) {logger.error("Appid: ".concat(appId.concat(" 更新ACCESSTOKENJOB失敗 返回數據為空")));return;}// 轉成JSON字符串JSONObject o = JSONObject.parseObject(retJson);// 判斷報錯字段if (o.containsKey("errcode") && o.getInteger("errcode") != 0) {throw new Exception(o.getString("errmsg"));}// AccessTokenString accessToken = o.getString("access_token");// 后面就自己寫啦,更新保存的操作//// ......} catch (Exception e) {e.printStackTrace();logger.error("Appid: ".concat(appId.concat(" 更新ACCESSTOKENJOB失敗 ")), e);} }消息模板推送
先去我們公眾號后臺配置推送模板,如下圖
| first.DATA | 模板標題 |
| key1.DATA | 目標內容 |
這里的key1.DATA只是這款模板的變量名,其他模板可能有key2.DATA , key3.DATA …
消息推送代碼
/*** 發送模板消息* * @param wxTemplate* @param accessToken* @throws Exception*/public void sendTemplate(WxTemplate wxTemplate, String accessToken) throws Exception {String endpoint = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;String wxTemplateJson = JSONObject.toJSONString(wxTemplate);Map<String, String> heads = new HashMap<String, String>(5);heads.put("Content-Type", "application/json");String openId = wxTemplate.getTouser();try {// 這是封裝的httpPost請求,請求方法需要你們自己寫。Map<String, String> ret = HttpMethodUtil.httpPostMethod(endpoint, heads, null, wxTemplateJson, "application/json");String retJson = ret.get(HttpMethodUtil.retKey);if (StrManager.isEmpty(retJson)) {throw new Exception("OpenId: ".concat(openId.concat(" 發送模板消息失敗 返回數據為空")));}System.out.println(retJson);JSONObject result = JSONObject.parseObject(retJson);// 判斷報錯字段if (result.containsKey("errcode") && result.getInteger("errcode") != 0) {throw new Exception(result.getString("errmsg"));}} catch (Exception e) {e.printStackTrace();throw new Exception(e.getMessage());}}WxTemplate的實體類
public class WxTemplate {/*** 模板消息id*/private String template_id;/*** 用戶openId*/private String touser;/*** URL置空,則在發送后,點擊模板消息會進入一個空白頁面(ios),或無法點擊(android)*/private String url;/*** 標題顏色*/private String topcolor;/*** 詳細內容*/private Map<String,TemplateData> data;public String getTemplate_id() {return template_id;}public void setTemplate_id(String template_id) {this.template_id = template_id;}public String getTouser() {return touser;}public void setTouser(String touser) {this.touser = touser;}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 Map<String, TemplateData> getData() {return data;}public void setData(Map<String, TemplateData> data) {this.data = data;} }網頁授權
在后臺配置授權回調地址 如下圖:
注意:沙盒是可以支持ip的,正式環境就必須用域名了。(正式環境提示支持域名帶項目名的,其實是不支持帶項目名的 避免踩坑)
創建授權鏈接
| appid | 是 | 應用ID |
| redirect_uri | 是 | 授權后重定向的回調地址,請使用 urlEncode 對鏈接進行處理 |
| response_type | 是 | 返回類型,請填寫code |
| scope | 是 | 應用授權作用域,snsapi_base (不彈出授權頁面,直接跳轉,只能獲取用戶openid),snsapi_userinfo (彈出授權頁面,可通過openid拿到昵稱、性別、所在地。并且, 即使在未關注的情況下,只要用戶授權,也能獲取其信息 ) |
| state | 否 | 重定向后會帶上state參數,不支持特殊字符,最多128字節 |
| #wechat_redirect | 是 | 無論直接打開還是做頁面302重定向時候,必須帶此參數 |
列子:
scope為snsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
scope為snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
用戶同意授權后
如果用戶同意授權,頁面將跳轉至 redirect_uri/?code=CODE&state=STATE。
最后總結
以上就是公眾號配置消息推送的相關教程啦,如果想深入了解或者覺得上面的信息不夠詳細。可以在這里找找看https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
總結
- 上一篇: DELPHI源码防QQ截屏区域截图全屏截
- 下一篇: vue兼容IE8以上解决方案