Access to WeChat public account: verify the validity of the server address

1. Access to WeChat public account

       When accessing the WeChat official account, the first step is to configure relevant information (url, token, etc.), and then verify the validity of the server address. Reference document:  Click to open the link

      This section mainly introduces the verification of the server-side address.


Second, the server-side code 


2.1 SignUtil.java signature tool class

package com.junlenet.core.weixin.util;

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

/**
 * Signature authentication tool class
 * @author Weijun Hu
 * @since Jul 9, 2016 at 10:19:36 AM
 */
public class SignUtil {

	/**
	 * The encryption/verification process is as follows:
		<li>1. Sort the three parameters of token, timestamp and nonce in lexicographic order</li>
		<li>2. Concatenate the three parameter strings into one string for sha1 encryption</li>
		<li>3. The encrypted string obtained by the developer can be compared with the signature, indicating that the request originated from WeChat</li>
	 * @param token
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 *@date Jul 9, 2016 at 10:19:36 AM
	 * @url http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html
	 */
	public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
		String[] arr = new String[] { token, timestamp, nonce };
		// Sort the three parameters of token, timestamp and nonce in lexicographic order
		Arrays.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");
			// 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;
		// 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
	 * @return
	 *@date July 9, 2016 at 10:20:53 AM
	 */
	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
	 * @return
	 *@date Jul 9, 2016 at 10:20:59 AM
	 */
	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;
	}
}



2.2 WechatController.java WeChat Controller class

package com.junlenet.core.weixin.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.junlenet.core.weixin.util.SignUtil;

/**
 * WeChat controller
 * @author Weijun Hu
 * @since Jul 9, 2016 at 10:19:36 AM
 */
@Controller
@RequestMapping("/wechatController")
public class WechatController {
	
	/**
	 * WeChat Official Account: Verify the validity of the server address<br>
	 * WeChat URL: http://IP:PORT/project name/wechatController/wechat.do<br>
	 * The developer verifies the request by checking the signature. If it is confirmed that the GET request is from the WeChat server, please return the echostr parameter content as it is, then the access will take effect and become a developer successfully, otherwise the access will fail. <br>
	 * Reference api: http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html
	 * @param request
	 * @param response
	 * @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
	 * @param echostr random string
	 *@date July 9, 2016 at 11:10:30 AM
	 */
	@RequestMapping(value="wechat", method = RequestMethod.GET)
	public void wechat(HttpServletRequest request,HttpServletResponse response,String signature,String timestamp,String nonce,String echostr) {
		String token = "XXXXXXXXXXXXXXXXXXXXXXXX";//The token in the configuration
		boolean flag = SignUtil.checkSignature(token, signature, timestamp, nonce);
		if(flag){
			try {
				//If the verification is successful, the content of the echostr parameter is returned as it is
				response.getWriter().print(echostr);
			} catch (Exception e) {
				e.printStackTrace ();
			}
		}
	}

	/**
	 * message processing
	 * @param response
	 * @param request
	 * @throws IOException
	 *@date Jul 9, 2016 at 11:20:31 AM
	 */
	@RequestMapping(value = "wechat", method = RequestMethod.POST)
	public void wechatPost(HttpServletResponse response,HttpServletRequest request) throws IOException {
		/*String respMessage = wechatService.do(request);*/ //TODO handles related business
		PrintWriter out = response.getWriter();
		//out.print(respMessage);
		out.close();
	}

}


Attachment: WeChat public account server configuration picture.




Guess you like

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