文章有不當之處,歡迎指正,若是喜歡微信閱讀,你也能夠關注個人微信公衆號:
好好學java
,獲取優質學習資源。html
doLogin:function(callback = () =>{}){
let that = this;
wx.login({
success:function(loginRes){
if(loginRes){
//獲取用戶信息
wx.getUserInfo({
withCredentials:true,//非必填 默認爲true
success:function(infoRes){
console.log(infoRes,'>>>');
//請求服務端的登陸接口
wx.request({
url: api.loginUrl,
data:{
code:loginRes.code,//臨時登陸憑證
rawData:infoRes.rawData,//用戶非敏感信息
signature:infoRes.signature,//簽名
encrypteData:infoRes.encryptedData,//用戶敏感信息
iv:infoRes.iv//解密算法的向量
},
success:function(res){
console.log('login success');
res = res.data;
if(res.result==0){
that.globalData.userInfo = res.userInfo;
wx.setStorageSync('userInfo',JSON.stringify(res.userInfo));
wx.setStorageSync('loginFlag',res.skey);
console.log("skey="+res.skey);
callback();
}else{
that.showInfo('res.errmsg');
}
},
fail:function(error){
//調用服務端登陸接口失敗
// that.showInfo('調用接口失敗');
console.log(error);
}
});
}
});
}else{
}
}
});
}
複製代碼
微信小程序端發起登陸請求,攜帶的參數主要有:java
code:loginRes.code,//臨時登陸憑證
rawData:infoRes.rawData,//用戶非敏感信息
signature:infoRes.signature,//簽名
encrypteData:infoRes.encryptedData,//用戶敏感信息
iv:infoRes.iv//解密算法的向量
複製代碼
參數解釋: code:loginRes.code,//臨時登陸憑證:必傳,經過code來換取後臺的
sessionKey
和openId
rawData:infoRes.rawData,//用戶非敏感信息 signature:infoRes.signature,//簽名 encrypteData:infoRes.encryptedData,//用戶敏感信息 iv:infoRes.iv//解密算法的向量mysql
signature,//簽名、encryptedData,//用戶敏感信息、iv//解密算法的向量:git
這三個參數是用來解碼用戶敏感信息的,好比電話號碼等信息。github
須要的數據主要有:skey
,用於標誌用戶的惟一性。redis
/**
* 登錄接口
*/
@RequestMapping("/login")
@ApiResponses({
@ApiResponse(code = 404, message = "服務器未找到資源"),
@ApiResponse(code = 200, message = "請求成功"),
@ApiResponse(code = 500, message = "服務器錯誤"),
@ApiResponse(code = 401, message = "沒有訪問權限"),
@ApiResponse(code = 403, message = "服務器拒絕訪問"),
})
@ApiOperation(value = "小程序登陸", httpMethod = "POST", notes = "小程序登陸")
public ResponseEntity<LoginDataResult> login(
@ApiParam(required = true, value = "臨時登陸憑證code", name = "code") String code,
@ApiParam(required = true, value = "用戶非敏感信息", name = "rawData")
@RequestParam(value = "rawData", required = true) String rawData,
@ApiParam(required = true, value = "簽名", name = "signature")
@RequestParam(value = "signature", required = true) String signature,
@ApiParam(required = true, value = "用戶敏感信息", name = "encrypteData")
@RequestParam(value = "encrypteData", required = true) String encrypteData,
@ApiParam(required = true, value = "解密算法的向量", name = "iv")
@RequestParam(value = "iv", required = true) String iv
) {
ObjectMapper mapper = new ObjectMapper();
logger.info("signature============================================================="+signature);
logger.info("encrypteData=========================================================="+encrypteData);
logger.info("iv========================================================================"+iv);
RawData data = null;
WxMaJscode2SessionResult session = null;
String openid = null;
String sessionKey = null;
String phoneNumber = null;
try {
if (rawData != null && !"".equals(rawData)) {
//一、獲取用戶非敏感信息
data = mapper.readValue(rawData, RawData.class);
}
session = this.wxService.getUserService().getSessionInfo(code);
//獲取到openid和sessionkey
openid = session.getOpenid();
sessionKey = session.getSessionKey();
logger.info("sessionkey========================================================="+sessionKey);
/* //二、獲取用戶手機號
phoneNumber = phone(code, signature, rawData, encrypteData, iv);
logger.info("phoneNumber========================================="+phoneNumber);
*/
} catch (IOException e) {
e.printStackTrace();
logger.info("獲取用戶信息失敗");
LoginDataResult loginDataResult = new LoginDataResult();
loginDataResult.setCode("2");
loginDataResult.setMsg("請求失敗");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(loginDataResult);
} catch (WxErrorException e) {
e.printStackTrace();
logger.info("獲取用戶信息失敗");
}
//三、向數據庫插入用戶信息
String skey = insertUser(data, openid, phoneNumber);
//四、緩存openid, sessionKey, skey到redis
redisCache(openid, sessionKey, skey);
//五、把新的skey返回給小程序
LoginDataResult loginDataResult = new LoginDataResult();
loginDataResult.setSkey(skey);
loginDataResult.setCode("1");
loginDataResult.setMsg("請求成功");
return ResponseEntity.status(HttpStatus.OK).body(loginDataResult);
}
/**
* 緩存openid,sessionKey,skey等信息
* @param openid 小程序用戶惟一標誌
* @param sessionKey 小程序會話標誌
* @param skey 後臺生成的用戶惟一標誌,會話管理
*/
private void redisCache(String openid, String sessionKey, String skey) {
//根據openid查詢skey是否存在
String skey_redis = jedisClient.hget("WEXIN_USER_OPENID_SKEY", openid);
if (StringUtils.isNotBlank(skey_redis)) {
//存在 刪除 skey 從新生成skey 將skey返回
jedisClient.hdel("WEXIN_USER_OPENID_SKEY", openid);
jedisClient.hdel("WEIXIN_USER_SKEY_OPENID", skey_redis);
jedisClient.hdel("WEIXIN_USER_SKEY_SESSIONKEY", skey_redis);
}
// 緩存一份新的
jedisClient.hset("WEXIN_USER_OPENID_SKEY", openid, skey);
jedisClient.expire("WEXIN_USER_OPENID_SKEY",432000);//設置5天過時
jedisClient.hset("WEIXIN_USER_SKEY_OPENID", skey, openid);
jedisClient.expire("WEIXIN_USER_SKEY_OPENID",432000);//設置5天過時
jedisClient.hset("WEIXIN_USER_SKEY_SESSIONKEY", skey, sessionKey);
jedisClient.expire("WEIXIN_USER_SKEY_SESSIONKEY",432000);//設置5天過時
}
/**
* 將用戶信息插入到數據庫
* @param data 用戶信息
* @param openid
* @param phoneNumber 手機號
* @return
*/
private String insertUser(RawData data, String openid, String phoneNumber) {
//判斷用戶數據庫是否存在,不存在,入庫。
Member user = userService.selectUserByOpenid(openid);
//uuid生成惟一key
String skey = UUID.randomUUID().toString();
if (user == null) {
//入庫
user = new Member();
user.setId(skey);
user.setCountry(data.getCountry());
user.setCreatedate(new Date());
user.setDf(1);
user.setGender(data.getGender().equals("1") ? 1 : 2);//1爲男,2爲女
user.setHeadimg(data.getAvatarUrl());
user.setNickname(data.getNickName());
user.setOpenid(openid);
user.setCitycode(data.getCity());
user.setProvincecode(data.getProvince());
user.setMobileno(phoneNumber);
//插入到數據庫
userService.insertUser(user);
} else {
//已存在
logger.info("用戶openid已存在,不須要插入");
return user.getId();//返回用戶惟一標誌skey
}
return skey;
}
/**
* 獲取用戶板綁定的手機號
* @param sessionKey 小程序session
* @param signature 簽名
* @param rawData 用戶信息
* @param encryptedData 小程序加密數據
* @param iv 小程序向量
* @return
*/
@ApiOperation(value = "用戶手機號獲取", httpMethod = "GET", notes = "用戶手機號獲取")
public String phone(String sessionKey, String signature, String rawData, String encryptedData, String iv) {
String phoneNumber = null;
try {
byte[] bytes = WxMiniappUtils.decrypt(Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv), Base64.decodeBase64(encryptedData));
String phone = new String(bytes, "UTF8");
logger.info("phone====================================="+phone);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
複製代碼
下面對上面代碼進行分析:算法
session = this.wxService.getUserService().getSessionInfo(code);
//獲取到openid和sessionkey
openid = session.getOpenid();
sessionKey = session.getSessionKey();
複製代碼
這段代碼是否是十分的簡潔,這裏用到了一個第三方的sdk(weixin-java-tools),經過這個sdk能夠很是簡便的獲取到openid和sessionKey,具體的demo。sql
固然,若是你不想用第三方的sdk
,也能夠本身實現,實現代碼以下:數據庫
public static JSONObject getSessionKeyOrOpenId(String code){
//微信端登陸code
String wxCode = code;
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
Map<String,String> requestUrlParam = new HashMap<String, String>( );
requestUrlParam.put( "appid","你的小程序appId" );//小程序appId
requestUrlParam.put( "secret","你的小程序appSecret" );
requestUrlParam.put( "js_code",wxCode );//小程序端返回的code
requestUrlParam.put( "grant_type","authorization_code" );//默認參數
//發送post請求讀取調用微信接口獲取openid用戶惟一標識
JSONObject jsonObject = JSON.parseObject( UrlUtil.sendPost( requestUrl,requestUrlParam ));
return jsonObject;
}
複製代碼
這個部分本身遇到了好多的坑,因爲須要獲取用戶的手機號碼,須要解密用戶的信息。json
/**
* 獲取用戶板綁定的手機號
* @param sessionKey 小程序session
* @param signature 簽名
* @param rawData 用戶信息
* @param encryptedData 小程序加密數據
* @param iv 小程序向量
* @return
*/
@ApiOperation(value = "用戶手機號獲取", httpMethod = "GET", notes = "用戶手機號獲取")
public String phone(String sessionKey, String signature, String rawData, String encryptedData, String iv) {
String phoneNumber = null;
try {
byte[] bytes = WxMiniappUtils.decrypt(Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv), Base64.decodeBase64(encryptedData));
String phone = new String(bytes, "UTF8");
logger.info("phone====================================="+phone);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
複製代碼
這裏調用了WxMiniappUtils.decrypt
這個工具類,工具類以下:
/**
* 解密用戶手機號算法
* @param sessionkey 小程序登陸sessionKey
* @param iv 向量
* @param encryptedData
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static byte[] decrypt(byte[] sessionkey, byte[] iv, byte[] encryptedData)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(sessionkey, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return cipher.doFinal(encryptedData);
}
複製代碼
這裏用到的Cipher
類是 javax.crypto
的類。
可是這裏使用這個decrypt
工具類的時候,遇到了好多的問題。
第一:AES解密是報錯javax.crypto.BadPaddingException: pad block corrupted
這個問題是因爲,工具類使用了Cipher.getInstance("AES/CBC/PKCS5Padding")
。
解決:Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding");。
第二:java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 這個問題是因爲,解碼出來的iv不是16位,好像是15位,這個爲何我也不太清楚。
解決:這個怎麼解決,本身也沒有找到方法,若是有大神解決,望告知!
個人解決方法:其實我發現這個問題並非這個工具類的問題,我折騰了一天發現,這個工具類並非不可以解碼手機號,有的是能夠的,有的解析不到手機號,只有普通的信息,因此我以爲,這個多是微信用戶註冊的時候,是否是用手機號註冊的,因此會出現有些可以解析,有的不能解析。若是有大神有其餘方法,望告知!
{"phoneNumber":"13880684012","purePhoneNumber":"13880684012","countryCode":"86","watermark":{"timestamp":1519460296,"appid":"wx6ede2086ee29a89f"}}
複製代碼
若是解析到了這樣的json數據,說明是成功了的。
public class AES {
public static final AES instance = new AES();
public static boolean initialized = false;
/**
* AES解密
* @param content 密文
* @return
* @throws InvalidAlgorithmParameterException
* @throws NoSuchProviderException
*/
public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
initialize();
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
Key sKeySpec = new SecretKeySpec(keyByte, "AES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
byte[] result = cipher.doFinal(content);
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void initialize(){
if (initialized) return;
Security.addProvider(new BouncyCastleProvider());
initialized = true;
}
//生成iv
public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(iv));
return params;
}
}
複製代碼
這個也會有上面的問題,有時候會解析失敗!具體方法,還在摸索中,有大神知道方法和原有,望告知!
WxMaPhoneNumberInfo phoneNoInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
phoneNumber = phoneNoInfo.getPurePhoneNumber();
複製代碼
這個也會有上面的問題出現,有時候會解析失敗!
1.小程序端發起請求並攜帶主要參數
2.java後臺接到/login請求後,根據code去調用微信接口獲取用戶惟一標識openid和sessionKey
3.根據openid查詢mysql數據庫,判斷該用戶是否存在,若是不存在將用戶非敏感信息和其餘初始化數據存入到數據庫中,若是已存在,不操做
4.根據openid查詢redis數據庫,判斷openid對應的skey是否存在,若是存在則刪除原來老的skey以及對應的openid和sessionKey
5.經過uuid生成惟一的skey,用openid作鍵,skey作值,存入到redis中
6.而後把skey作鍵,openid和sessionKey的json串作值也從新存入到redis中
7.根據解密算法,參數有encryptedData、sessionKey和iv,獲取用戶信息userInfo,若是userInfo字段不知足須要,可經過userInfo.put( "balance",user.getUbalance() );添加所須要的字段和值
8.將微信小程序須要的數據封裝到map中,返回給小程序端。