网页抓取解密(小程序授权登录的代码前,需要了解清楚openid与unionid的区别)
优采云 发布时间: 2021-10-02 19:03网页抓取解密(小程序授权登录的代码前,需要了解清楚openid与unionid的区别)
首先,“登录”、“授权”、“授权登录”都是同一个意思,不用担心。
在编写小程序授权登录的代码之前,需要了解openid和unionid的区别。下面是一个简单的介绍:
腾讯有“微信·开放平台”。只有企业才能注册账号,可以理解为微信系统中的顶级账号。官网地址:除了这个微信开放平台,还有一个叫“微信公众平台”,可以注册服务号、订阅号、小程序、企业微信四种帐号。也就是说,公众号(服务号和订阅号可以统称为公众号)占用一个帐号,小程序也占用一个帐号。在绑定开放平台之前,小程序授权登录只能获取用户的openid。官网地址:小程序可以绑定公众号,公众号可以绑定微信开放平台,小程序也可以绑定微信开放平台。(好像有点绕)简单来说就是所有公众平台账号都需要绑定“开放平台”才能获得unionid。这是打通同一个公司下所有微信公众号最有效的方式(官方推荐),具体可以用百度...一、 以下是小程序登录代码:
官方说明如何获取UnionID,如果开发者账号下有同一主题的公众号,且用户已关注该公众号。开发者可以通过wx.login+code2Session直接获取用户的UnionID,无需用户重新授权。
开发者账号下存在同一主题的公众号或移动应用,且用户已被授权登录该公众号或移动应用。用户的UnionID也可以通过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 * 通过前端传过来的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}
复制代码
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}
复制代码
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}
复制代码
目前通过代码可以获取到用户的openid和session_key,但是如果不满足条件,即使小程序绑定微信开放平台也无法获取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}
复制代码
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;
复制代码
二、 以下为公众号(网页)授权码:
网页授权更简单,可以查看官方文档
需要添加riversoft相关依赖包,公众号网页授权,只需将公众号绑定到开放平台,即可获取unionid等用户信息。
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}
复制代码
以下是我整理的微信公众号授权和小程序授权的一些经验和问题的总结。我希望你能从他们那里找到解决办法。