基于springboot微信公眾號開發(微信自動回復)

發布時間: 2019-11-07 18:28:41 來源: 互聯網 欄目: Java 點擊:

這篇文章主要介紹了基于springboot微信公眾號開發(微信自動回復),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

效果圖

1.準備工作

申請微信訂閱號(個人只能申請訂閱號,而且沒什么功能,也無法認證),申請完畢,點擊 開發=>基本配置,如下圖:

服務器配置需要有 域名 80端口,我猜你沒有,這里推薦個實用工具,pagekite,下載鏈接,

這個工具需要 python2.7以上環境,還有郵箱一個,一個郵箱一個月,郵箱這東西大家懂得,

用pagekite申請完域名,就可以用自己的電腦做訂閱號服務器了.

2.服務器代碼

創建個springboot工程

pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
  </parent>


  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- 使thymeleaf支持h5標簽 -->
    <dependency>
      <groupId>net.sourceforge.nekohtml</groupId>
      <artifactId>nekohtml</artifactId>
      <version>1.9.22</version>
    </dependency>
    <dependency>
			      <groupId>dom4j</groupId>
			      <artifactId>dom4j</artifactId>
			      <version>1.6.1</version>
		    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

入口類

@SpringBootApplication
public class WeChatApplication {

  public static void main(String[] args) {
    SpringApplication.run(WeChatApplication.class, args);
    System.out.println("====啟動成功====");
  }

}

application.properties,配置server.port=80

Controller,這個是處理微信請求,get方法就是微信公眾平臺 服務器配置url請求的路徑,post是處理用戶事件

@RestController
public class WeChatController {
  @Autowired
  private WeChatService weChatService;
  /**
   * 處理微信服務器發來的get請求,進行簽名的驗證
   * 
   * signature 微信端發來的簽名
   * timestamp 微信端發來的時間戳
   * nonce   微信端發來的隨機字符串
   * echostr  微信端發來的驗證字符串
   */
  @GetMapping(value = "wechat")
  public String validate(@RequestParam(value = "signature") String signature,
      @RequestParam(value = "timestamp") String timestamp, 
      @RequestParam(value = "nonce") String nonce,
      @RequestParam(value = "echostr") String echostr) {
    return WeChatUtil.checkSignature(signature, timestamp, nonce) ? echostr : null;

  }
  /**
   * 此處是處理微信服務器的消息轉發的
   */
  @PostMapping(value = "wechat")
  public String processMsg(HttpServletRequest request) {
    // 調用核心服務類接收處理請求
    return weChatService.processRequest(request);    
  }
}

Service,處理post請求

/**
 * 核心服務類
 */
