1. WeChat public account development - preparation before development

foreword

        I recently completed the development of a complete set of WeChat public accounts, so I will share it quickly. The column just happened to be applied for, so let's write something in the column. I myself do javaweb development, and now I work on android. It can be said that I have never done this thing before. The documentation on the official website is written well, but if you get started, it will inevitably be a little confusing. If you go to the documentation to continue in-depth development, you will get twice the result with half the effort;

        I will not say anything about registering an account. In that respect, individuals will register. The suggestion is to get a developer test account, because the functions are the same, and the developer account has more permissions. If you have company information, you can also review the information and use the official account to learn. The background code is the same. After the development is completed, you only need to change the background configuration, and you don't need to move the code at all. Of course, I mean under the premise that the code is written beautifully;

        Attach 2 addresses, which are the addresses of the official account and the test account:

        Official account homepage

        Test number address

text

        After registering and logging in, enter the text, the configuration of the official version and the test account are similar, I will take the official version as an example;

        

        First, set the developer password (appsecret) and ip whitelist. After this password is generated, you can copy and paste it and save it. After this, you will not be able to see it unless you reset the new password. The ip whitelist refers to the connection ip that your service is allowed to access, and the ip address of my server is temporarily set here;     

        The server address points to the address where you process WeChat requests, using the full name, http://. . . , this address must be an IP address whitelisted address. After the configuration is complete, this address will be the address of all WeChat network requests to access in the future. And WeChat accesses port 80 by default, do not use other ports. If the token token is set at will, it is fine. The verification operation when the server is configured in the common language; the message encryption key is also randomly generated, and it is just copied when it is used;

        When enabled, go back to the url address to send a request. This background needs to be processed. In fact, it is very simple. Just compare the token to see if it is your own verification request, and then send it back to him with a random code sent by him. Okay, the code is as follows:

        @Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//First verify whether it is the url of the configured token
		if (Sign.checkSignature(request.getParameter("signature"), request.getParameter("timestamp"), request.getParameter("nonce"))) {
			Utils.out(response, request.getParameter("echostr"));//Wechat official account to verify Token, just output the incoming echostr parameter as it is
			return;}
	}

        My background here is simply written in servlet, the reason is the same, the processing of WeChat information is mainly concentrated in the control layer and the business layer; here to process a get request, only need to write a tool class to verify the WeChat Just sign it;

package com.wx.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * WeChat signature verification tool class
 * @author Baidu
 */
public class Sign {
    
    // Consistent with the Token in the interface configuration information
    private static String wxToken = "yoursToken";

    /**
     * WeChat verification signature
     * @param signature WeChat encrypted signature, signature combines the token parameter filled in by the developer with the timestamp parameter and nonce parameter in the request.
     * @param timestamp timestamp
     * @param nonce random number
     * Is @return correct?
     */
    public static boolean checkSignature(String signature, String timestamp,String nonce) {
        // 1. Sort the three parameters of token, timestamp and nonce in lexicographic order
        String[] arr = new String[] { wxToken, timestamp, nonce };
        Arrays.sort(arr);
        // 2. Concatenate the three parameter strings into one string for sha1 encryption
        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");
            // Concatenate the three parameter strings into one string for sha1 encryption
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace ();
        }
        content = null;
        // 3. Compare the sha1-encrypted string with signature to identify that the request originates from WeChat
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * Convert byte array to hex string
     * @param byteArray byte array
     * @return String
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * Convert bytes to hex string
     * @param mByte bytes object
     * @return String
     */
    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;
    }
}
        If the verification is passed, the front-end will display that the configuration is successful, then it means that the configuration is complete, and you can start the next step of development!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325732748&siteId=291194637