簡介
小程序官方API URL: https://developers.weixin.qq.com/miniprogram/dev/api/api-login.html
小程序登錄 流程圖
API的詳細知識這裏就不科普了,想了解的就到官方文檔瞭解吧~~~~ 又過5分鐘~~~話癆啊~~ 趕緊上代碼 看下面哦
-------------------------------------------------------------------------------實測開始-------------------------------------------------------------------------
小程序客戶端(實測)
//app.js
App({
onLaunch: function () {
// 展示本地存儲能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登錄
wx.login({
success: res => {
withCredentials: true,//非必填 默認爲true
console.log('獲取用戶code:' + res.code) //臨時登錄憑證
// 發送 res.code 到後臺換取 openId, sessionKey, unionId
if (res.code) {
wx.getUserInfo({
success: function (res_user) {
wx.request({
url: 'http://192.168.1.102:8080/agile/applet/getOpenId', //這裏是本地請求路徑,可以寫你自己的本地路徑,也可以寫線上環境
data: {
code: res.code,//獲取openid的話 需要向後臺傳遞code,利用code請求api獲取openid
headurl: res_user.userInfo.avatarUrl,//這些是用戶的基本信息
nickname: res_user.userInfo.nickName,//獲取暱稱
sex: res_user.userInfo.gender,//獲取性別
country: res_user.userInfo.country,//獲取國家
province: res_user.userInfo.province,//獲取省份
city: res_user.userInfo.city//獲取城市
},
success: function (res) {
wx.setStorageSync("openid", res.data)//可以把openid保存起來,以便後期需求的使用
}
})
}
})
}
}
})
// 獲取用戶信息
wx.getSetting({
success: res => {
}
})
},
globalData: {
userInfo: null
}
})
java服務端
1.定義final變量
// AppID(小程序ID) 小程序唯一標識 (在微信小程序管理後臺獲取)
private static final String APPID = "wx8a503ea211d48xxx";
// 小程序的 AppSecret(小程序密鑰) (在微信小程序管理後臺獲取)
private static final String APPSECRET = "d3455f3cfb9685c602b60e48caa0xxxx";
// 授權(必填) 填寫爲 authorization_code
private static final String GRANT_TYPE = "authorization_code";
2.調用官方API,返回客戶端OpenId信息 (實測)
注意(此處未使用 encryptedData 加密與iv偏移量)加密解密處理
/**
*
* @Title: getOpenId
* @Description: TODO(根據小程序客戶端code服務端返回OpenId)
* @param: code 客戶端code (只能使用一次)
* @param: encryptedData 包括敏感數據在內的完整用戶信息的加密數據
* @param: iv 加密算法的初始向量
* @param:
* @return: Map<String,Object>
* @throws
*/
@ResponseBody
@RequestMapping(value = "getOpenId" , method = RequestMethod.GET)
public Map<String, Object> getOpenId(HttpServletRequest request,HttpServletResponse response
,@RequestParam(required=true) String code
,String encryptedData,String iv){
Map<String, Object> map = Maps.newHashMap();
//code獲取參數
if (StringUtils.isBlank(code)) {
map.put("status", "fail");
map.put("message", "code is not null.");
return map;
}
//獲取用戶信息
String str_code =request.getParameter("code");
String str_nickname =request.getParameter("nickname");
String str_sex =request.getParameter("sex");
String sr_country =request.getParameter("country");
String str_province =request.getParameter("province");
String str_city =request.getParameter("city");
String str_avatarUrl =request.getParameter("avatarUrl");
System.out.println("-------user ino begin---------");
System.out.println("code="+str_code);
System.out.println("nickname="+str_nickname);
System.out.println("sex="+str_sex);
System.out.println("country="+sr_country);
System.out.println("code="+str_province);
System.out.println("city="+str_city);
System.out.println("avatarUrl="+str_avatarUrl);
System.out.println("-------user ino end---------");
//發起GET請求獲取憑證
JSONObject jsonObject = null;
String stringToken = String.format(
"https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=%s",
APPID, APPSECRET, code,GRANT_TYPE);
String result = HttpRequest.sendGet(stringToken,null);
jsonObject = JSONObject.fromObject(result);
try {
String openId = jsonObject.getString("openid");// 用戶唯一標識
String session_key = jsonObject.getString("session_key");// 密鑰
System.out.println("--------success info begin-----");
System.out.println("openid="+openId);
System.out.println("session_key="+session_key);
System.out.println("--------success info end-----");
map.put("openId", openId);
map.put("status", "success");
map.put("message", "請求成功");
} catch (Exception e) {
System.out.println("--------err info begin-----");
System.out.println("errcode="+jsonObject.getString("errcode"));
System.out.println("errmsg="+jsonObject.getString("errmsg"));
System.out.println("--------err info end-----");
switch (jsonObject.getString("errcode")) {
case "40163":
map.put("message", "code重複使用");
break;
case "40029":
map.put("message", "code無效");
break;
case "40125":
map.put("message", "appId or secret無效");
break;
default:
map.put("message", "錯誤");
break;
}
map.put("openId", "");
map.put("status", "fail");
}
return map;
}
3.實測返回結果
-------user ino begin---------
code=011j67xg2Qs4vA051mwg2eLaxg2j67xE
nickname=菜芽
sex=1
country=Angola
code=Cunene
city=
avatarUrl=null
-------user ino end---------
null--->[HTTP/1.1 200 OK]
Date--->[Thu, 08 Nov 2018 08:30:09 GMT]
Content-Length--->[83]
Content-Type--->[text/plain]
Connection--->[keep-alive]
--------success info begin-----
openid=oAJ1N5Vg-XXXXfCj6uGrD1NgTXXX
session_key=B7RlqqkXXX406N0/XXX==
--------success info end-----
收工,暫時先這樣不優化了,等有時間在優化下,有需要的直接擄走就能使用。吼吼~~~~