最近在写小程序项目时遇到一些问题,小程序登录授权API接口调用会区分新旧版本库,旧版本在调取wx.getUserProfile接口时会直接从底部弹窗,从而允许或取消授权;而新版本库则需要自行设置弹窗,提醒用户授权使用。
测试新版本和旧版本究竟是哪个可以自动底部弹窗,使用多个版本后发现2.25.4是相较于高版本并且可以升起底部授权弹窗,2.26.2发发生报错,建议使用2.25.4
本文介绍老版本库从底部弹窗授权登录,调用wx.getUserProfile接口获取用户基本信息(微信昵称、头像、openid、session_key)使用微信开发者工具+idea编写后端是Java的springboot
1、微信小程序端:button点击授权按钮
wxml:
<view>
<button class="confirm-btn" bindtap="getUserProfile">点击授权</button>
</view>
js :
data: {
session: null,
code: null,
userInfo: null,
hasUserInfo: false,
avatarUrl: null,
nickName: null,
jwt:null,
},
getUserProfile(e){
wx.getUserProfile({
desc: '用于完善会员资料',
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true,
}),
console.log('登录成功:', res);
app.globalData.UserInfo = this.data.userInfo;
this.onGetUserInfo(res);
}
})
},
onGetUserInfo: function(e) {
if (e) {
// 用户同意了授权
wx.login({
success: async (res) => {
if (res.code) {
// 获取用户登录凭证(code)
var code = res.code;
console.log(code);
// 发起网络请求,将code发送给服务器
wx.request({
url: 'http://localhost:8080/wx/user/login',
data: {
code : code,
avatarUrl : this.data.userInfo.avatarUrl,
nickName : this.data.userInfo.nickName
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded' // POST请求默认为 application/x-www-form-urlencoded
},
success: function(res) {
console.log('登录成功:', res);
app.globalData.jwt = res.data.content.jwt
setTimeout(() => {
wx.switchTab({
url: '/pages/main/homePage/homePage',
});
}, 1000);
},
fail: function(err) {
console.error('登录失败:', err);
}
});
} else {
console.log('获取用户登录态失败!' + res.errMsg);
}
}
});
} else {
// 用户按了拒绝按钮
wx.showToast({
title: '您已拒绝授权',
icon: 'none'
});
}
},
2、后端springboot:直接在controller调用
@RestController
@RequestMapping("/wx")
public class WxLoginController {
@Autowired
private WxUserDataService wxUserDataService;
/**
* 登录分为用户小程序登录和后台员工登录
**/
/**
* 小程序端微信用户登录
*/
private static final String APPID = "****"; // 你的小程序AppID
private static final String SECRET = "****"; // 你的小程序AppSecret
@PostMapping("/user/login")
public Result login(String code, String nickName, String avatarUrl) throws IOException {
// 构造请求微信服务器的URL
Map<String, String> params = new LinkedHashMap<>();
params.put("appid", APPID);
params.put("secret", SECRET);
params.put("js_code", code);
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
requestUrl = String.format(requestUrl, APPID, SECRET, code);
// 使用RestTemplate发起请求
RestTemplate restTemplate = new RestTemplate();
// 发起GET请求
ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class, params);
if (response.getStatusCode().is2xxSuccessful()) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(response.getBody());
// 获取session_key和openid
String sessionKey = jsonNode.get("session_key").asText();
String openid = jsonNode.get("openid").asText();
WxUserData wxUserData = new WxUserData();
wxUserData.setUserOpenId(openid);
wxUserData.setUserSession(sessionKey);
wxUserData.setUserNickName(nickName);
wxUserData.setUserAvatarUrl(avatarUrl);
wxUserDataService.wxUserLogin(wxUserData);
//生成JWT
JwtDto jwtDto = new JwtDto();
if (wxUserData != null){
Map<String, Object> claims = new HashMap<>();
claims.put("openid", openid);
claims.put("session_key", sessionKey);
claims.put("nickName", nickName);
claims.put("avatarUrl", avatarUrl);
String jwt = JwtUtils.generateJwt(claims);
jwtDto.setJwt(jwt);
}
// 返回session_key和openid
return Result.success(jwtDto);
} catch (IOException e) {
return Result.fail("微信登录获取信息异常!");
}
} else {
ResponseEntity<String> body = ResponseEntity.status(response.getStatusCode()).body(response.getBody());
return Result.fail(500,"登陆失败",body);
}
}
}
呈现状态:
小程序端点击授权后
允许后查看小程序端控制台输出
成功调用wx.getUserProfile接口获取用户基本信息。
标签:openid,code,String,登录,微信,res,授权,wx From: https://blog.csdn.net/bao_cai/article/details/142854872