|
1.首先我們需要去微信公眾平臺 https://mp.weixin.qq.com/ 準備的是AppID(小程序ID)和AppSecret(小程序密鑰)
 2.準備好后開始寫代碼 3.controller @RestController
public class GetOpenIdController {
/**
* 功能描述:
* 微信小程序用codeid換取openid
* @param codeId
* @return
*/
@GetMapping("/onLogin")
private HttpResponseEntity onLogin(String codeId){
HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
try {
String openid = RedisUtils.getOpenId(codeId);
System.err.println(openid);
httpResponseEntity.setCode(Constans.SUCCESS_CODE);
httpResponseEntity.setMessage(Constans.RESULT_SUCCESS);
httpResponseEntity.setData(openid);
}catch (Exception e){
e.printStackTrace();
httpResponseEntity.setMessage(Constans.RESULT_EXIST);
httpResponseEntity.setCode(Constans.ADD_EXIST_CODE);
}
return httpResponseEntity;
}
}
4.RedisUtils /**
* 獲取小程序codeid換取openid
* @param codeId
* @return
*/
public static String getOpenId(String codeId) {
String url = CODE_URL APP_ID "&secret=" SECRET "&js_code=" codeId "&grant_type=authorization_code";
PrintWriter out = null;
BufferedReader in = null;
String line;
StringBuffer stringBuffer = new StringBuffer();
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性 設置請求格式
//設置返回類型
conn.setRequestProperty("contentType", "text/plain");
//設置請求類型
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//設置超時時間
conn.setConnectTimeout(1000);
conn.setReadTimeout(1000);
conn.setDoOutput(true);
conn.connect();
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應 設置接收格式
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = in.readLine()) != null) {
stringBuffer.append(line);
}
JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
return jsonObject.get("openid").toString();
} catch (Exception e) {
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 根據(jù)code換取openId
* 本接口應在后端服務器調(diào)用
*/
private final static String CODE_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=";
private final static String APP_ID = "AppID(小程序ID)";
private final static String SECRET = "AppSecret(小程序密鑰)";
CODE_URL為請求地址 這樣后臺就完成了(封裝的返回結果集這里就不展示了) 微信小程序端:新建一個小程序 修改app.js就好 //app.js
App({
onLaunch: function () {
var that = this;
// 展示本地存儲能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登錄
wx.login({
success: function(res) {
// 發(fā)送 res.code 到后臺換取 openId, sessionKey, unionId
if(res.code){
wx.request({
url: 'http://localhost:8080/onLogin',
data:{
codeId:res.code
},
success: res => {
console.log(res);
res.data.openid = res.data.data;
that.globalData.openid = res.data.openid;
console.log(that.globalData.openid);
}
})
}else{
console.log("獲取用戶登錄失敗!" res.errMsg)
}
}
})
// 獲取用戶信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已經(jīng)授權,可以直接調(diào)用 getUserInfo 獲取頭像昵稱,不會彈框
wx.getUserInfo({
success: res => {
// 可以將 res 發(fā)送給后臺解碼出 unionId
this.globalData.userInfo = res.userInfo
console.log(res);
// 由于 getUserInfo 是網(wǎng)絡請求,可能會在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
globalData: {
userInfo: null,
openid:null
}
})
這樣就基本完成了 我們來運行下看看效果:


|