实现微信小程序微信登录的前提,你需要注册一个微信公众平台 小程序 账号 ,然后才可以进行下面的操作!(感觉小程序登录相对于企业微信登录简单一点)
话不多说 上代码:
在微信小程序端发起登录
-------------------------------------------------微信小程序端--------------------------------------------------------
<button style=" background-color: green;" open-type='getUserInfo' bindgetuserinfo='doLogin'>微信登录</button>
现在登录用button的形式授权 open-type='getUserInfo' bindgetuserinfo='doLogin' 这两个是重要的属性
doLogin :function(e){
console.log(e)
wx.login({
success: function(res){
console.log(res)
//获取登录临时凭证
var code = res.code;
//调用后端接口 获取微信的session_key 和 openID
wx.request({
url: 'http://localhost:8080/wxLogin?code='+code,
method:"post",
success: function (resule){
console.log(resule);
}
})
}
})
}
然后到 js 调用微信小程序 login 方法 访问后台接口
------------------------------------------------java后端代码---------------------------------------------------------
@PostMapping("/wxLogin")
public IMoocJSONResult wxLogin(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, String> param = new HashMap<>();
param.put("appid", "这里放你的微信小程序id");
param.put("secret", "这里放你的微信小程序密匙");
param.put("js_code", code);
param.put("grant_type", "authorization_code");
String wxResult = this.doGet(url, param);
System.out.println(wxResult);
//wxResult 已经拿到openid 和 session_key 下面转为json格式
WXSessionModel model = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);
return IMoocJSONResult.ok(model);
}
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
可直接cv,以上就是微信小程序获取登录的一个流程和实现