各位大佬请教一个问题,我这里没有获得unionid的原因是小程序没有认证完成吗?
// app.js
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: 'http://localhost:8081/api/login',
data: {
code: res.code
},
success: function (response) {
// 处理登录结果
console.log(response.data);
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
},
globalData: {
userInfo: null
}
})
package com.msbd.backend.test;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSONObject;
@RestController
public class LoginController {
private static final String APPID = "xxxxxxxxxxxxxxx";
@GetMapping("/api/login")
public String login(@RequestParam("code") String code) {
try {
// 假设这里使用 saToken 生成 JWT 令牌
String jwtToken = StpUtil.getTokenInfo().getTokenValue();
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + jwtToken + "&js_code=" + code + "&grant_type=authorization_code";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jsonObject = JSONObject.parseObject(response.toString());
String unionid = jsonObject.getString("unionid");
System.out.println("========================>unionid = " + unionid);
// 根据 unionid 查找或创建用户
// ...
return "Login success with unionid: " + unionid;
} catch (Exception e) {
e.printStackTrace();
return "Login failed";
}
}
}
未绑定在微信开放平台下,不会有unionid这个参数
跟认证没关系,unionid 是绑定在微信开放平台账号(https://open.weixin.qq.com/)下才会返回的。