小程序登陸、微信網頁受權(Java版)

首先呢,「登陸」、「受權」、「受權登陸」,是同樣的意思,不用糾結。html

寫小程序受權登陸的代碼前,須要瞭解清楚openid與unionid的區別,這裏再簡單介紹一下:前端

  1. 騰訊有個 「微信·開放平臺」,只有企業才能註冊帳號,可理解爲微信體系裏,最頂級的帳號。官網地址:https://open.weixin.qq.com
  2. 除了這個微信開放平臺,還有另外一個叫作 「微信公衆平臺」,可註冊四種帳號,包括服務號、訂閱號、小程序、企業微信。也就是說,公衆號(服務號和訂閱號可統稱爲公衆號)佔一個帳號,小程序也佔一個帳號。在沒有綁定開放平臺前,小程序受權登陸只能拿到用戶的openid。官網地址:https://mp.weixin.qq.com
  3. 小程序可綁定在公衆號下,公衆號能夠綁定在微信開放平臺下,小程序也能夠綁定在微信開放平臺下。(好像有點小繞)簡單點說,全部的公衆平臺帳號都須要綁定在 「開放平臺」 下,纔可得到的unionid,這是打通同個企業下全部微信公衆帳號的最有效方法(官方推薦)
  4. 更加具體的可自行百度…

1、如下爲小程序登陸的代碼:

  • 方式一:經過code調用code2session接口得到message,包含openid、session_key,知足條件的狀況下還能直接得到unionidjava

    • 條件以下:(存在侷限性)
    1. 官方說明UnionID獲取途徑,若是開發者賬號下存在同主體的公衆號,而且該用戶已經關注了該公衆號。開發者能夠直接經過 wx.login + code2Session 獲取到該用戶 UnionID,無須用戶再次受權。web

    2. 開發者賬號下存在同主體的公衆號或移動應用,而且該用戶已經受權登陸過該公衆號或移動應用。也可經過code2session獲取該用戶的 UnionID。數據庫

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     * 經過前端傳過來的code, 調用小程序登陸接口, 獲取到message並返回 (包含openid session_key等)
11     *
12     * @param code
13     * @return
14     */
15    public static JSONObject login(String code) {
16        log.info("==============小程序登陸方法開始================");
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;
22        try {
23            // RestTemplate是Spring封裝好的, 挺好用, 可作成單例模式
24            RestTemplate restTemplate = new RestTemplate();
25            String response = restTemplate.getForObject(url, String.class);
26            message = JSON.parseObject(response);
27        } catch (Exception e) {
28            log.error("微信服務器請求錯誤", e);
29            message = new JSONObject();
30        }
31        log.info("message:" + message.toString());
32        log.info("==============小程序登陸方法結束================");
33        return message;
34
35        // 後續, 可獲取openid session_key等數據, 如下代碼通常放在Service層
36        //if (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
43    }
44}
複製代碼
  • - 補充1: WeiXinPropertiesUtils工具類
1public class WeiXinPropertiesUtils {
 2
 3    // 微信小程序配置
 4    private static WxMiniProperties miniProperties;
 5    // 微信公衆號配置
 6    private static WxProperties wxProperties;
 7
 8    private static void init() {
 9        if (miniProperties == null) {
10            miniProperties = ContextLoader.getCurrentWebApplicationContext()
11                .getBean(WxMiniProperties.class);
12        }
13        if (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        return wxProperties;
27    }
28}
複製代碼
  • - 補充2: WxMiniProperties配置類
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}
複製代碼

到此已能經過code獲取到用戶的openid和session_key,但若不知足條件,即便將小程序綁定到微信開放平臺上,也獲取不到unionid,因此此方式不穩定,推薦使用解密的方式獲取數據。apache

  • 方式二:經過解密的方式獲取用戶unionid
1/**
 2 * 經過encryptedData,sessionKey,iv得到解密信息, 擁有用戶豐富的信息, 包含openid,unionid,暱稱等
 3 */
 4public static JSONObject decryptWxData(String encryptedData, String sessionKey, String iv) throws Exception {
 5    log.info("============小程序登陸解析數據方法開始==========");
 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("============小程序登陸解析數據方法結束==========");
13    return userInfo;
14}
複製代碼
  • - 補充1: AesCbcUtil工具類,直接複製便可,須要添加bouncycastle依賴。BouncyCastle是一個開源的加解密解決方案,官網可查看www.bouncycastle.org/
1package com.luwei.common.utils;
 2
 3import org.bouncycastle.jce.provider.BouncyCastleProvider;
 4import org.apache.commons.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解密
23     *
24     * @param data     //被加密的數據
25     * @param key      //加密祕鑰
26     * @param iv       //偏移量
27     * @param encoding //解密後的結果須要進行的編碼
28     */
29    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);// 初始化
43            byte[] resultByte = cipher.doFinal(dataByte);
44            if (null != resultByte && resultByte.length > 0) {
45                return new String(resultByte, encoding);
46            }
47            return null;
48
49        } catch (Exception e) {
50            e.printStackTrace();
51        }
52
53        return null;
54    }
55}
複製代碼

到此已經獲取到 JSONObject類型的 userInfo,包含openid,unionid,暱稱,頭像等數據小程序

後續能夠將用戶信息保存到數據庫,再返回給前端一個token便可,shiro通過公司封裝了一層,代碼以下:微信小程序

1...
2// 得到用戶ID
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;
複製代碼

2、如下爲公衆號(網頁)受權的代碼:

網頁受權更加簡單,可查看 官方文檔api

需添加 riversoft 相關依賴包,公衆號網頁受權,只須要將公衆號綁定了開放平臺,就能獲取到unionid及其餘用戶信息。bash

1public static OpenUser webSiteLogin(String code, String state) {
 2    log.info("============微信公衆號(網頁)受權開始===========");
 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    OpenUser openUser = openOAuth2s.userInfo(accessToken.getAccessToken(), accessToken.getOpenId());
10    log.info("============微信公衆號(網頁)受權結束===========");
11    return openUser;
12
13    // 後續, 可將用戶信息保存
14    // 最後一步, 生成token後, 需重定向回頁面
15    //return "redirect:" + state + "?token=" + token;
16}
複製代碼

如下就是本人整理的關於微信公衆號受權和小程序受權的一些經驗和問題彙總,但願你們可以從中得到解決方法。


隆鵬

廣州蘆葦科技Java開發團隊

蘆葦科技-廣州專業互聯網軟件服務公司

抓住每一處細節 ,創造每個美好

關注咱們的公衆號,瞭解更多

想和咱們一塊兒奮鬥嗎?lagou搜索「 蘆葦科技 」或者投放簡歷到 server@talkmoney.cn 加入咱們吧

關注咱們,你的評論和點贊對咱們最大的支持

相關文章
相關標籤/搜索