完成wxLogin模块接口bug修复

pull/58/head
riverflow 1 month ago
parent af2d588e8a
commit a433c059a9

@ -69,6 +69,12 @@
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version> <!-- 或者使用与你的Spring Boot版本兼容的版本 -->
</dependency>
</dependencies>
<build>

@ -0,0 +1,14 @@
package com.itmk.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

@ -5,55 +5,74 @@ import com.itmk.web.wxapi.entity.Code2Session;
import com.itmk.web.wxapi.entity.LoginParm;
import com.itmk.web.wxapi.entity.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.client.RestTemplate;
@Slf4j
@RestController
@RequestMapping("/wxapi/user")
public class WxLoginController {
@Autowired
private RestTemplate restTemplate;
@Value("${Wechat.Applets.appId}")
private String appId;
@Value("${Wechat.Applets.appSecret}")
private String appSecret;
//小程序登录
@PostMapping("/wxLogin")
public ResultVo wxLogin(@RequestBody LoginParm parm){
String code = parm.getCode();
log.info("wxlogin - code: " + code);
String url = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, String> param = new HashMap<>();
param.put("appid", appId);
param.put("secret", appSecret);
param.put("js_code", code);
param.put("grant_type", "authorization_code");
log.info("param: " + param);
try {
//发送请求
String wxResult = HttpClientUtil.doGet(url, param);
// 构建请求URL
String url = "https://api.weixin.qq.com/sns/jscode2session" +
"?appid=" + appId +
"&secret=" + appSecret +
"&js_code=" + code +
"&grant_type=authorization_code";
log.info("Request URL: " + url);
// 使用 RestTemplate 发送请求
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
String wxResult = response.getBody();
log.info("WeChat API response: " + wxResult);
//转换参数
Code2Session userJson = FastJsonTools.getJson(wxResult, Code2Session.class);
log.info("userJson: " + userJson);
if(userJson == null) throw new BusinessException(500,"小程序获取open失败");
if(userJson == null || userJson.getOpenid() == null) {
throw new BusinessException(500,"小程序获取open失败");
}
String openid = userJson.getOpenid();
String sessionKey = userJson.getSession_key();
log.info("openid: " + openid);
log.info("sessionKey: " + sessionKey);
LoginVo vo = new LoginVo();
vo.setOpenid(openid);
vo.setSessionKey(sessionKey);
return ResultUtils.success("获取成功",vo);
} catch (Exception e) {
e.printStackTrace();
log.error(String.format("WxLoginController.wxLogin Error", e));
log.error("WxLoginController.wxLogin Error", e);
return ResultUtils.error("小程序获取open失败: " + e.getMessage());
}
return ResultUtils.error("小程序获取open失败");
}
}

@ -27,34 +27,128 @@
onShow
} from '@dcloudio/uni-app';
import {
ref
ref,
onMounted
} from 'vue'
//
const nickName = ref('大幕孤烟直')
const nickName = ref('微信用户')
//
const avatarUrl = ref('/static/user.jpg')
//
onMounted(() => {
const storedAvatar = uni.getStorageSync('avatarUrl')
const storedNickName = uni.getStorageSync('nickName')
if (storedAvatar && storedNickName) {
nickName.value = storedNickName
avatarUrl.value = storedAvatar
console.log('从缓存加载用户信息:', storedNickName, storedAvatar)
}
})
//
const getUserInfo = () => {
console.log('获取头像')
if (uni.getStorageSync('avatarUrl') && uni.getStorageSync('nickName')) {
nickName.value = uni.getStorageSync('nickName')
avatarUrl.value = uni.getStorageSync('avatarUrl')
} else {
uni.getUserProfile({
desc: '用于头像昵称展示', //
success: (res) => {
console.log(res)
nickName.value = res.userInfo.nickName
avatarUrl.value = res.userInfo.avatarUrl
uni.setStorageSync('avatarUrl', res.userInfo.avatarUrl);
uni.setStorageSync('nickName', res.userInfo.nickName);
console.log('获取用户信息')
//
uni.getSetting({
success: (res) => {
if (res.authSetting['scope.userInfo']) {
//
uni.showLoading({
title: '获取用户信息中...'
})
//
uni.getUserInfo({
success: (res) => {
console.log('已授权用户信息:', res)
// 使
const userInfo = res.userInfo || {}
nickName.value = userInfo.nickName || '未知用户'
// URL
let avatar = userInfo.avatarUrl || '/static/user.jpg'
if (avatar !== '/static/user.jpg') {
//
avatar += (avatar.includes('?') ? '&' : '?') + 't=' +
new Date().getTime()
}
avatarUrl.value = avatar
//
uni.setStorageSync('avatarUrl', avatar);
uni.setStorageSync('nickName', nickName.value);
console.log('更新后的用户信息:', nickName.value, avatarUrl.value)
//
uni.showToast({
title: '信息更新成功',
icon: 'success'
})
},
fail: (err) => {
uni.hideLoading()
console.log('获取用户信息失败:', err)
uni.showToast({
title: '获取信息失败',
icon: 'none'
})
}
})
} else {
//
uni.showModal({
title: '用户信息授权',
content: '需要获取您的头像和昵称',
success: (res) => {
if (res.confirm) {
//
uni.getUserProfile({
desc: '用于完善会员资料',
success: (res) => {
console.log('授权成功:', res)
// 使
const userInfo = res.userInfo || {}
nickName.value = userInfo.nickName ||
'未知用户'
// URL
let avatar = userInfo.avatarUrl ||
'/static/user.jpg'
if (avatar !== '/static/user.jpg') {
//
avatar += (avatar.includes('?') ? '&' :
'?') + 't=' + new Date()
.getTime()
}
avatarUrl.value = avatar
//
uni.setStorageSync('avatarUrl', avatar);
uni.setStorageSync('nickName', nickName
.value);
console.log('更新后的用户信息:', nickName.value,
avatarUrl.value)
},
fail: (err) => {
console.log('授权失败:', err)
uni.showToast({
title: '授权失败',
icon: 'none'
})
}
})
}
}
})
}
})
}
},
fail: (err) => {
console.log('检查授权设置失败:', err)
}
})
}
onShow(() => {
getUserInfo()
})
</script>
<style lang="scss">

Loading…
Cancel
Save