微信小程序獲取openId
官方文檔
wx.login:【穿梭門】
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
auth.code2Session【穿梭門】
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
案例
小程序端
首先登錄獲取code,攜帶code去我們自己的后台。
wx.login({
success(res) {
if (res.code) {
console.log(res.code)
http.postData('我們自己的后台接口地址', {
'code': res.code
}, (rep) => {
if (rep.success) {
console.log("返回數據:", rep);
} else {
console.log("獲取openId失敗",);
}
})
} else {
console.log('登錄失敗")
}
}
})
我們自己后台
我們自己的后台接口,用戶接受微信小程序請求我們自己后台接口
/**
* @TODO 微信小程序通過code獲取openid
* @Auther wjw
* @Date 2020/4/22 8:29
*/
@ApiOperation("微信小程序通過code獲取openid")
@PostMapping("/getId")
public Result<Object> getWeChatOpenId(@RequestBody JSONObject jsonObject) {
String code= jsonObject.getString("code");
JSONObject json = getSessionKeyOropenid(code);
return Result.ok(json);
}
后台接收到小程序的請求根據這個方式請求微信官方獲取用戶的openId
/**
* 獲取微信小程序 session_key 和 openid
*
* @param code 調用微信登陸返回的Code
* @return
*/
public JSONObject getSessionKeyOropenid(String code) {
//微信端登錄code值
String wxCode = code;
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session"; //請求地址 https://api.weixin.qq.com/sns/jscode2session
Map<String, String> requestUrlParam = new HashMap<String, String>();
requestUrlParam.put("appid", "你微信小程序的appID"); //開發者設置中的appId
requestUrlParam.put("secret", "你微信小程序的appSecret"); //開發者設置中的appSecret
requestUrlParam.put("js_code", wxCode); //小程序調用wx.login返回的code
requestUrlParam.put("grant_type", "authorization_code"); //默認參數 authorization_code
//發送post請求讀取調用微信 https://api.weixin.qq.com/sns/jscode2session 接口獲取openid用戶唯一標識
JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
return jsonObject;
}
在獲取微信用戶openId是調用的方法,就是發送一個post請求,請求微信官方。
/**
* 向指定 URL 發送POST方法的請求
*
* @param url 發送請求的 URL
* @return 所代表遠程資源的響應結果
*/
public 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) + "&";
}
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) {
// logger.error(e.getMessage(), e);
}
//使用finally塊來關閉輸出流、輸入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
最后微信用戶的openID就拿到了。