(1) Internet mapping tool
natapp is a reverse proxy software based on ngrok, which establishes a safe channel between the public network and the local Web server. The tool provides free network channels for Internet mapping. However, free domain names are randomly generated and will change every time they are started. If you need to pay for a fixed domain name, it depends on your personal choice.
Registration website: https://natapp.cn/
After successful registration, select the tunnel and configure the basic information
Download local client tools
Then natapp Create a new config.exe under the same level directory INI file
#Place this file in the natapp peer directory, and the program will read the [default] section #In the command line parameter mode, such as natapp -authtoken=xxx, the same parameters will override this configuration #Command line parameter - config = you can specify any config INI file [default] authtoken=46ea912760053247 #authtoken corresponding to a tunnel clienttoken= #The corresponding client's clienttoken will ignore the authtoken. If not, please leave it blank, log=stdout #Log log file, local file can be specified, none = no record, stdout = direct screen output, and the default is none loglevel=DEBUG #The log levels DEBUG, INFO, WARNING, ERROR are DEBUG by default http_proxy= #Proxy settings such as http://10.123.10.10:3128 Please be sure to leave blank for non agent Internet users
Just fill in authtoken
This local port needs to be determined according to the port opened by your specific application
After building the configuration file, save it, configure the mapping port in the background of natapp, and start natapp Exe, remember to adjust the info, and the mapped domain name printed out is at the DEBUG level
The red border in the figure above shows the generated Internet address. According to this address, you can access your application on the Internet
(2) Principle of wechat data interaction
WeChat official account has two modes. One is editing mode, that is, the menu way directly operated by official account backstage panel. The second development mode is to integrate the background server program to process message and respond. The two modes are mutually exclusive. When the development mode is enabled, the editing mode will be closed.
Among them, WeChat backstage is WeChat's server services. WeChat official account server refers to our own development of program services. The above figure shows that when users interact with the services we develop through WeChat official account, they need to be forwarded through WeChat background, and the intermediate forwarding is through the XML data format.
(3) Development mode access
1. Fill in the server configuration
After logging into the official website of wechat public platform, on the development basic settings page of the official website of the public platform, check the protocol to become a developer, click the "modify configuration" button, and fill in the server address (URL), Token and encoding aeskey, where the URL is the interface URL used by the developer to receive wechat messages and events. The Token can be filled in arbitrarily by the developer and used to generate a signature (the Token will be compared with the Token contained in the interface URL to verify the security). The encoding aeskey is filled in manually or randomly generated by the developer and will be used as the encryption and decryption key of the message body.
[1] You need to fill in the authentication interface you provide to the wechat background, which is the complete path of the interface. The request method is GET
[2] Token is a self-defined string, which should be consistent with this when developing locally
[3] Randomly generated secret key
2. Verify the validity of the server address
After the developer submits the information, the wechat server will send a GET request to the filled server address URL. The parameters carried by the GET request are shown in the following table:
The developer verifies the request by verifying the signature (the verification method is shown below). If you confirm that the GET request comes from the wechat server, please return the content of the echostr parameter as it is. Then the access will take effect and become a developer. Otherwise, the access will fail. The encryption / verification process is as follows:
1) Sort the token, timestamp and nonce parameters in dictionary order
2) Splice three parameter strings into one string for sha1 encryption
3) The encrypted string obtained by the developer can be compared with signature to identify that the request comes from wechat
@RestController @Slf4j public class WxController { private String token = "demo"; /** * Wechat authentication * Sort the three parameters token, timestamp and nonce in dictionary order. 2) splice the three parameter strings into a string for sha1 encryption * The encrypted string obtained by the developer can be compared with signature to identify that the request comes from wechat */ @GetMapping(value = "/wx/auth") @ResponseBody public String auth(HttpServletRequest request) { String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); log.info("Wechat authentication"); if (CheckUtil.checkSignature(signature, timestamp, nonce, token)) { //If the verification is successful, the random string will be returned in the original way return echostr; } return null; } }
public class CheckUtil { public static boolean checkSignature(String signature, String timestamp, String nonce, String tooken) { //1. Define the array to store token, timestamp and nonce String[] arr = {tooken, timestamp, nonce}; //2. Sort the array Arrays.sort(arr); //3. Generate string StringBuilder sb = new StringBuilder(); for (String s : arr) { sb.append(s); } //4.1 encryption String temp = getSha1(sb.toString()); if (temp != null) { //5. Compare the encrypted string with the encrypted signature sent by wechat and return the result return temp.equals(signature); } return false; } public static String getSha1(String str) { if (str == null || str.length() == 0) { return null; } char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { MessageDigest mdTemp = MessageDigest.getInstance("SHA1"); mdTemp.update(str.getBytes("UTF-8")); byte[] md = mdTemp.digest(); int j = md.length; char[] buf = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; buf[k++] = hexDigits[byte0 >>> 4 & 0xf]; buf[k++] = hexDigits[byte0 & 0xf]; } return new String(buf); } catch (Exception e) { return null; } } }
Note: the service address is filled in the complete URL address, not just the domain name, which means that you can customize the request breakpoints and have your own other business processing logic
3. Message receiving and response in development mode
(1) Explain
Official reference documents:
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
Wechat messages are delivered through XML protocol, so we need to process messages through an XML tool when receiving and sending messages. There are many such tool classes on the Internet, which will not be described in detail
(2) Receive and respond to messages
When an ordinary wechat user sends a message to a public account, the wechat server sends the XML packet of the POST message to the URL filled in by the developer.
/** * Receive official account message interface */ @PostMapping(value = "/wx/auth") @ResponseBody public String getMessage(HttpServletRequest request) throws Exception { String resultXml = null; Map<String, String> map = MessageFormat.xmlToMap(request); String toUserName = map.get("ToUserName"); String fromUserName = map.get("FromUserName"); String createTime = map.get("CreateTime"); String msgType = map.get("MsgType"); String content = map.get("Content"); if ("text".equals(msgType)) { //If you receive a text message, all fields need to be passed during transmission Map<String, String> sendMap = new HashMap<>(); sendMap.put("ToUserName", fromUserName); sendMap.put("FromUserName", toUserName); sendMap.put("MsgType", "text"); sendMap.put("Content", "Hello World"); sendMap.put("CreateTime", String.valueOf(new Date().getTime())); sendMap.put("MsgId", "12345678940123456"); resultXml = MessageFormat.mapToXml(sendMap); } log.info(resultXml); return resultXml; }
[note]
When we are building the response message, if we do not use the entity object, but only use the Map to convert XML, note that all fields of wechat XML must be transmitted, otherwise it will not be transmitted normally and the server error will be displayed. It is suggested to build an object storage, so there will be no problem.
(3) Event push
[message type]
In the above example, only text type is used. In addition to text, picture message image, voice message, video message, link message and geographic location message can also be used
[event push] event
Attention: subscribe
Unsubscribe: unsubscribe
CLICK menu: CLICK, VIEW
Reference documents:
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html