@Service
public class WeChatServiceImpl implements WeChatService{
  @Autowired
  private FeignUtil feignUtil;
  @Autowired
  private RedisUtils redisUtils;
  public String processRequest(HttpServletRequest request) {
    // xml格式的消息數據
    String respXml = null;
    // 默認返回的文本消息內容
    String respContent;
    try {
      // 調用parseXml方法解析請求消息
      Map<String,String> requestMap = WeChatUtil.parseXml(request);
       // 消息類型
      String msgType = (String) requestMap.get(WeChatContant.MsgType);
      String mes = null;
      // 文本消息
      if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_TEXT)) {
        mes =requestMap.get(WeChatContant.Content).toString();
        if(mes!=null&&mes.length()<2){
          List<ArticleItem> items = new ArrayList<>();
          ArticleItem item = new ArticleItem();
          item.setTitle("照片墻");
          item.setDescription("阿貍照片墻");
          item.setPicUrl("http://changhaiwx.pagekite.me/photo-wall/a/iali11.jpg");
          item.setUrl("http://changhaiwx.pagekite.me/page/photowall");
          items.add(item);
          
          item = new ArticleItem();
          item.setTitle("哈哈");
          item.setDescription("一張照片");
          item.setPicUrl("http://changhaiwx.pagekite.me/images/me.jpg");
          item.setUrl("http://changhaiwx.pagekite.me/page/index");
          items.add(item);
          
          item = new ArticleItem();
          item.setTitle("小游戲2048");
          item.setDescription("小游戲2048");
          item.setPicUrl("http://changhaiwx.pagekite.me/images/2048.jpg");
          item.setUrl("http://changhaiwx.pagekite.me/page/game2048");
          items.add(item);
          
          item = new ArticleItem();
          item.setTitle("百度");
          item.setDescription("百度一下");
          item.setPicUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505100912368&di=69c2ba796aa2afd9a4608e213bf695fb&imgtype=0&src=http%3A%2F%2Ftx.haiqq.com%2Fuploads%2Fallimg%2F170510%2F0634355517-9.jpg");
          item.setUrl("http://www.baidu.com");
          items.add(item);
          
          respXml = WeChatUtil.sendArticleMsg(requestMap, items);
        }else if("我的信息".equals(mes)){
          Map<String, String> userInfo = getUserInfo(requestMap.get(WeChatContant.FromUserName));
          System.out.println(userInfo.toString());
          String nickname = userInfo.get("nickname");
          String city = userInfo.get("city");
          String province = userInfo.get("province");
          String country = userInfo.get("country");
          String headimgurl = userInfo.get("headimgurl");
          List<ArticleItem> items = new ArrayList<>();
          ArticleItem item = new ArticleItem();
          item.setTitle("你的信息");
          item.setDescription("昵稱:"+nickname+" 地址:"+country+" "+province+" "+city);
          item.setPicUrl(headimgurl);
          item.setUrl("http://www.baidu.com");
          items.add(item);
          
          respXml = WeChatUtil.sendArticleMsg(requestMap, items);
        }
      }
      // 圖片消息
      else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_IMAGE)) {
        respContent = "您發送的是圖片消息!";
        respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
      }
      // 語音消息
      else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VOICE)) {
        respContent = "您發送的是語音消息!";
        respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
      }
      // 視頻消息
      else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_VIDEO)) {
        respContent = "您發送的是視頻消息!";
        respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
      }
      // 地理位置消息
      else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LOCATION)) {
        respContent = "您發送的是地理位置消息!";
        respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
      }
      // 鏈接消息
      else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_LINK)) {
        respContent = "您發送的是鏈接消息!";
        respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
      }
      // 事件推送
      else if (msgType.equals(WeChatContant.REQ_MESSAGE_TYPE_EVENT)) {
        // 事件類型
        String eventType = (String) requestMap.get(WeChatContant.Event);
        // 關注
        if (eventType.equals(WeChatContant.EVENT_TYPE_SUBSCRIBE)) {
          respContent = "謝謝您的關注!";
          respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
        }
        // 取消關注
        else if (eventType.equals(WeChatContant.EVENT_TYPE_UNSUBSCRIBE)) {
          // TODO 取消訂閱后用戶不會再收到公眾賬號發送的消息,因此不需要回復
        }
        // 掃描帶參數二維碼
        else if (eventType.equals(WeChatContant.EVENT_TYPE_SCAN)) {
          // TODO 處理掃描帶參數二維碼事件
        }
        // 上報地理位置
        else if (eventType.equals(WeChatContant.EVENT_TYPE_LOCATION)) {
          // TODO 處理上報地理位置事件
        }
        // 自定義菜單
        else if (eventType.equals(WeChatContant.EVENT_TYPE_CLICK)) {
          // TODO 處理菜單點擊事件
        }
      }
      mes = mes == null ? "不知道你在干嘛" : mes;
      if(respXml == null)
        respXml = WeChatUtil.sendTextMsg(requestMap, mes);
      System.out.println(respXml);
      return respXml;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
    
  }
}

微信工具類(只寫了回復文本消息,和圖文消息,其他的都是大同小異)

package com.wechat.util;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.wechat.bean.ArticleItem;

/**
 * 請求校驗工具類
 * 
 * @author 32950745
 *
 */
