微信小程序授权登录,前后端代码,Java版本,并获取手机号、昵称和头像
时间: 2023-06-01 18:03:18 浏览: 184
login-test.zip_AQRV_thounyf_微信小程序_授权登录_获取手机号
前端代码:
1. 在页面中引入微信登录组件:
```
<login wx:if="{{!isLogin}}" bind:success="onLoginSuccess" bind:fail="onLoginFail"></login>
```
2. 在页面中定义微信登录组件的回调函数:
```
onLoginSuccess(event) {
const { code } = event.detail;
wx.request({
url: 'https://your-backend-server.com/wechat/login',
method: 'POST',
data: {
code: code,
},
success: res => {
const { token } = res.data;
wx.setStorageSync('token', token);
this.setData({
isLogin: true,
});
},
});
},
onLoginFail() {
wx.showToast({
title: '登录失败,请重试',
icon: 'none',
});
},
```
3. 在页面中调用微信提供的获取用户信息的接口:
```
wx.getUserInfo({
success: res => {
const { encryptedData, iv } = res;
wx.request({
url: 'https://your-backend-server.com/wechat/user-info',
method: 'POST',
header: {
Authorization: `Bearer ${wx.getStorageSync('token')}`,
},
data: {
encryptedData: encryptedData,
iv: iv,
},
success: res => {
const { nickName, avatarUrl } = res.data;
this.setData({
nickName: nickName,
avatarUrl: avatarUrl,
});
},
});
},
});
```
后端代码:
1. 在后端中实现微信登录的接口:
```
@PostMapping("/wechat/login")
public ResponseEntity<Object> login(@RequestParam String code) {
String appId = "your-app-id";
String appSecret = "your-app-secret";
String url = "https://api.weixin.qq.com/sns/jscode2session?" +
"appid=" + appId +
"&secret=" + appSecret +
"&js_code=" + code +
"&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode jsonNode = objectMapper.readTree(response);
if (jsonNode.has("openid")) {
String openid = jsonNode.get("openid").asText();
String sessionKey = jsonNode.get("session_key").asText();
String token = jwtService.generateToken(openid, sessionKey);
return ResponseEntity.ok(Map.of("token", token));
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return ResponseEntity.badRequest().build();
}
```
2. 在后端中实现获取微信用户信息的接口:
```
@PostMapping("/wechat/user-info")
public ResponseEntity<Object> getUserInfo(@RequestHeader("Authorization") String authorization,
@RequestParam String encryptedData, @RequestParam String iv) {
String sessionKey = jwtService.getSessionKey(authorization);
byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
byte[] ivBytes = Base64.getDecoder().decode(iv);
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedDataBytes = cipher.doFinal(encryptedDataBytes);
String decryptedDataString = new String(decryptedDataBytes, StandardCharsets.UTF_8);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(decryptedDataString);
if (jsonNode.has("nickName") && jsonNode.has("avatarUrl")) {
String nickName = jsonNode.get("nickName").asText();
String avatarUrl = jsonNode.get("avatarUrl").asText();
return ResponseEntity.ok(Map.of("nickName", nickName, "avatarUrl", avatarUrl));
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | JsonProcessingException e) {
e.printStackTrace();
}
return ResponseEntity.badRequest().build();
}
```
3. 在后端中实现JWT的生成和解析:
```
@Service
public class JwtService {
private final String secret = "your-jwt-secret";
private final long expirationTime = 86400000L;
public String generateToken(String openid, String sessionKey) {
Date now = new Date();
Date expirationDate = new Date(now.getTime() + expirationTime);
return Jwts.builder()
.setSubject(openid)
.claim("session_key", sessionKey)
.setIssuedAt(now)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getSessionKey(String authorization) {
String token = authorization.replace("Bearer ", "");
String sessionKey = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().get("session_key", String.class);
return sessionKey;
}
}
```
阅读全文