springboot WeChat公衆番号に基づいて開発(WeChat自動返信)


効果図

1.準備作業
WeChat購読番号を申請します。(個人は購読番号を申請するしかなく、機能もないし、認証もできません。)申請が終わりました。開発をクリックします。基本的な配置は以下の図の通りです。

サーバーの構成にはドメイン名80ポートが必要です。ここでは実用的なツールを紹介します。
このツールはpython 2.7以上の環境が必要です。メールボックスもあります。一ヶ月間、メールボックスというものは分かります。
pagekiteでドメイン名を申請したら、自分のコンピュータで購読番号サーバを作ることができます。
2.サーバコード
スプリングブックプロジェクトを作成します。
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、これはWeChat要求を処理するので、get方法はWeChat公衆プラットフォームサーバの配置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 "";
    
  }
}
WeChatツール類(返信テキストメッセージと図文メッセージだけを書いています。他は大同小異です。)

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を配置して、個人の購読号は完成します。
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。