微信小程序微信小程序 springboot后台如何获取用户的后台如何获取用户的openid
主要介绍了微信小程序 springboot后台如何获取用户的openid,文中通过示例代码介绍的非常详细,对大家的学
习或者工作具有一定的参考学习价值,需要的朋友可以参考下
openid可以标识一个用户,session_key会变,所以来获取一下openid。
openid不能在微信小程序中直接获取,需要后台发送请求到微信的接口,然后微信返回一个json格式的字符串到后台,后台处
理之后,再返回到微信小程序。
发布的小程序需要https的域名,而测试的时候可以使用http。
小程序在小程序在app.js中,修改中,修改login()中的内容:中的内容:
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
wx.request({
url: 'http://localhost:84/user/login',
method: 'POST',
data: {
code: res.code
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success(res) {
console.log("openid:"+res.data.openid);
if (res.data.openid != "" || res.data.openid!=null){
// 登录成功
wx.setStorageSync("openid", res.data.openid);//将用户id保存到缓存中
wx.setStorageSync("session_key", res.data.session_key);//将session_key保存到缓存中
}else{
// 登录失败
// TODO 跳转到错误页面,要求用户重试
return false;
}
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
这里请求的http://localhost:84/user/login
后台的处理类:后台的处理类:
package com.ft.feathertrade.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ft.feathertrade.entity.OpenIdJson;
import com.ft.feathertrade.utils.HttpUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class LoginHandler {
private String appID = "";
private String appSecret = "";
@PostMapping("/user/login")
public String userLogin(@RequestParam("code") String code) throws IOException {
String result = "";
try{//请求微信服务器,用code换取openid。HttpUtil是工具类,后面会给出实现,Configure类是小程序配置信息,后面会给出代码
result = HttpUtil.doGet(
"https://api.weixin.qq.com/sns/jscode2session?appid="
+ this.appID + "&secret="
评论0