小程序app.js:

//app.js 
App({
requestSite: 'https://group.huoyuntong.top',
session: {
data: null,
status: 0,
readyHandle: {
length: 0
},
init: function(e) {
var app = e || getApp(),
session = this;
if (app) {
session.status = 1;
wx.login({
success: function(res) {
if (res.code) {
//发起网络请求
wx.showLoading({
title: '',
})
app.globalData.code = res.code;
wx.request({
url: app.requestSite + '/inform/decodeOpenid?code=' + res.code,
data: {
version: app.version
},
method: 'POST',
success: function(res) {
wx.hideLoading()
console.log('OPENID:', res)
if (res.data.code == 400) {
session.status = 0;
session.init(app);
} else if (res.data.code == 0) {
session.data = res.data;
session.data.userInfo = e;
if (session.data.data) {
session.status = 2;
app.globalData.isGetOpenId = true;
for (var i in session.readyHandle)
if (session.readyHandle.hasOwnProperty(i))
if (typeof session.readyHandle[i] === 'function')
session.readyHandle[i](session.data);
session.readyHandle = {
length: 0
};
if (app.getOpenHandle) {
app.getOpenHandle();
}
} else {
session.init(app);
}
}
},
fail: function() {
session.status = 0;
session.init(app);
}
})
}
}
});
}
},
get: function(space, call) {
var session = this;
call = typeof space === 'function' ? space : call;
space = typeof space === 'string' || typeof space === 'number' ? space : session.readyHandle.length++;
// console.log('space', space, session.readyHandle.length);
function pushHandle() {
session.readyHandle[space] = call;
}
if (session.status === 0) {
pushHandle();
session.init();
} else if (session.status === 1) {
pushHandle();
} else if (session.status === 2) {
if (session.data.data) {
call(session.data)
} else {
pushHandle();
session.init();
}
}
}
},
onLaunch: function() {

var app = this;

function ready() {
app.session.init(app);
}

function showLowerVersion() {
wx.showModal({
title: '提示',
content: '当前微信版本过低,将会影响小程序的正常使用,建议升级微信版本',
showCancel: false,
confirmText: '知道了',
complete: function(e) {
ready();
}
});
}
if (wx.getSystemInfoSync) {
var sysInfo = wx.getSystemInfoSync();
var SDKVersion = sysInfo['SDKVersion'].split('.');
if (SDKVersion[0] <= 1 && SDKVersion[1] < 4) showLowerVersion();
else ready();
} else showLowerVersion();
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId


}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo

// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})

},

globalData: {
userInfo: null
},

})

后台代码:

    @ResponseBody
@RequestMapping(value = "/inform/decodeOpenid", produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
public String decodeOpenid(HttpServletResponse response, String code){
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");

String wxspAppid = "填写小程序appid";
String wxspSecret = "填写小程序密钥";

try {
Map<String, String> map = new HashMap<>();
// 授权(必填)
String grant_type = "authorization_code";
// 请求参数
String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
+ grant_type;
log.info("解析code请求参数:"+params.toString());
// 发送请求
String sr = HttpRequest.sendPost("https://api.weixin.qq.com/sns/jscode2session", params);
// 解析相应内容(转换成json对象)
JSONObject json = JSONObject.parseObject(sr);
log.info("解析code请求结果:"+json.toString());
// 获取会话密钥(session_key)
String session_key = json.getString("session_key");
String openid = json.getString("openid");

log.info("openid:"+openid);
return RespResult.resp400("openId生成失败");
} catch (Exception e) {
e.printStackTrace();
return RespResult.resp500(e);
}
}

关注公众号回复091可获取项目源码