600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 微信公众号开发-接收与回复消息

微信公众号开发-接收与回复消息

时间:2022-06-20 13:56:46

相关推荐

微信公众号开发-接收与回复消息

微信公众平台:https://mp./wiki?t=resource/res_main&id=mp1445241432&token=&lang=zh_CN

申请测试公众号

@Resourceprivate WechatService wechatService;/***验证微信服务器*@paramout*@paramresponse*@paramsignature*@paramtimestamp*@paramnonce*@paramechostr*/@RequestMapping(value = "/callback",method = RequestMethod.GET)public void callback(PrintWriter out, HttpServletResponse response, @RequestParam(value = "signature", required = false) String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr) {log.info("signature:" + signature + "\ntimestamp:" + timestamp + "\nnonce:" + nonce + "\nechostr:" + echostr); if (CheckUtil.checkSignature(signature, timestamp, nonce)) {log.info(echostr); out.print(echostr); }}/***接收来自微信发来的消息*@paramrequest*@paramresponse*/@ResponseBody@RequestMapping(value = "/callback",method = RequestMethod.POST)public void getmessage(HttpServletRequest request, HttpServletResponse response) {response.setCharacterEncoding("utf-8"); PrintWriter out = null; try {out = response.getWriter(); } catch (IOException e) {e.printStackTrace(); }String responseMessage = wechatService.processRequest(request); System.out.println(responseMessage); out.print(responseMessage); out.flush();}

CheckUtil.java

public class CheckUtil {private static final Stringtoken= "zhangyingjie"; public static boolean checkSignature(String signature, String timestamp, String nonce) {// 拼接字符串String[] arr = new String[] {token, timestamp, nonce };// 排序Arrays.sort(arr);// 生成字符串StringBuffer content = new StringBuffer();for (int i = 0; i < arr.length; i++) {content.append(arr[i]);}// SHA1加密String tmp = DecriptUtil.SHA1(content.toString());return tmp.equals(signature); }}

DecriptUtil.java

public static String SHA1(String decript) {try {MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(decript.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) {String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) {hexString.append(0); }hexString.append(shaHex); }return hexString.toString(); } catch (NoSuchAlgorithmException e) {e.printStackTrace(); }return "";}

WechatMessageUtil.java

public class WechatMessageUtil {// 各种消息类型,除了扫带二维码事件 /** *文本消息 */ public static final StringMESSAGE_TEXT= "text"; /** *图片消息 */ public static final StringMESSAtGE_IMAGE= "image"; /** *图文消息 */ public static final StringMESSAGE_NEWS= "news"; /** *语音消息 */ public static final StringMESSAGE_VOICE= "voice"; /** *视频消息 */ public static final StringMESSAGE_VIDEO= "video"; /** *小视频消息 */ public static final StringMESSAGE_SHORTVIDEO= "shortvideo"; /** *地理位置消息 */ public static final StringMESSAGE_LOCATION= "location"; /** *链接消息 */ public static final StringMESSAGE_LINK= "link"; /** *事件推送消息 */ public static final StringMESSAGE_EVENT= "event"; /** *事件推送消息中,事件类型,subscribe(订阅) */ public static final StringMESSAGE_EVENT_SUBSCRIBE= "subscribe"; /** *事件推送消息中,事件类型,unsubscribe(取消订阅) */ public static final StringMESSAGE_EVENT_UNSUBSCRIBE= "unsubscribe"; /** *事件推送消息中,上报地理位置事件 */ public static final StringMESSAGE_EVENT_LOCATION_UP= "LOCATION"; /** *事件推送消息中,自定义菜单事件,点击菜单拉取消息时的事件推送 */ public static final StringMESSAGE_EVENT_CLICK= "CLICK"; /** *事件推送消息中,自定义菜单事件,点击菜单跳转链接时的事件推送 */ public static final StringMESSAGE_EVENT_VIEW= "VIEW"; /** *将xml转化为Map集合 * *@paramrequest *@return*/ public static Map<String, String> xmlToMap(HttpServletRequest request) {Map<String, String> map = new HashMap<String, String>();SAXReader reader = new SAXReader();InputStream ins = null;try {ins = request.getInputStream();} catch (IOException e1) {e1.printStackTrace();}Document doc = null;try {doc = reader.read(ins);} catch (DocumentException e1) {e1.printStackTrace();}Element root = doc.getRootElement();@SuppressWarnings("unchecked")List<Element> list = root.elements();for (Element e : list) {map.put(e.getName(), e.getText());}try {ins.close();} catch (IOException e1) {e1.printStackTrace();}return map; }/** *文本消息转化为xml * *@paramtextMessage *@return*/ public static String textMessageToXml(TextMessage textMessage) {return MessageFormat.format("<xml>" +"<ToUserName><![CDATA[{0}]]></ToUserName>" +"<FromUserName><![CDATA[{1}]]></FromUserName>" +"<CreateTime>{2}</CreateTime>" +"<MsgType><![CDATA[text]]></MsgType>" +"<Content><![CDATA[{3}]]></Content>" +"</xml>", textMessage.getToUserName(), textMessage.getFromUserName(), textMessage.getCreateTime(), textMessage.getContent()); }}

WechatService.java

@Service("wechatService")public class WechatService {private static Loggerlog= Logger.getLogger(WechatService.class); public String processRequest(HttpServletRequest request) {Map<String, String> map = WechatMessageUtil.xmlToMap(request); log.info(map); // 发送方帐号(一个OpenID) String fromUserName = map.get("FromUserName"); // 开发者微信号 String toUserName = map.get("ToUserName"); // 消息类型 String msgType = map.get("MsgType"); // 默认回复一个"success" String responseMessage = "success"; // 对消息进行处理 if (WechatMessageUtil.MESSAGE_TEXT.equals(msgType)) {// 文本消息 TextMessage textMessage = new TextMessage(); textMessage.setMsgType(WechatMessageUtil.MESSAGE_TEXT); textMessage.setToUserName(fromUserName); textMessage.setFromUserName(toUserName); textMessage.setCreateTime(System.currentTimeMillis()); textMessage.setContent("我已经受到你发来的消息了"); responseMessage = WechatMessageUtil.textMessageToXml(textMessage); }log.info(responseMessage); return responseMessage; }}

BaseWechatMessage.java

@Datapublic class BaseWechatMessage {/** *开发者微信号 */ private String ToUserName; /** *发送方帐号(一个OpenID) */ private String FromUserName; /** *消息创建时间 (整型) */ private long CreateTime; /** *消息类型 */ private String MsgType; /** *消息id,64位整型 */ private String MsgId; }

TextMessage.java

@Datapublic class TextMessage extends BaseWechatMessage {/** *文本消息内容 */ private String Content;}

maven:

<!-- /artifact/com.thoughtworks.xstream/xstream --><dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.9</version></dependency><!-- /artifact/xmlpull/xmlpull --><dependency> <groupId>xmlpull</groupId> <artifactId>xmlpull</artifactId> <version>1.1.3.1</version></dependency><!--lombok--><dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version></dependency>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。