被浏览:6959
关注者:351
最佳回答:
获取UnionID的两种方式:前言:微信开发平台为开发者提供openid用来区分用户的唯一性,但是openId只是在独立的应用内是唯一的,如果开发者拥有多个移动应用、网站应用、和公众帐号(包括小程序),可通过 UnionID 来区分用户的唯一性,因为只要是同一个微信开放平台帐号下所有应用,用户的 UnionID 是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,UnionID是相同的。微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html
- 如果开发者帐号下存在同主体的公众号,并且该用户已经关注了该公众号。开发者可以直接通过 wx.login code2Session 获取到该用户 UnionID
- 从加密数据中获取UnionID
1. 已经关注公众号获取UnionIDps : 这里要注意的是微信开放平台如果没有绑定微信小程序,不可能获取到unionId,无论哪种方式
这种方式对于开发者来说是获取unionID最简单的方式,开发者可以直接通过 wx.login code2Session 获取到该用户 UnionID。以下代码只针对于Java语言来演示
package com.jinke.applets.common;import com.alibaba.fastjson.JSONObject;import com.jinke.utils.HttpUtil;import lombok.extern.Slf4j.Slf4j;import java.util.HashMap;import java.util.Map;/** * @author zsc * @date 2020/7/17 */@Slf4jpublic class AppletsWeChatUtil { // 登录凭证校验地址 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code"; // 小程序的appId以及appSecret private static final String appId = "xxxxxxxxxxxxx"; private static final String appSecret = "xxxxxxxxxxxxxxx"; /** * 小程序授权获取openID和unionID * @param code 前端通过wx.login获取的wxCode * @return */ public static Map<String, String> oauth2GetUnion(String code) { String requestUrl = GetPageAccessTokenUrl.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code); Map<String, String> result = new HashMap<>(); try { /** * HttpUtil工具类会在下方贴出,此处也可换成自己的写法,只要是get请求就可以 * 此处请求返回的json数据包为: * openidstring用户唯一标识 * session_keystring会话密钥 * unionidstring用户在开放平台的唯一标识符 * errcodenumber错误码 * errmsgstring错误信息 */ String response = HttpUtil.get(requestUrl); JSONObject jsonResult = JSONObject.parseObject(response); String openid = String.valueOf(jsonResult.get("openid")); // 若用户没有改小程序同主体公众号,则此处unionID为空 String unionid = String.valueOf(jsonResult.get("unionid")); result.put("openid", openid); result.put("unionid",unionid); } catch (Exception e) { log.info("授权获取unionid出现异常"); e.printStackTrace(); } return result; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
2. 解密数据获取UnionID
此方式针对于没有主体公众号或者做不到让用户都关注公众号的情况下获取UnionID.大致流程如下
- 前端js调取公开接口wx.getUserInfo获取encryptedData和iv
- 根据code2Session获取session_key和openid,如果有unionid直接返回
- 根据session_key,encryptedData和iv进行AES解密
package com.jinke.rusi.utils;import com.alibaba.fastjson.JSONObject;import com.jinke.utils.HttpUtil;import lombok.extern.slf4j.Slf4j;import java.util.HashMap;import java.util.Map;/** * @author zsc * @date 2020/7/17 */@Slf4jpublic class AppletsWeChatUtil { // 登录凭证校验地址 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code"; // 小程序的appId以及appSecret private static final String appId = "xxxxxxxxxxxxx"; private static final String appSecret = "xxxxxxxxxxxxxxx"; /** * 小程序授权 * @param code WxCode * @param encryptedData 加密数据 * @param iv 偏移量iv * @return */ public static Map<String, String> oauth2GetUnionId(String code,String encryptedData,String iv) { String requestUrl = GetPageAccessTokenUrl.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code); Map<String, String> result = new HashMap<>(); try { String response = HttpUtil.get(requestUrl); JSONObject jsonObject = JSONObject.parseObject(response); String openid = String.valueOf(jsonObject.get("openid")); // 获取解密所需的session_key String session_key = String.valueOf(jsonObject.get("session_key")); // 通过AES解密encryptedData 获取union_id,工具类见下方 String encryptedResult = AESUtil.decrypt(encryptedData, session_key, iv, "UTF-8"); /** * 此处解密之后数据包格式为: * openid string用户唯一标识 * nickName string 昵称 * gender string 性别 * city string城市 * province string 省份 * country string 国家 * avatarUrl string头像 * unionId string用户在开放平台的唯一标识符 * watermark JSON数据水印,包括appid,timestamp字段 为了校验数据的有效性 */ JSONObject parseObject = JSONObject.parseObject(encryptedResult); // ps:此处一定要注意解密的出来的字段名为驼峰命名的unionId,openId,并非直接授权的unionid String unionid = String.valueOf(parseObject.get("unionId")); result.put("openid", openid); result.put("unionid",unionid); } catch (Exception e) { log.info("授权获取unionid出现异常"); e.printStackTrace(); } return result; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
工具类及依赖
AESUtil:
package com.jinke.rusi.utils;import net.sf.json.JSONObject;import org.apache.commons.codec.binary.Base64;import org.bouncycastle.jce.provider.BouncyCastleProvider;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import java.io.UnsupportedEncodingException;import java.security.*;import java.security.spec.InvalidParameterSpecException;/** * @author zsc * @date 2020/07/17 * AES-128-CBC 加密方式 * AES-128-CBC可以自己定义“密钥”和“偏移量“。 * AES-128是jdk自动生成的“密钥”。 */public class AESUtil { static { Security.addProvider(new BouncyCastleProvider()); } /** * AES解密 * @param data 密文,被加密的数据 * @param key 秘钥 * @param iv 偏移量 * @param encodingFormat 解密后的结果需要进行的编码 * @return * @throws Exception */ public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception { //被加密的数据 byte[] dataByte = Base64.decodeBase64(data); //加密秘钥 byte[] keyByte = Base64.decodeBase64(key); //偏移量 byte[] ivByte = Base64.decodeBase64(iv); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); SecretKeySpec spec = new SecretKeySpec(keyByte, "AES"); AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); parameters.init(new IvParameterSpec(ivByte)); cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化 byte[] resultByte = cipher.doFinal(dataByte); if (null != resultByte && resultByte.length > 0) { String result = new String(resultByte, encodingFormat); return result; } return null; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidParameterSpecException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
HttpUtil:
package com.jinke.utils;import com.alibaba.fastjson.JSON;import org.apache.http.HttpEntity;import org.apache.http.StatusLine;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpRequestBase;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.*;public class HttpUtil { private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class); public static int DATA_JSON = 1; public static int DATA_FORM = 2; private static String JSON_CONTENT_TYPE = "application/json"; private static String CHARACTER = "UTF-8"; private static String CONTENT_TYPE_NAME = "Content-Type"; public static String get(String url) { return send(new HttpGet(url)); } public static String post(String url, Map<String, Object> param, Integer dataType) { return post(url, param, dataType, null); } public static String post(String url, Map<String, Object> param, Integer dataType, Map<String, String> headers) { HttpPost post = new HttpPost(url); if (dataType == DATA_FORM) { Iterator localIterator; Map.Entry<String, String> entries; if (headers != null) for (localIterator = headers.entrySet().iterator(); localIterator.hasNext(); ) { entries = (Map.Entry) localIterator.next(); post.setHeader((String) entries.getKey(), (String) entries.getValue()); } Object paramList = new ArrayList(); for (Map.Entry<String, Object> entry : param.entrySet()) { ((List) paramList).add(new BasicNameValuePair((String) entry.getKey(), entry.getValue().toString())); } try { post.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity((List) paramList)); } catch (UnsupportedEncodingException e) { LOGGER.info(e.getMessage()); } } else if (dataType.intValue() == DATA_JSON) { post.setHeader(CONTENT_TYPE_NAME, JSON_CONTENT_TYPE); post.setEntity(new StringEntity(JSON.toJSONString(param), CHARACTER)); } return send(post); } private static String send(HttpRequestBase request) { CloseableHttpClient client = org.apache.http.impl.client.HttpClients.createDefault(); String result = null; try { CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == 200) { result = EntityUtils.toString(entity); EntityUtils.consume(entity); } else { result = String.valueOf(status); } LOGGER.info("http response ------------" result); response.close(); } catch (IOException e) { LOGGER.info(e.getMessage()); } return result; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
AES加密依赖的包
这里需要注意的是,AES解密的时候需要用到javax.crypto.*包的类,在jdk的 jce.jar中提供,是jdk自带的库。如果是Maven项目,则需要在pom.xml文件中配置指定编译路径jce.jar如果配置路径麻烦,可以选择去maven或者gradle自行下载。Maven依赖:<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --><dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.50</version></dependency>Gradle依赖:// https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15oncompile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.50'
获赞:570
收藏:62
回答时间:2022-11-25 10:59:20