Java server configuration for WeChat official account

WeChat official account development server configuration

Because the company web page needs to call the official account number api, so it makes special records.

Because the IP address obtained by wechat server is not fixed, you need to call api and configure the server address

1. WeChat public platform configuration

To configure the server, first log in to the wechat public platform. The general steps are as follows:

  1. Log in to wechat public platform, and find development basic configuration in the bottom submenu of menu bar on the left

 

 

 

2. Enter basic configuration

 

Official documents: https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

 

 

 

Access overview

To access wechat public platform development, developers need to complete the following steps:

1. Fill in server configuration

2. Verify the validity of the server address

3. Implement business logic according to interface documents

These three steps are described in detail below.

Step 1: fill in the server configuration

After logging in 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, fill in the server address (URL), Token and encoding aeskey, where URL is the interface URL used by the developer to receive wechat messages and events. The Token can be filled in by the developer at will and used as the generation signature (the Token will be compared with the Token contained in the interface URL to verify the security). Encoding aeskey is manually filled in or randomly generated by the developer and will be used as the encryption and decryption key of the message body.

At the same time, developers can choose message encryption and decryption mode: plaintext mode, compatibility mode and security mode. The mode selection and server configuration will take effect immediately after submission. Please fill in and select carefully. The default state of encryption and decryption mode is clear text mode. To select compatibility mode and security mode, you need to configure the relevant encryption and decryption code in advance, For details, please refer to the document of message body signature and encryption / decryption .

 

 

Step 2: verify that the message is indeed from the wechat server

After the developer submits the information, the wechat server will send the GET request to the URL of the server address filled in. The parameters of the GET request are shown in the following table:

parameter describe
signature Wechat encryption signature combines the token parameter filled in by the developer with the timestamp parameter and nonce parameter in the request.
timestamp time stamp
nonce random number
echostr Random string

I use java authentication

 

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

/**
 * zh  on 2020/5/18.
 */
public class SignUtil {
    private static String token = "WeChatToken";// On the official account of WeChat token Consistent, server token( token),What does it say here. What does the server fill in

    /**
     * Verification signature
     *
     * @param signature autograph
     * @param timestamp time stamp
     * @param nonce     random number
     * @return Boolean value
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String checktext = null;
        if (null != signature) {
            //Yes ToKen,timestamp,nonce Sort by dictionary
            String[] paramArr = new String[]{token, timestamp, nonce};
            Arrays.sort(paramArr);
            //Spell the sorted result into a string
            String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                //String after docking sha1 encryption
                byte[] digest = md.digest(content.toString().getBytes());
                checktext = byteToStr(digest);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        //The encrypted string and signature Compare
        return checktext != null ? checktext.equals(signature.toUpperCase()) : false;
    }

    /**
     * Convert byte array to my hexadecimal string
     *
     * @param byteArrays Character array
     * @return character string
     */
    private static String byteToStr(byte[] byteArrays) {
        String str = "";
        for (int i = 0; i < byteArrays.length; i++) {
            str += byteToHexStr(byteArrays[i]);
        }
        return str;
    }

    /**
     * Convert bytes to hexadecimal strings
     *
     * @param myByte byte
     * @return character string
     */
    private static String byteToHexStr(byte myByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tampArr = new char[2];
        tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
        tampArr[1] = Digit[myByte & 0X0F];
        String str = new String(tampArr);
        return str;
    }
}

Call:

**
 * zh  on 2020/5/18.
 */
@RestController
@RequestMapping(path = "wxPublic")
@CrossOrigin
/*
Verify official account number token
 */
public class WxPublicController {


    private static final Logger log = LoggerFactory.getLogger(TempMaterialController.class);


    @GetMapping(value = "serial")
    public String checkSign(HttpServletRequest request, HttpServletResponse response) {
        try {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            log.info("itself" + signature);
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                return echostr;
            }
        } catch (Exception e) {
            log.error("Official account verification token fail", e);
        }
        return null;
    }
}

Note that the server address of your project publishing (must be a filed domain name, and the port must be 80 or 443) + project name + interface name: it means that your project must be published on a server accessible by an external network, and the published port must be 80 or 443,

 

 

Tags: Java encoding SHA1 network

Posted on Tue, 19 May 2020 04:40:02 -0700 by werty37