阿狸巴巴科技|微信小程序技巧——获取用户唯一标识openid

相关知识
微信小程序、spring-boot
一、步骤
1.获得的用户登录凭证code(有效期五分钟)2.发送参数code至后端3.通过code获取openid
二、实现
1.获取code
接口:wx.login
接口地址:https://developers.weixin.qq.com/miniprogram/dev/framework/plugin/functional-pages/user-info.html
app.js
//登录wx.login({success:res=>{//发送res.code到后台换取openId,sessionKey,unionIdpconsole.log(res.code)wx.request({url:'http://127.0.0.1:8081/user_info/openid?code='+res.code,success:res=>{console.log(res)this.globalData.openid=res.data.data[0].openid}})}})globalData:{openid:null,}2.通过code获取openid
接口:https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
接口地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
核心代码
@ServicepublicclassUserInfoServiceImplimplementsUserInfoService{privateLoggerlogger=LoggerFactory.getLogger(this.getClass());@OverridepublicList<HashMap>getOpenId(Stringcode){logger.info(''根据code获取openid'');Stringurl=jscode2session+''?''+''appid=''+appid+''&secret=''+secret+''&js_code=''+code+''&grant_type=authorization_code'';try{returnHttpRequest.httpGet(url);}catch(Exceptione){e.printStackTrace();logger.error(''获取openid失败'');}returnnull;}}请求工具
<!--druidstart--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.18</version></dependency><!--druidend--><!--json对象转换start--><!--https://mvnrepository.com/artifact/com.alibaba/fastjson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency><!--json对象转换end-->packagecom.aiplay.aipic.utils.http;importcom.alibaba.druid.support.json.JSONUtils;importcom.alibaba.fastjson.JSONObject;importjava.io.BufferedReader;importjava.io.DataOutputStream;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;publicclassHttpRequest{publicstaticList<HashMap>httpGet(StringhttpUrl){try{URLurl=newURL(httpUrl);//通过远程url连接对象打开一个连接 , 强转成httpURLConnection类HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//设置连接方式:getconnection.setRequestMethod(''GET'');//设置连接主机服务器的超时时间:15000毫秒connection.setConnectTimeout(15000);//设置读取远程返回的数据时间:60000毫秒connection.setReadTimeout(60000);//发送请求connection.connect();//通过connection连接 , 获取输入流//得到响应流InputStreaminputStream=connection.getInputStream();//获取响应BufferedReaderreader=newBufferedReader(newInputStreamReader(inputStream));Stringline;List<HashMap>hashMaps=newArrayList<>();while((line=reader.readLine())!=null){HashMaphashMap=JSONObject.parseObject(line,HashMap.class);hashMaps.add(hashMap);}reader.close();connection.disconnect();returnhashMaps;}catch(Exceptione){e.printStackTrace();}returnnull;}}注意:测试时需要进入微信小程序 , 关闭IP白名单 , 否则请求不了openid