微信小程序Java登录流程要怎样实现,,,,,下面为各人介绍详细的开发流程。。。。


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{
}
}
});
}
复制代码
微信小程序端提倡登录请求,,,,,携带的参数主要有:
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//解密算法的向量
signature,//署名、 encryptedData ,//用户敏感信息、 iv //解密算法的向量:
这三个参数是用来解码用户敏感信息的,,,,,好比电话号码等信息。。。。
需要的数据主要有: skey ,,,,,用于标记用户的唯一性。。。。
/**
* 登陆接口
*/
@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)) {
//1、获取用户非敏感信息
data = mapper.readValue(rawData, RawData.class);
}
session = this.wxService.getUserService().getSessionInfo(code);
//获取到openid和sessionkey
openid = session.getOpenid();
sessionKey = session.getSessionKey();
logger.info("sessionkey========================================================="+sessionKey);
/* //2、获取用户手机号
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("获取用户信息失败");
}
//3、向数据库插入用户信息
String skey = insertUser(data, openid, phoneNumber);
//4、缓存openid, sessionKey, skey到redis
redisCache(openid, sessionKey, skey);
//5、把新的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 。。。。
虽然,,,,,若是你不想用 第三方的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;
}
复制代码
这个部分自己遇到了好多的坑,,,,,由于需要获取用户的手机号码,,,,,需要解密用户的信息。。。。
/**
* 获取用户板绑定的手机号
* @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中,,,,,返回给小程序端。。。。
小程序工具提供多类型商城/门店小程序制作,,,,,可视化编辑 1秒天生5步上线。。。。通过拖拽、拼接???榻峁剐〕绦蛏坛且趁,,,,,所看即所得,,,,,只需要美工就能做出细腻商城。。。。更多小程序市肆请审查:小程序市肆
KESION pp电子软件
KESION pp电子软件是海内领先的在线教育软件及私域社交电商软件服务提供商,,,,,恒久专注于为企业提供在线教育软件及社交电商SaaS平台解决方案。。。。
公司焦点产品云开店SaaS社交电商服务平台、在线教育SaaS服务平台、教育企业数字化SaaS云平台、企微营销助手、私有化自力安排品牌网校和在线教育咨询等。。。。KESION 一直通过手艺立异,,,,,提供产品和服务,,,,,助力企业向数字化转型,,,,,通过科技驱动商业刷新,,,,,让商业变得更智慧!
最近是不是各人都在痴迷谷歌开发的一个《猜画小歌》小程序呢,,,,,简直是蜜汁有趣,,,,,随便画画,,,,,谷歌人工智能就能猜到准确谜底。。。。那么下面为各人剖析这款小程序背后的原理。。。。...
接待各人前往腾讯云+社区,,,,,获取更多腾讯海量手艺实践干货哦~ 本文由腾讯视频云终端团队 揭晓于云+社区专栏 Demo 体验 升级微信到最新版本,,,,,发明页卡 = 小程序 = 搜索“腾讯视频云”...