How to connect to the server with WeChat development API, let’s introduce it to you below
1. Explanation
* This example is developed and demonstrated according to the WeChat development document: http://mp.weixin.qq.com/wiki/home/index.html latest version (4/3/2016 5:34:36 PM).
* Editing platform: myeclipse10.7+win32+jdk1.7+tomcat7.0
* Server: Alibaba Cloud Windows Server 2008 64bits
* Platform requirements: servlet usage annotation method, platform requirements: j2ee6.0+, jdk6.0+, tomcat7.0+
* Demo focuses more on API parsing.
* For the sake of testing instructions, each test case is independent and does not depend on other methods. Don't consider the packaging much.
* The demonstration is carried out as much as possible according to the API requirements. Purpose: understand how the document is used and achieve the effect of learning from one example and applying it to others.
* Knowledge requirements: solid Java foundation, understanding http network communication knowledge, having enough understanding of Javaweb, json analysis
* Current time: 4/3/2016 5:32:57 PM, this time shall prevail.
2. Original document (abstract)
Document address: http://mp.weixin.qq.com/wiki/8/f9a0b8382e0b77d87b3bcc1ce6fbc104.html
To access the development of WeChat public platform, developers need to follow the following steps:
1. Fill in the server configuration
2. Verify the validity of the server address
3. Implement business logic based on interface documents
3. Document understanding
Verify the validity of the server address
1. API is introduced like this:
After the developer submits the information, the WeChat server will send a GET request to the filled-in server address URL. The GET request carries four parameters: signature, timestamp, nonce, echostr
The developer checks the request by verifying the signature (there is a verification method below).
If you confirm that the GET request comes from the WeChat server, please return the echostr parameter content as it is, and the access takes effect and becomes a developer successfully. Otherwise, the access fails.
The encryption/checking process is as follows:
1) Sort dictionary order of token, timestamp, and nonce
2) Splice three parameter strings into one string for sha1 encryption
3) The strings obtained by the developer can be compared with signature to identify the request originated from WeChat.
2. Understand
It means that the request is in the "GET" mode, and accessing the request will return four parameters: signature, timestamp, nonce, echostr.
We need to accept these parameters and then process them. If the verification is successful, the received "echostr" is returned, otherwise the verification fails.
The verification method is to sort the accepted three parameters token, timestamp, and nonce, then sha1 encryption, and finally compare it with signature.
*The encrypted string can be compared with signature. If it is equal [the API may not explain it very clearly], return "echostr" and verify it successfully.
3. Realize
Create a servlet CoreServlet to implement HttpServlet and overload the doGet method.
Parameter preparation
// Set a global token, the developer sets it himself. api explains this way: the token can be filled in by the developer at will, // Used as a generation signature (the token will be compared with the token contained in the interface URL to verify security) String token = "wgyscsf";// According to the API description, obtain the above four parameters String signature = req.getParameter("signature"); String timestamp = req.getParameter("timestamp"); String nonce = req.getParameter("nonce"); String echostr = req.getParameter("echostr");Operation according to the three steps mentioned by the API
// Step 1: Sort dictionary order of token, timestamp, nonce String[] parms = new String[] { token, timestamp, nonce };// Put the strings that need to be sorted dictionary in the array Arrays.sort(parms);// Sort dictionary order according to API requirements [Baidu: What is dictionary order sort] // Step 2: Splice the three parameter strings into a string for sha1 encryption [Baidu: java sha1 encryption] // Splice the string String parmsString = "";// Note that it cannot =null here. for (int i = 0; i < parms.length; i++) { parmsString += parms[i];}// sha1 encryption String mParms = null;// The result after encryption... // This place is the implementation of sha1 encryption, no code is posted mParms = hexString.toString();// Encryption result/* * api requirements: If you confirm that this GET request comes from the WeChat server, please return the echostr parameter content as it is, and the access takes effect and becomes a developer successfully, otherwise the access fails. */// Step 3: The developer obtains the encrypted string and can compare it with the signature to identify that the request comes from the successful access of WeChat. System.out.println(TAG + ":" + mParms + "--->" + signature);if (mParms.equals(signature)) { // System.out.println(TAG + ":" + mParms + "---->" + signature); printWriter.write(echostr);} else { // Access failed, no need to write back // System.out.println(TAG + "Access failed");}4. Fill in the server configuration
1) Including content server configuration is mainly the server and WeChat access interface that we need to configure after we write our own code to access the WeChat development platform.
2) Server operation Open the server's tomcat and put the written code into the webapps file.
3) WeChat public platform operation
*Apply for a WeChat test account (scan directly with WeChat to log in): http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
*Open the WeChat public platform test number and configure interface configuration information. The configuration is as follows
URL: http://ip/WeixinApiDemo/CoreServlet
Token:wgyscsf
*There will be reminded when submitting, configuration success and failure.
All operation source codes in this part can be used directly
package com.gist.servlet;import java.io.IOException;import java.io.PrintWriter;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.Arrays;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * @author Gao Yuan</n> Email: [email protected]</n> Blog http://blog.csdn.net/wgyscsf</n> * Writing period 2016-4-3 4:34:05 pm */@WebServlet("/CoreServlet")public class CoreServlet extends HttpServlet { String TAG = "CoreServlet"; /* * Step 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-in server address URL. * The GET request carries four parameters: signature, timestamp, nonce, echostr * The developer verifies the request by verifying the signature (there is a verification method below). If you confirm that the GET request comes from the WeChat server, please return the echostr parameter content as it is, *, the access takes effect and becomes a developer successfully, otherwise the access fails. * * The encryption/checking process is as follows: 1. Sort dictionary order of token, timestamp, and nonce 2. * Splice the three parameter strings into a string for sha1 encryption 3. The strings after the developer obtains the encrypted strings can be compared with signature, identifying that the request comes from WeChat */ /* * Dictionary sorting (lexicographical * order) is a sorting method for random variables to form sequences. The method is to form a sequence from small to large in alphabetical order or in the order of small and large numbers. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Set encoding req.setCharacterEncoding("utf-8"); resp.setContentType("html/text;charset=utf-8"); resp.setCharacterEncoding("utf-8"); // Get output stream PrintWriter printWriter = resp.getWriter(); // Set a global token, the developer sets it himself. api explains this: the token can be filled in at will by the developer, // Used as a generation signature (the token will be compared with the token contained in the interface URL to verify security) String token = "wgyscsf"; // According to the API description, get the above four parameters String signature = req.getParameter("signature"); String timestamp = req.getParameter("timestamp"); String nonce = req.getParameter("nonce"); String echostr = req.getParameter("echostr"); // // temp: temporary printing, watch the return parameter situation // System.out.println(TAG + ":signature:" + signature + ",timestamp:" // + timestamp + ",nonce:" + nonce + ",echostr:" + echostr); // Access according to the "encryption/verification process" mentioned by the API. There are three steps in total // Step 1: Sort dictionary order of token, timestamp, nonce three parameters String[] parms = new String[] { token, timestamp, nonce };// Put the strings that need to be sorted dictionary in the array Arrays.sort(parms);// Sort dictionary order according to API requirements // Step 2: Splice the three parameter strings into a string for sha1 encryption // Splice the string String parmsString = "";// Note that it cannot =null here. for (int i = 0; i < parms.length; i++) { parmsString += parms[i]; } // sha1 encryption String mParms = null;// Encrypted result MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } digest.update(parmsString.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // Convert byte array to hexadecimal number 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); } mParms = hexString.toString();// Encryption result/* * api requirements: If you confirm that the GET request is from the WeChat server, please return the echostr parameter content as it is, and the access will take effect and become a developer successfully. Otherwise, the access will fail. */ // Step 3: The developer obtains the encrypted string and can compare it with the signature to identify that the request comes from the successful access of WeChat. System.out.println(TAG + ":" + mParms + "--->" + signature); if (mParms.equals(signature)) { // System.out.println(TAG + ":" + mParms + "---->" + signature); printWriter.write(echostr); } else { // Access failed, no need to write back // System.out.println(TAG + "Access failed"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
The first article of Java WeChat development API is introduced to you here. I hope you will continue to pay attention to the updated content in the future. Thank you!