public class WeChatUtil {  

  /**
   * 驗證簽名
   * 
   * @param signature
   * @param timestamp
   * @param nonce
   * @return
   */
  public static boolean checkSignature(String signature, String timestamp, String nonce) {
    String[] arr = new String[] { WeChatContant.TOKEN, timestamp, nonce };
    // 將token、timestamp、nonce三個參數進行字典序排序
    // Arrays.sort(arr);
    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");
      // 將三個參數字符串拼接成一個字符串進行sha1加密
      byte[] digest = md.digest(content.toString().getBytes());
      tmpStr = byteToStr(digest);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    content = null;
    // 將sha1加密后的字符串可與signature對比,標識該請求來源于微信
    return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
  }

  /**
   * 將字節數組轉換為十六進制字符串
   * 
   * @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;
  }

  /**
   * 將字節轉換為十六進制字符串
   * 
   * @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;
  }

  private static void sort(String a[]) {
    for (int i = 0; i < a.length - 1; i++) {
      for (int j = i + 1; j < a.length; j++) {
        if (a[j].compareTo(a[i]) < 0) {
          String temp = a[i];
          a[i] = a[j];
          a[j] = temp;
        }
      }
    }
  }

  /**
   * 解析微信發來的請求(xml)
   * 
   * @param request
   * @return
   * @throws Exception
   */
  @SuppressWarnings({ "unchecked"})
  public static Map<String,String> parseXml(HttpServletRequest request) throws Exception {
    // 將解析結果存儲在HashMap中
    Map<String,String> map = new HashMap<String,String>();

    // 從request中取得輸入流
    InputStream inputStream = request.getInputStream();
    // 讀取輸入流
    SAXReader reader = new SAXReader();
    Document document = reader.read(inputStream);
    // 得到xml根元素
    Element root = document.getRootElement();
    // 得到根元素的所有子節點
    List<Element> elementList = root.elements();
    // 遍歷所有子節點
    for (Element e : elementList)
      map.put(e.getName(), e.getText());

    // 釋放資源
    inputStream.close();
    inputStream = null;
    return map;
  }

  public static String mapToXML(Map map) {
    StringBuffer sb = new StringBuffer();
    sb.append("<xml>");
    mapToXML2(map, sb);
    sb.append("</xml>");
    try {
      return sb.toString();
    } catch (Exception e) {
    }
    return null;
  }

  private static void mapToXML2(Map map, StringBuffer sb) {
    Set set = map.keySet();
    for (Iterator it = set.iterator(); it.hasNext();) {
      String key = (String) it.next();
      Object value = map.get(key);
      if (null == value)
        value = "";
      if (value.getClass().getName().equals("java.util.ArrayList")) {
        ArrayList list = (ArrayList) map.get(key);
        sb.append("<" + key + ">");
        for (int i = 0; i < list.size(); i++) {
          HashMap hm = (HashMap) list.get(i);
          mapToXML2(hm, sb);
        }
        sb.append("</" + key + ">");

      } else {
        if (value instanceof HashMap) {
          sb.append("<" + key + ">");
          mapToXML2((HashMap) value, sb);
          sb.append("</" + key + ">");
        } else {
          sb.append("<" + key + "><![CDATA[" + value + "]]></" + key + ">");
        }

      }

    }
  }
  /**
   * 回復文本消息
   * @param requestMap
   * @param content
   * @return
   */
   public static String sendTextMsg(Map<String,String> requestMap,String content){
    
    Map<String,Object> map=new HashMap<String, Object>();
    map.put("ToUserName", requestMap.get(WeChatContant.FromUserName));
    map.put("FromUserName", requestMap.get(WeChatContant.ToUserName));
    map.put("MsgType", WeChatContant.RESP_MESSAGE_TYPE_TEXT);
    map.put("CreateTime", new Date().getTime());
    map.put("Content", content);
    return mapToXML(map);
  }
   /**
   * 回復圖文消息
   * @param requestMap
   * @param items
   * @return
   */
  public static String sendArticleMsg(Map<String,String> requestMap,List<ArticleItem> items){
    if(items == null || items.size()<1){
      return "";
    }
    Map<String,Object> map=new HashMap<String, Object>();
    map.put("ToUserName", requestMap.get(WeChatContant.FromUserName));
    map.put("FromUserName", requestMap.get(WeChatContant.ToUserName));
    map.put("MsgType", "news");
    map.put("CreateTime", new Date().getTime());
    List<Map<String,Object>> Articles=new ArrayList<Map<String,Object>>(); 
    for(ArticleItem itembean : items){
      Map<String,Object> item=new HashMap<String, Object>();
      Map<String,Object> itemContent=new HashMap<String, Object>();
      itemContent.put("Title", itembean.getTitle());
      itemContent.put("Description", itembean.getDescription());
      itemContent.put("PicUrl", itembean.getPicUrl());
      itemContent.put("Url", itembean.getUrl());
      item.put("item",itemContent);
      Articles.add(item);
    }
    map.put("Articles", Articles);
    map.put("ArticleCount", Articles.size());
    return mapToXML(map);
  }
  
}

