Receive news for WeChat public account development

1. Register WeChat public subscription account

2. Server configuration:

URL (server address): rest/portal/getWeixinTokenToken

(token): XXX

EncodingAESKey (message encryption and decryption key): VzfRmFPyc7BNm84OzNHIY5EwfTkbGmgodF58OW0ZouW

Message encryption and decryption mode: plaintext mode

  3. The WeChat official account sends a message to the server, first accesses the get method to verify the token, and then accesses the post method to push the message to the server
 
 
 
 


   URL: written in Java, deployed to the server

  The first step is to access the get method to verify the token

 

import java.io.IOException;
import java.io.PrintWriter;
@Path("/getWeixinToken")
	@GET
	@Description("WeChat token verification")
	public void listSchoolHotMessageByPage(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
		String signature = request.getParameter("signature");  
        // timestamp  
        String timestamp = request.getParameter("timestamp");  
        // random number  
        String nonce = request.getParameter("nonce");  
        // random string  
        String echostr = request.getParameter("echostr");  
  
        PrintWriter out = response.getWriter();  
        // Verify the request by checking the signature. If the verification is successful, the echostr will be returned as it is, indicating that the access is successful, otherwise the access fails.  
        if (WeiXinSignUtil.checkSignature(signature, timestamp, nonce)) {  
            out.print(echostr);  
        }  
        out.close();  
        out = null;  
	}

 

package com.mashang.xlb.modules.portalmanage.util;

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

public class WeiXinSignUtil {
	// Consistent with the Token in the interface configuration information
	private static String token = "weixinCourse";

	/**
	 * Verify signature
	 *
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(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
	 */
	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
	 */
	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. Access the post method and send the message to the server:

 

@Path("/getWeixinToken")
	@POST
	@Description("WeChat token verification")
	@Consumes(MediaType.TEXT_XML)
	public void getWeixinTokenReceiveMsg(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException, IllegalArgumentException, IllegalAccessException, DOMException {
        WeiXinReceiveMsgDTO wxrmDto = parseXml(request);
        LogUtil.debug(log, wxrmDto.toString());
        response.getWriter().write("成功!");  
	}

	private WeiXinReceiveMsgDTO parseXml(HttpServletRequest request) throws IllegalArgumentException, IllegalAccessException, DOMException{
		WeiXinReceiveMsgDTO wxrmDto = new WeiXinReceiveMsgDTO();
		try {
			InputStream is = request.getInputStream();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
			DocumentBuilder db = dbf.newDocumentBuilder();   
			Document document = db.parse(is);
			NodeList employees = document.getChildNodes();   
			for (int i = 0; i < employees.getLength(); i++) {   
				Node employee = employees.item(i);   
				NodeList employeeInfo = employee.getChildNodes();   
				for (int j = 0; j < employeeInfo.getLength(); j++) {   
					Node node = employeeInfo.item(j);   
					NodeList employeeMeta = node.getChildNodes();   
					for (int k = 0; k < employeeMeta.getLength(); k++) {   
						this.setOjectFieldValue(wxrmDto,node.getNodeName(),employeeMeta.item(k).getTextContent());
					}   
				}   
			}   
			
		} catch (IOException | ParserConfigurationException | SAXException e) {
			e.printStackTrace ();
		}
		return wxrmDto;
	}
	
	/**
	 * Assign values ​​to object properties
	 * @param obj object
	 * @param name needs to assign attribute name
	 * @param value required assignment
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 */
	private void setOjectFieldValue(Object obj, String name , String value){
		try {
			Field[] flds = obj.getClass().getDeclaredFields();
			for (int k2 = 0; k2 < flds.length; k2++) {
				String foeldName = flds[k2].getName().replaceFirst(flds[k2].getName().substring(0, 1), flds[k2].getName().substring(0, 1).toUpperCase());
				if(foeldName.equals(name)){
					//The essential. . . Accessible private variables  
					flds[k2].setAccessible(true);
					//assign the property
					flds[k2].set(obj, value);
				}
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace ();
		}
	}
 

 

 

 

Guess you like

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