1. WeChat applet <br />Step 1: Call wx.login to get the code document address Step 2: Determine whether the user authorizes to read the user information document address Step 3: Call wx.getUserInfo to read the user data document address Step 4: Since the mini program background authorized domain name cannot authorize the WeChat domain name, we can only call the WeChat server through our own server to obtain user information. Therefore, we will pass the encryptedData and iv obtained by wx.login to get code and wx.getUserInfo to the background through wx.request request
Data returned by the server:
Mini Program Code:
//Calling the login interface to get code wx.login({ success: function (res) { wx.getSetting({ success(setRes) { // Determines whether authorized if (!setRes.authSetting['scope.userInfo']) { // Authorize access to wx.authorize({ scope: 'scope.userInfo', success() { //Get user information wx.getUserInfo({ lang: "zh_CN", success: function (userRes) { //Stack network request wx.request({ url: config.loginWXUrl, data: { code: res.code, encryptedData: userRes.encryptedData, iv: userRes.iv }, header: { "Content-Type": "application/x-www-form-urlencoded" }, method: 'POST', // Server-side retrieval success: function (result) { var data = result.data.result; data.expireTime = nowDate + EXPIRETIME; wx.setStorageSync("userInfo", data); userInfo = data; } }) } }) } } }) } else { //Get user information wx.getUserInfo({ lang: "zh_CN", success: function (userRes) { //Stack network request wx.request({ url: config.loginWXUrl, data: { code: res.code, encryptedData: userRes.encryptedData, iv: userRes.iv }, header: { "Content-Type": "application/x-www-form-urlencoded" }, method: 'POST', success: function (result) { var data = result.data.result; data.expireTime = nowDate + EXPIRETIME; wx.setStorageSync("userInfo", data); userInfo = data; } }) } } }) } } } }) } } }) } }) 2. Java server
Obtain openid and decode user information code according to code
The required jar package
<dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-core</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk16</artifactId> <version>1.46</version> </dependency>
/** * Get WeChat applet information * @author zhy */ public class WXAppletUserInfo { private static Logger log = Logger.getLogger(WXAppletUserInfo.class); /** * Get WeChat applet session_key and openid * * @author zhy * @param code Call the code returned by WeChat login * @return */ public static JSONObject getSessionKeyOropenid(String code){ //WeChat login code value String wxCode = code; ResourceBundle resource = ResourceBundle.getBundle("weixin"); //Read the property file String requestUrl = resource.getString("url"); //Request address https://api.weixin.qq.com/sns/jscode2session Map<String,String> requestUrlParam = new HashMap<String,String>(); requestUrlParam.put("appid", resource.getString("appId")); //AppId in the developer settings requestUrlParam.put("secret", resource.getString("appSecret")); //appSecret requestUrlParam.put("js_code", wxCode); //The code returned by the applet call wx.login requestUrlParam.put("grant_type", "authorization_code"); //Default parameters//Send post request to read and call WeChat https://api.weixin.qq.com/sns/jscode2session interface to obtain the openid user unique identifier JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(requestUrl, requestUrlParam)); return jsonObject; } /** * Decrypt user sensitive data to obtain user information* * @author zhy * @param sessionKey The key for encrypted signature of data* @param encryptedData Encrypted data including sensitive data* @param iv The initial vector of the encryption algorithm* @return */ public static JSONObject getUserInfo(String encryptedData,String sessionKey,String iv){ // Encrypted data byte[] dataByte = Base64.decode(encryptedData); // Encrypted key byte[] keyByte = Base64.decode(sessionKey); // Offset byte[] ivByte = Base64.decode(iv); try { // If the key is less than 16 bits, then make up for it. The content in this if is very important int base = 16; if (keyByte.length % base != 0) { int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0); byte[] temp = new byte[groups * base]; Arrays.fill(temp, (byte) 0); System.arraycopy(keyByte, 0, temp, 0, keyByte.length); keyByte = temp; } // Initialize Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC"); SecretKeySpec spec = new SecretKeySpec(keyByte, "AES"); AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); parameters.init(new IvParameterSpec(ivByte)); cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// Initialize byte[] resultByte = cipher.doFinal(dataByte); if (null != resultByte && resultByte.length > 0) { String result = new String(resultByte, "UTF-8"); return JSON.parseObject(result); } } catch (NoSuchAlgorithmException e) { log.error(e.getMessage(), e); } catch (NoSuchPaddingException e) { log.error(e.getMessage(), e); } catch (InvalidParameterSpecException e) { log.error(e.getMessage(), e); } catch (IllegalBlockSizeException e) { log.error(e.getMessage(), e); } catch (BadPaddingException e) { log.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } catch (InvalidKeyException e) { log.error(e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { log.error(e.getMessage(), e); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); } return null; } } Code to send the request
/** * Send a request to the specified URL for POST method* * @param url The URL for sending the request * @param param Request parameter* @return The response result of the remote resource represented by the name*/ ublic static String sendPost(String url, Map<String, ?> paramMap) { PrintWriter out = null; BufferedReader in = null; String result = ""; String param = ""; Iterator<String> it = paramMap.keySet().iterator(); while(it.hasNext()) { String key = it.next(); param += key + "=" + paramMap.get(key) + "&"; } try { URL realUrl = new URL(url); // Open the connection between URLConnection conn = realUrl.openConnection(); // Set the general request attribute conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Accept-Charset", "utf-8"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // To send a POST request, you must set the following two lines conn.setDoOutput(true); conn.setDoInput(true); // Get the output stream corresponding to the URLConnection object out = new PrintWriter(conn.getOutputStream()); // Send the request parameter out.print(param); // Buffering out.flush() of the flush output stream; // Define the BufferedReader input stream to read the URL response in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { log.error(e.getMessage(), e); } //Use finally blocks to close the output stream and input stream finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.