前言导读:第一次写小程序的时候,踩过不少坑,所以在这写出来。第一次写博客,写的不好,请见谅
我们在小程序拉起登陆的时候,要去获取个人信息的允许。小程序代码:
wx.login({ //这里是使用微信的登陆,去获取微信给予的code
success(res) {
var code = res.code;
if (code) {
wx.getUserInfo({ //这里是使用个微信小程序的接口,去拉取用户信息。获取微信给的三个参数
success(res) {
// 请求第三方接口
mineModel.getLogin(res.encryptedData, res.iv, code) // 这个是去后台,解析参数,获取用户信息
.then(res => {
console.log('请求第三方接口', res)
that.setData({
userInfo: res
})
wx.setStorageSync('userInfos', res)
app.globalData.userInfo = that.data.userInfo
wx.navigateBack()
})
},
fail() {
console.log('获取用户信息失败')
}
})
} else {
console.log('获取用户登录态失败!' + r.errMsg)
}
},
fail() {
console.log('登陆失败')
}
})
####################
// 登陆
getLogin(encryptedData, iv, code){
return this.request({
url: '', //这里写自己的后台接口地址
data: {
encryptedData: encryptedData,
iv: iv,
code: code
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
})
}
2. 后台代码
使用的工具类:
用于解密的:
package com.redis.util;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
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 org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class AesUtil {
static {
//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
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 {
// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
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;
}
}
第二个用户去微信拉取加密的用户信息:
public Map<String,Object> decodeUserInfo(HttpServletRequest request){
String wxspAppid = ""; //这里填写的是微信小程序给予的AppID(小程序ID)
String wxspSecret = ""; //这里填写的是小程序的密钥,如果忘记了可以重置
String grant_type = "authorization_code"; // 这个是类型,固定的
// 如果不清楚,可以去小程序的官网上看下参数说明
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + request.getParameter("code") + "&grant_type=authorization_code" ; //这个是去微信那边请求数据过来
HttpURLConnection http = null;
InputStream is = null;
Map<String, Object> map = new HashMap<String, Object>();
URL urlGet;
try {
urlGet = new URL(url);
http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.setConnectTimeout(15000);
http.setReadTimeout(15000);
http.connect();
is = http.getInputStream();
int size = http.getContentLength();
byte[] jsonBytes = new byte[size];
int nIdx = 0;
int nTotalLen = jsonBytes.length;
int nReadLen = 0;
while (nIdx < nTotalLen) {
nReadLen = is.read(jsonBytes, nIdx, nTotalLen - nIdx);
if (nReadLen > 0) {
nIdx = nIdx + nReadLen;
} else {
break;
}
}
String message = new String(jsonBytes, "UTF-8");
com.alibaba.fastjson.JSONObject messageJson = JSON.parseObject(message); // 这里把请求过来的数据传成JSONObject的数据
String session_key = messageJson.getString("session_key");//拿出来session_key
String result = AesUtil.decrypt(request.getParameter("encryptedData"), messageJson.getString("session_key"), request.getParameter("iv"), "UTF-8");//进行解密
if (null != result && result.length() > 0) {
map.put("status", 1);
map.put("msg", "解密成功");
//这里解密成功后,就可以做自己的项目逻辑
}else {
map.put("status", 0);
map.put("msg", "解密失败");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
3. 好了。到这里我们的小程序登陆就告一段落了。