java获取微信用户openid

按照惯例,先是官方传送门:https://developers.weixin.qq.com/miniprogram/dev/api/api-login.html

1.登录流程介绍

调用微信开放接口wx.login获取一个临时的登录凭证code

微信小程序通过https请求访问自己的服务器,服务器携带登录凭证code以及小程序的appid和appsecret从微信服务器中获取openid和session_key,UnionID 只在满足一定条件的情况下返回,另外,一个code只能使用一次。

2.开发

2.1 前端

wxml:

< button class= "login" type= "" open-type= "getUserInfo" bindgetuserinfo= "login">微信登录 </ button >

wxss:(目的是为了去除微信button自带的样式)

.login{
background-color: #FFF;
box-sizing: unset;
}
.login::after{
border: 0 rpx;
}

感受一下加了这段css的前后变化

          

js:

login: function (e) {
var that = this;
//调用登录接口,获取 code
if (wx.getStorageSync( "userInfo") && wx.getStorageSync( "empInfo")){
return;
}
wx.login({
success: function (res) {
wx.getSetting({
success(setRes) {
// 判断是否已授权
if (!setRes.authSetting[ 'scope.userInfo']) {
// 授权访问
wx.authorize({
scope: 'scope.userInfo',
success() {
//获取用户信息
wx.getUserInfo({
lang: "zh_CN",
success: function (userRes) {
//发起网络请求
wx.request({
//url: API_URL,
url: address+ 'getWxUserInfo',
data: {
grant_type: "authorization_code",
encryptedData: userRes.encryptedData,
iv: userRes.iv,
code: res.code
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
//服务端的回掉
success: function (result) {
var openid = result.data.openid;
var session_key = result.data.session_key
that.data.userInfo.openid = openid;
that.data.userInfo.session_key = session_key;
wx.setStorageSync( "userInfo", that.data.userInfo);
that.showModal();
}, fail: function () {
wx.showToast({
title: '服务器异常,清稍候再试',
icon: 'none'
})
}
})
},
})
}
})
} else {
//获取用户信息
wx.getUserInfo({
lang: "zh_CN",
success: function (userRes) {
that.setData({
userInfo: userRes.userInfo
})
//发起网络请求
wx.request({
url: address + 'getWxUserInfo' ,
data: {
grant_type: "authorization_code",
encryptedData: userRes.encryptedData,
iv: userRes.iv,
code: res.code,
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'POST',
success: function (result) {
var openid = result.data.openid;
var session_key = result.data.session_key
that.data.userInfo.openid = openid;
that.data.userInfo.session_key = session_key;
wx.setStorageSync( "userInfo", that.data.userInfo);
that.showModal();
}, fail: function () {
wx.showToast({
title: '服务器异常,清稍候再试',
icon: 'none'
})
}
})
}
})
}
}
})
}, fail: function (res) {
wx.showToast({
title: '获取授权信息失败',
icon: 'none'
})
}
})
},

java后端:

https请求:

@RequestMapping("/getWxUserInfo")
    public static JSONObject getSessionKeyOropenid(String grant_type,String code,String iv,String encryptedData){ 
        //微信端登录code值  
        //String wxCode = code;  
        //ResourceBundle resource = ResourceBundle.getBundle("weixin");   //读取属性文件  
        //String requestUrl = resource.getString("url");  //请求地址 https://api.weixin.qq.com/sns/jscode2session  
        Map<String,String> requestUrlParam = new HashMap<String,String>();  
        requestUrlParam.put("appid", WXConst.appId);  //开发者设置中的appId  
        requestUrlParam.put("secret", WXConst.appSecret); //开发者设置中的appSecret  
        requestUrlParam.put("js_code", code); //小程序调用wx.login返回的code  
        requestUrlParam.put("grant_type", grant_type);    //默认参数  
          
        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识  
        JSONObject jsonObject = JSON.parseObject(UrlUtil.sendPost(WXConst.WxGetOpenIdUrl, requestUrlParam));  
        return jsonObject;  

    }

UrlUtil.java

private static Logger log = Logger.getLogger(UrlUtil.class);


/**
* 向指定 URL 发送POST方法的请求

* @param url
*            发送请求的 URL
* @param param
*            请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, ?> paramMap) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";


String param = "";
Iterator<String> it = paramMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
param += key + "=" + paramMap.get(key) + "&";
}
param = param.substring(0,param.length()-1);
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;

}

WXConst.java

//微信小程序appid
public static String appId = "";
//微信小程序appsecret
public static String appSecret = "";
    //获取微信Openid的请求地址

public static String WxGetOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session";


就这样就好啦~很简单呐!!!

猜你喜欢

转载自blog.csdn.net/u012667477/article/details/80942306
今日推荐