java后台关联微信公众号开发
生活随笔
收集整理的這篇文章主要介紹了
java后台关联微信公众号开发
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.需要配置到微信公眾號的法控制類
注意:get是用于微信公眾號的校驗噠
post是用來接收公眾號發(fā)送的請求進行處理
2.MessageUtil
package com.youruan.logistics.util;import com.alibaba.fastjson.JSONObject; import com.youruan.logistics.config.excetion.ServiceException; import com.youruan.logistics.config.global.Constant; import com.youruan.logistics.config.global.Mark; import org.dom4j.Document; import org.dom4j.Element;import java.io.IOException; import java.io.PrintWriter; import java.util.Map;public class MessageUtil {public static void replyMessage(String message, PrintWriter out) throws IOException {Document document = XMLUtil.readString2XML(message);Element root = document.getRootElement();String MsgType = XMLUtil.readNode(root, "MsgType");String ToUserName = XMLUtil.readNode(root, "ToUserName"); //開發(fā)者微信號String FromUserName = XMLUtil.readNode(root, "FromUserName");String CreateTime = XMLUtil.readNode(root, "CreateTime");String Event = XMLUtil.readNode(root, "Event");System.out.println("MsgType="+MsgType+"\n---ToUserName="+ToUserName+"\n---FromUserName="+FromUserName+"\n---CreateTime="+CreateTime+"\n---Event="+Event);if (MsgType.equals(Constant.REQ_MESSAGE_TYPE_EVENT)) {/*** 用戶關(guān)注了微信號啦*/if(Event.equals(Constant.EVENT_TYPE_SUBSCRIBE)){/*** 獲取用戶信息保存到數(shù)據(jù)庫*/System.out.println("用戶關(guān)注了微信號啦");Map<String, Object> map = WxUserinfoByOpenId(FromUserName);System.out.println(map.toString());System.out.println("unionid=="+map.get("unionid"));}/*** 用戶取消關(guān)注啦*/else if(Event.equals(Constant.EVENT_TYPE_UNSUBSCRIBE)){System.out.println("用戶取消關(guān)注啦");Map<String, Object> map = WxUserinfoByOpenId(FromUserName);System.out.println(map.toString());System.out.println("unionid=="+map.get("unionid"));}out.close();}}/*** 根據(jù)openId獲取微信端的用戶信息* @param openId* @return* @throws IOException*/public static Map<String, Object> WxUserinfoByOpenId(String openId) throws IOException {System.out.println("===========WxUserinfoByOpenId");HttpUtil httpUtil = new HttpUtil();String url = "https://api.weixin.qq.com/cgi-bin/user/info";String accessToken = (String)getAccessToken().get("access_token");String result = httpUtil.header("X-Requested-With", "XMLHttpRequest").data("openid", openId).data("access_token",accessToken).data("lang", "zh_CN").url(url).get();System.out.println("WxUserinfoByOpenId==="+result);Map<String, Object> map = JSONObject.parseObject(result, Map.class);return map;}/*** 獲取公眾號的access_token* @return* @throws IOException*/public static Map<String, Object> getAccessToken() throws IOException {System.out.println("===========getAccessToken");HttpUtil httpUtil = new HttpUtil();String url = "https://api.weixin.qq.com/cgi-bin/token";String result = httpUtil.header("X-Requested-With", "XMLHttpRequest").data("appid", Mark.GZH_APPID).data("secret", Mark.GZH_APPSECRET).data("grant_type", Mark.TOKEN_GRANT_TYPE).url(url).get();System.out.println(result);Map<String, Object> map = JSONObject.parseObject(result, Map.class);if (!map.containsKey("access_token")) {throw new ServiceException("錯誤信息:" + map.get("errmsg"));}return map;} }3.SendWxMessage
package com.youruan.logistics.util;import com.alibaba.fastjson.JSONObject; import com.youruan.logistics.entity.WxTemplate;/*** 發(fā)送消息模板的類*/ public class SendWxMessage {public static boolean sendTemplateMsg(String token, WxTemplate 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);String jsonResultT=CommonUtil.httpRequest(requestUrl, "POST", template.toJSON());JSONObject jsonResult = JSONObject.parseObject(jsonResultT);if(jsonResult!=null){int errorCode=jsonResult.getInteger("errcode");String errorMessage=jsonResult.getString("errmsg");if(errorCode==0){flag=true;}else{System.out.println("模板消息發(fā)送失敗:"+errorCode+","+errorMessage);flag=false;}}return flag;} }4.SignUtil(公眾號校驗)
package com.youruan.logistics.util;import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays;public class SignUtil {private static String token = "tongfenfen";/*** 校驗簽名*/public static boolean checkSignature(String signature, String timestamp, String nonce) {System.out.println("signature:" + signature + "timestamp:" + timestamp + "nonc:" + nonce);String[] arr = new String[] { token, timestamp, nonce };// 將token、timestamp、nonce三個參數(shù)進行字典序排序Arrays.sort(arr);StringBuilder content = new StringBuilder();for (int i = 0; i < arr.length; i++) {content.append(arr[i]);}MessageDigest md = null;String tmpStr = null;try {md = MessageDigest.getInstance("SHA-1");// 將三個參數(shù)字符串拼接成一個字符串進行sha1加密byte[] digest = md.digest(content.toString().getBytes());tmpStr = byteToStr(digest);} catch (NoSuchAlgorithmException e) {e.printStackTrace();}content = null;// 將sha1加密后的字符串可與signature對比,標識該請求來源于微信System.out.println(tmpStr.equals(signature.toUpperCase()));return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;}/*** 將字節(jié)數(shù)組轉(zhuǎn)換為十六進制字符串** @param byteArray* @return*/private static String byteToStr(byte[] byteArray) {String strDigest = "";for (int i = 0; i < byteArray.length; i++) {strDigest += byteToHexStr(byteArray[i]);}return strDigest;}/*** 將字節(jié)轉(zhuǎn)換為十六進制字符串** @param mByte* @return*/private static String byteToHexStr(byte mByte) {char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };char[] tempArr = new char[2];tempArr[0] = Digit[(mByte >>> 4) & 0X0F];tempArr[1] = Digit[mByte & 0X0F];String s = new String(tempArr);return s;} }5.XMLUtil(解析xml數(shù)據(jù))
package com.youruan.logistics.util;import java.util.List;import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element;public class XMLUtil {public static String content="";public static Document readString2XML(String str){Document document=null;try {document=DocumentHelper.parseText(str);} catch (DocumentException e) {e.printStackTrace();}return document;};/*** 讀取根節(jié)點下每一個節(jié)點信息* @param node* @return*/public static String readNodes(Element node){content+=node.getName()+":"+node.getTextTrim()+"\n";//遞歸遍歷當前節(jié)點所有的子節(jié)點List<Element> listElement=node.elements();//所有一級子節(jié)點的listfor(Element e:listElement){//遍歷所有一級子節(jié)點readNodes(e);//遞歸}return content;}/*** 讀取單個節(jié)點信息* @param node* @param name* @return*/public static String readNode(Element node,String name){Element e=node.element(name);String nodeString=e.getTextTrim();return nodeString;} }6.HttpUtilOfWx
package com.youruan.logistics.util;import com.alibaba.fastjson.JSONObject;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.Map;public class HttpUtilOfWx {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;}/*** 根據(jù)字符串json數(shù)據(jù)解析access_token* @param jsonStr* @return map*/public static Map<String,Object> getAccessTokenByJsonStr(String jsonStr){/* 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"));}*/Map<String, Object> map = JSONObject.parseObject(jsonStr, Map.class);/*if (!map.containsKey("openid")) {throw new ServiceException("錯誤信息:" + map.get("errmsg"));}*/return map;}}7.實體類TemplateParam
package com.youruan.logistics.entity;public class TemplateParam {//模板消息由于模板選取不同,那么就要封裝倆個實體類// 參數(shù)名稱private String name;// 參數(shù)值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;} }8.實體類 WxTemplate
package com.youruan.logistics.entity;import java.util.List; /*** 模板基類**/ public class WxTemplate {//消息接收方private String toUser;//模板idprivate String templateId;//模板消息詳情鏈接private String url;//消息頂部的顏色private String topColor;//參數(shù)列表private List<TemplateParam> templateParamList;public WxTemplate() {super();// TODO Auto-generated constructor stub}public WxTemplate(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();} }9.Constant
/*** 微信觸發(fā)的事件*/public static final Object REQ_MESSAGE_TYPE_EVENT = "event";public static final Object EVENT_TYPE_SUBSCRIBE = "subscribe"; //關(guān)注public static final Object EVENT_TYPE_UNSUBSCRIBE = "unsubscribe"; //取消關(guān)注總結(jié)
以上是生活随笔為你收集整理的java后台关联微信公众号开发的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 本地购物车实现
- 下一篇: GDKOI2023 D1T1