微信小程序 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跳转到错误页面,要求用户重试
returnfalse;
}
}
})
}else{
console.log('获取用户登录态失败!'+res.errMsg)
}
}
})
这里请求的http://localhost:84/user/login
后台的处理类:
packagecom.ft.feathertrade.handler;
importcom.fasterxml.jackson.databind.ObjectMapper;
importcom.ft.feathertrade.entity.OpenIdJson;
importcom.ft.feathertrade.utils.HttpUtil;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
importjava.io.IOException;
@RestController
publicclassLoginHandler{
privateStringappID="";
privateStringappSecret="";
@PostMapping("/user/login")
publicStringuserLogin(@RequestParam("code")Stringcode)throwsIOException{
Stringresult="";
try{//请求微信服务器,用code换取openid。HttpUtil是工具类,后面会给出实现,Configure类是小程序配置信息,后面会给出代码
result=HttpUtil.doGet(
"https://api.weixin.qq.com/sns/jscode2session?appid="
+this.appID+"&secret="
+this.appSecret+"&js_code="
+code
+"&grant_type=authorization_code",null);
}
catch(Exceptione){
e.printStackTrace();
}
ObjectMappermapper=newObjectMapper();
OpenIdJsonopenIdJson=mapper.readValue(result,OpenIdJson.class);
System.out.println(result.toString());
System.out.println(openIdJson.getOpenid());
returnresult;
}
}
HttpUtil工具类:
packagecom.ft.feathertrade.utils; importjava.io.BufferedReader; importjava.io.InputStreamReader; importjava.net.HttpURLConnection; importjava.net.URL; importjava.net.URLEncoder; importjava.util.HashMap; importjava.util.Map.Entry; importjava.util.Set; importorg.apache.commons.httpclient.HttpStatus;//此类需要添加maven依赖或jar包 /**将此依赖添加到pom.xml中**/ publicclassHttpUtil{ publicstaticStringdoGet(StringurlPath,HashMap commons-httpclient commons-httpclient 3.1 params) throwsException{ StringBuildersb=newStringBuilder(urlPath); if(params!=null&&!params.isEmpty()){//说明有参数 sb.append("?"); Set >set=params.entrySet(); for(Entry entry:set){//遍历map里面的参数 Stringkey=entry.getKey(); Stringvalue=""; if(null!=entry.getValue()){ value=entry.getValue().toString(); //转码 value=URLEncoder.encode(value,"UTF-8"); } sb.append(key).append("=").append(value).append("&"); } sb.deleteCharAt(sb.length()-1);//删除最后一个& } //System.out.println(sb.toString()); URLurl=newURL(sb.toString()); HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000);//5s超时 conn.setRequestMethod("GET"); if(conn.getResponseCode()==HttpStatus.SC_OK){//HttpStatus.SC_OK== //200 BufferedReaderreader=newBufferedReader(newInputStreamReader( conn.getInputStream())); StringBuildersbs=newStringBuilder(); Stringline; while((line=reader.readLine())!=null){ sbs.append(line); } returnsbs.toString(); } returnnull; } }
OpenIdJson的实体类:
packagecom.ft.feathertrade.entity;
publicclassOpenIdJson{
privateStringopenid;
privateStringsession_key;
publicStringgetOpenid(){
returnopenid;
}
publicvoidsetOpenid(Stringopenid){
this.openid=openid;
}
publicStringgetSession_key(){
returnsession_key;
}
publicvoidsetSession_key(Stringsession_key){
this.session_key=session_key;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。