天天看點

java擷取微信使用者openid1.登入流程介紹2.開發

按照慣例,先是官方傳送門: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的前後變化

java擷取微信使用者openid1.登入流程介紹2.開發
java擷取微信使用者openid1.登入流程介紹2.開發

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);

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";

就這樣就好啦~很簡單呐!!!