微信常量

public class WeChatContant {
   //APPID
  public static final String appID = "appid";
  //appsecret
  public static final String appsecret = "appsecret";
  // Token
  public static final String TOKEN = "zch";
  public static final String RESP_MESSAGE_TYPE_TEXT = "text";
  public static final Object REQ_MESSAGE_TYPE_TEXT = "text";
  public static final Object REQ_MESSAGE_TYPE_IMAGE = "image";
  public static final Object REQ_MESSAGE_TYPE_VOICE = "voice";
  public static final Object REQ_MESSAGE_TYPE_VIDEO = "video";
  public static final Object REQ_MESSAGE_TYPE_LOCATION = "location";
  public static final Object REQ_MESSAGE_TYPE_LINK = "link";
  public static final Object REQ_MESSAGE_TYPE_EVENT = "event";
  public static final Object EVENT_TYPE_SUBSCRIBE = "SUBSCRIBE";
  public static final Object EVENT_TYPE_UNSUBSCRIBE = "UNSUBSCRIBE";
  public static final Object EVENT_TYPE_SCAN = "SCAN";
  public static final Object EVENT_TYPE_LOCATION = "LOCATION";
  public static final Object EVENT_TYPE_CLICK = "CLICK";
  
  public static final String FromUserName = "FromUserName";
  public static final String ToUserName = "ToUserName";
  public static final String MsgType = "MsgType";
  public static final String Content = "Content";
  public static final String Event = "Event";
  
}

圖文消息實體bean

public class ArticleItem {
  private String Title;
  private String Description;
  private String PicUrl;
  private String Url;
  public String getTitle() {
    return Title;
  }
  public void setTitle(String title) {
    Title = title;
  }
  public String getDescription() {
    return Description;
  }
  public void setDescription(String description) {
    Description = description;
  }
  public String getPicUrl() {
    return PicUrl;
  }
  public void setPicUrl(String picUrl) {
    PicUrl = picUrl;
  }
  public String getUrl() {
    return Url;
  }
  public void setUrl(String url) {
    Url = url;
  }
  
}

好了運行項目,在公眾平臺配置好url,個人訂閱號完成.

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持我們。

本文標題: 基于springboot微信公眾號開發(微信自動回復)
本文地址: http://www.leskzw.tw/ruanjian/java/284831.html

如果認為本文對您有所幫助請贊助本站

支付寶掃一掃贊助微信掃一掃贊助

  • 支付寶掃一掃贊助
  • 微信掃一掃贊助
  • 支付寶先領紅包再贊助
    聲明:凡注明"本站原創"的所有文字圖片等資料,版權均屬編程客棧所有,歡迎轉載,但務請注明出處。
    Java方法重載Overload原理及使用解析基于javamelody監控springboot項目過程詳解
    Top 广东好彩1中奖规则