First of all, “login”, “authorized”, “authorized login”, it means the same thing, don’t bother.

Before writing small program authorization login code, need to understand the difference between OpenID and UnionID, here is a brief introduction:

  1. Tencent has a “wechat · Open platform”, only enterprises can register accounts, which can be understood as the top account in the wechat system. Website address: https://open.weixin.qq.com
  2. In addition to this wechat open platform, there is another called “wechat public platform”, which can register four kinds of accounts, including service account, subscription account, small program, enterprise wechat. That is to say, the public number (service number and subscription number can be collectively known as the public number) accounts for an account, small programs also account for an account. Before binding to open platform, applets can only get the user’s OpenID for authorized login. Official website: https://mp.weixin.qq.com
  3. Small programs can be bound to the public account, the public account can be bound to the wechat open platform, small programs can also be bound to the wechat open platform. To put it simply, all public platform accounts need to be bound to the “open platform” to obtain the unionID, which is the most effective way to open all wechat public accounts under the same enterprise (official recommendation)
  4. More specific can be self-baidu…

First, the following is the small program login code:

  • Method 1: Call code2session interface through code to obtain message, including OpenID and session_key. If conditions are met, unionID can also be directly obtained

    • The conditions are as follows :(limitations exist)
    1. Official description UnionID access, if the developer account under the same subject of the public account, and the user has been concerned about the public account. The developer can directly obtain the UnionID of the user through wx.login + code2Session without user re-authorization.

    2. The developer account has a public account or mobile application of the same subject, and the user has been authorized to log in to the public account or mobile application. The user’s UnionID can also be obtained through code2Session.

 1/**
 2 * Author: huanglp
 3 * Date: 2018-11-28
 4 */
 5public class WeiXinUtils {
 6
 7    private static Logger log = LoggerFactory.getLogger(WeiXinUtils.class); 8 9 /** 10 * Through the code passed from the front end, call the small program login interface, get the message and return (including openID session_key, etc.) 11 * 12 * @param code 13 * @return
14     */
15    public static JSONObject login(String code) {
16        log.info("============== applet login method start ================");
17        WxMiniProperties properties = WeiXinPropertiesUtils.getWxMiniProperties();
18        String url = properties.getInterfaceUrl() + "/sns/jscode2session? appid="
19            + properties.getAppId() + "&secret=" + properties.getAppSecret() 
20            + "&js_code=" + code + "&grant_type=authorization_code"; 21 JSONObject message; RestTemplate = new RestTemplate(); RestTemplate = new RestTemplate(); 25 String response = restTemplate.getForObject(url, String.class); 26 message = JSON.parseObject(response); 27 } catch (Exception e) { 28 log.error("Wechat server request error", e);
29            message = new JSONObject();
30        }
31        log.info("The message:" + message.toString());
32        log.info("============== applet login method end ================");
33        returnmessage; 34 35 // Obtain openID session_key and other data. The following code is generally placed in the Service layerif (message.get("errcode") != null) {
37        //    throw new ValidationException(message.toString());
38        //}
39        //String openid = message.get("openid").toString();
40        //String sessionKey = message.get("session_key").toString(); 41 / /... 42 and 43} 44}Copy the code
  • – Add 1: WeiXinPropertiesUtils tool class
 1public class WeiXinPropertiesUtils {2 3 private static WxMiniProperties miniProperties; 6 private static WxProperties WxProperties; 7 8 private static voidinit() {9if(miniProperties == null) { 10 miniProperties = ContextLoader.getCurrentWebApplicationContext() 11 .getBean(WxMiniProperties.class); 12} 13if (wxProperties == null) {
14            wxProperties = ContextLoader.getCurrentWebApplicationContext()
15                .getBean(WxProperties.class);
16        }
17    }
18
19    public static WxMiniProperties getWxMiniProperties() {
20        init();
21        return miniProperties;
22    }
23
24    public static WxProperties getWxProperties() {
25        init();
26        returnwxProperties; 28 27}}Copy the code
  • – Addendum 2: WxMiniProperties configuration class
 1@Data
 2@Component
 3@ConfigurationProperties(prefix = "luwei.module.wx-mini")
 4public class WxMiniProperties {
 5
 6    private String appId;
 7    private String appSecret;
 8    private String interfaceUrl;
 9
10}
Copy the code

So far, the user’s OpenID and session_key can be obtained through code. However, if the conditions are not met, the unionID cannot be obtained even if the small program is bound to the wechat open platform. Therefore, this method is unstable, and it is recommended to obtain data through decryption.

  • Method 2: Obtain the unionID of the user through decryption
1/2 * * * through the encryptedData, sessionKey, iv declassified information, has a wealth of information users, 3 */ 4public static JSONObject decryptWxData(String encryptedData, String sessionKey, String iv) throws Exception { 5 log.info("============ applets login parsing data method start ==========");
 6    String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
 7    JSONObject userInfo = new JSONObject();
 8    if(null ! = result && result.length() > 0) { 9 userInfo = JSONObject.parseObject(result); 10 } 11 log.info("result: " + userInfo);
12    log.info("============ applet login parsing data method end ==========");
13    return userInfo;
14}
Copy the code
  • – Add 1: AesCbcUtil utility class, copy directly, need to add bouncyCastle dependency. BouncyCastle is an open source encryption and decryption solution available at www.bouncycastle.org/
1package com.luwei.common.utils; 2 3import org.bouncycastle.jce.provider.BouncyCastleProvider; 4 import org.apache.com mons. Codec, binary Base64; 5import javax.crypto.Cipher; 6import javax.crypto.spec.IvParameterSpec; 7import javax.crypto.spec.SecretKeySpec; 8import java.security.AlgorithmParameters; 9import java.security.Security; 10 11/** 12 * Updated by huanglp 13 * Date: 2018-11-28 14 */ 15public class AesCbcUtil { 16 17 static { 18 Security.addProvider(new BouncyCastleProvider()); 19} 20 21 /** 22 * AES decryption 23 * 24 * @param data // encrypted data 25 * @param key // encryption key 26 * @param IV // offset 27 * @param Public static String decrypt(String data, String key, String iv, String encoding) { 30 31 // org.apache.commons.codec.binary.Base64 32 byte[] dataByte = Base64.decodeBase64(data); 33 byte[] keyByte = Base64.decodeBase64(key); 34 byte[] ivByte = Base64.decodeBase64(iv); 35 36 try { 37 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
38            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
39            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); 40 parameters.init(new IvParameterSpec(ivByte)); 41 42 cipher.init(Cipher.DECRYPT_MODE, spec, parameters); Byte [] resultByte = cipher.dofinal (dataByte); // Initialize 43 byte[] resultByte = cipher.dofinal (dataByte); 44if(null ! = resultByte && resultByte.length > 0) { 45returnnew String(resultByte, encoding); 46} 47returnnull; 48 49 } catch (Exception e) { 50 e.printStackTrace(); 51} 52 of 53returnnull; 55 54}}Copy the code

The userInfo of type JSONObject has been obtained, including OpenID, UnionID, nickname, avatar and other data

Subsequently, the user information can be saved to the database, and then returned to the front end of a token, Shiro encapsulated a layer of the company, the code is as follows:

1... 2// get userId 3int userId = wxuser.getwxuserid (); 4shiroTokenService.afterLogout(userId); 5String uuid = UUID.randomUUID().toString(); 6String token = StringUtils.deleteAny(uuid,"-") + Long.toString(System.currentTimeMillis(), Character.MAX_RADIX);
7shiroTokenService.afterLogin(userId, token, null);
8return token;
Copy the code

Ii. The following is the authorization code of the official account (webpage) :

Web authorization is easier, and official documentation can be viewed

It is necessary to add riversoft related dependency packages and webpage authorization of the public account. Only by binding the public account to the open platform, the unionID and other user information can be obtained.

 1public static OpenUser webSiteLogin(String code, String state) {
 2    log.info("============ wechat official account (webpage) authorization begins ===========");
 3    WxProperties properties = WeiXinPropertiesUtils.getWxProperties(); 4 AppSetting appSetting = new AppSetting(properties.getAppId(), properties.getAppSecret()); 5 OpenOAuth2s openOAuth2s = OpenOAuth2s.with(appSetting); 6 AccessToken accessToken = openOAuth2s.getAccessToken(code); 7 8 9 / / get the user information OpenUser OpenUser = openOAuth2s. The userInfo (accessToken.. getAccessToken (), accessToken.. getOpenId ()); 10 log.info("============ wechat official account (webpage) authorization end ===========");
11    returnopenUser; 12 13 // Subsequent user information can be saved. 14 // In the last step, after the token is generated, the user needs to be redirected to the page 15 //return "redirect:" + state + "? token=" + token;
16}
Copy the code

The following is the summary of my experience and problems about wechat public number authorization and small program authorization, and I hope you can get a solution.


Lung peng

Guangzhou Reed Technology Java development team

Reed Technology – Guangzhou professional Internet software service company

Seize every detail, create every beauty

Follow our official account to learn more

Want to fight with us? Lagou search for “Reed Technology” or join us by sending your resume to [email protected]

Follow us, your comments and likes support us the most