参考文档:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
①小程序端wx.login获取code
wx.login({
success(res) {
if (res.code) {
// 发起网络请求
wx.request({
url: 'https://test.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
②调用java后台获取session_key和openid
/**
* 获取openid和sessionKey方法
* @param code
* @return
*/
private JSONObject getSessionKeyOrOpenId(String code){
String tokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
tokenUrl = tokenUrl.replace("APPID",miniAppId).replace("SECRET",miniAppsecret).replace("JSCODE", code);
String resultToken = restTemplateUtil.doGet(tokenUrl).getBody();
JSONObject jsonObject = JSONUtil.parseObj(resultToken);
return jsonObject;
}
③根据前端传过来的sessionKey解密手机号做绑定或登录操作
/**
* 微信小程序登录
* @param miniLoginDto
* @return
*/
@PostMapping("/miniLogin")
public Map<String, Object> miniLogin(@RequestBody MiniLoginDto miniLoginDto){
Map<String, Object> reuslt = new HashMap();
// 1.解析加密数据
String phoneNumber = null;
JSONObject userencryptedData = AES.wxDecrypt(miniLoginDto.getEncryptedData(),miniLoginDto.getSessionKey(), miniLoginDto.getIv());
if (StringUtils.isNotBlank((String) userencryptedData.get("phoneNumber"))){
phoneNumber = (String) userencryptedData.get("phoneNumber");
}
// 2.自己的登录 逻辑
return reuslt ;
}
注意:
可以将②和③放在一起,我这里没有成功,获取的sessionKey解密手机号一直报错,所有分三步来完成
pom
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.59</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.4.5</version>
</dependency>
用到的工具类:JSONUtil
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
/**
* @author xiaoqiang
* @Description 参考博客找不到了--------------
* @date 2019/5/7 15:44
*/
public class AES {
// 算法名
public static final String KEY_NAME = "AES";
// 加解密算法/模式/填充方式
// ECB模式只用密钥即可对数据进行加密解密,CBC模式需要添加一个iv
public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
/**
* 微信 数据解密<br/>
* 对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充<br/>
* 对称解密的目标密文:encrypted=Base64_Decode(encryptData)<br/>
* 对称解密秘钥:key = Base64_Decode(session_key),aeskey是16字节<br/>
* 对称解密算法初始向量:iv = Base64_Decode(iv),同样是16字节<br/>
*
* @param encrypted 目标密文
* @param session_key 会话ID
* @param iv 加密算法的初始向量
*/
public static JSONObject wxDecrypt(String encrypted, String session_key, String iv) {
String json = null;
byte[] encrypted64 = Base64.decodeBase64(encrypted);
byte[] key64 = Base64.decodeBase64(session_key);
byte[] iv64 = Base64.decodeBase64(iv);
byte[] data;
try {
init();
json = new String(decrypt(encrypted64, key64, generateIV(iv64)));
} catch (Exception e) {
System.out.println("解密微信手机号失败:" + e.getMessage());
}
return JSONUtil.parseObj(json);
}
/**
* 初始化密钥
*/
public static void init() throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyGenerator.getInstance(KEY_NAME).init(128);
}
/**
* 生成iv
*/
public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
// iv 为一个 16 字节的数组,这里采用和 iOS 端一样的构造方法,数据全为0
// Arrays.fill(iv, (byte) 0x00);
AlgorithmParameters params = AlgorithmParameters.getInstance(KEY_NAME);
params.init(new IvParameterSpec(iv));
return params;
}
/**
* 生成解密
*/
public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, AlgorithmParameters iv)
throws Exception {
Key key = new SecretKeySpec(keyBytes, KEY_NAME);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(encryptedData);
}
}
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
* @author xiaoqiang
* @Description RestTemplate 工具类
* @date 2019/4/22 11:10
*/
@Component
public class RestTemplateUtil {
@Autowired
private RestTemplate restTemplate;
/**
* DoGet方法
* @param url 请求地址
* @return 请求结果
*/
public ResponseEntity<String> doGet(String url) {
return restTemplate.getForEntity(url, String.class);
}
/**
* DoGet方法
* @param url 请求地址
* @param responseType 返回类型
* @return 请求结果
*/
public ResponseEntity<T> doGet(String url, Class<T> responseType) {
return restTemplate.getForEntity(url, responseType);
}
/**
* DoPost方法
* @param url 请求地址
* @param httpHeaders 请求头
* @param uriVariables 请求参数
* @param responseType 返回类型
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public ResponseEntity<T> doPost(String url, HttpHeaders httpHeaders, Map<String, ?> uriVariables, Class<T> responseType) {
/* 请求头 */
MultiValueMap headers = null;
if(httpHeaders == null) {
headers = new HttpHeaders();
}else {
headers = httpHeaders;
}
/* 请求内容封装成HttpEntity */
HttpEntity httpEntity= new HttpEntity(uriVariables, headers);
return restTemplate.postForEntity(url, httpEntity, responseType);
}
/**
* DoPost方法
* @param url 请求地址
* @param params 请求参数
* @param responseType 返回类型
* @return
*/
public ResponseEntity<T> doPost(String url, String params, Class<T> responseType) {
/* 请求内容封装成HttpEntity */
HttpEntity<String> httpEntity= new HttpEntity<String>(params);
return restTemplate.postForEntity(url, httpEntity, responseType);
}
}