1, 首先前端會調用授權接口這個不用管, 調用授權接口以後, 會拿到微信用戶的頭像, 名稱, 前端的朋友請往這邊走, 微信小程序登入流程, 你可能走錯片場了, 我們討論的是後臺的登入
2, 我只需要知道, 當前端調用微信的授權接口以後, 有一個很重要的參數, 那就是code, 這個code是微信授權以後下發的, 我們拿到這個code , 就可以去微信服務器, 拿到這個用戶在微信的上面的唯一標識, 理論上我們需要三個參數, 根據業務不同
code : 微信授權以後的就更隨機驗證碼似的
username: 你可要可不要, 我覺得你最好還是好了
userimage: 用戶的頭像, 這個最好存起來,
上面這三個參數後臺都不需要管, 而是前端調用授權接口以後就會有的, 讓前端發送回後臺就好了
3, 使用http請求工具訪問微信獲取用戶信息, http請求工具
登入控制器
@RequestMapping("/login")
public ResultMap login(@Param("code") String code, HttpServletRequest request, @Param("inviteId") final Long inviteId){
ResultMap resultMap = new ResultMap();
resultMap.setSuccess(true);
Map data = resultMap.getData();
try {
Map<String,String[]> parameterMap = request.getParameterMap();
if (StringUtils.isEmpty(code)) {
throw new RuntimeException("參數異常");
}
//去微信查詢用戶的openid
StringBuilder urlPath = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session");
urlPath.append(String.format("?appid=%s", appId)); //appid
urlPath.append(String.format("&secret=%s", secret)); //secretid
urlPath.append(String.format("&js_code=%s", code));
urlPath.append(String.format("&grant_type=%s", "authorization_code"));
JSONObject object = HttpUtil.doGet(urlPath.toString());
//工具類返回的數據封裝成map了
final Map map = object.parseObject(object.toJSONString());
//這個就是我們要的
String openId = (String) map.get("openid");
String sessionKey = (String) map.get("session_key");
if (openId == null){
throw new RuntimeException("登入code錯誤");
}
//查詢用戶, 拿着openid去數據庫查
Account account = accountService.findByOpenid(openId);
//查不到就代表未註冊
if(account == null){
//新用戶, 保存參數到數據庫
}else{
//老用戶, 登入操作
}
return resultMap;
} catch (Exception e) {
e.printStackTrace();
ResultMap resultMap = new ResultMap();
resultMap.setSuccess(false);
resultMap.setMsg("登入失敗");
return resultMap;
}
}
登入以後, 根據去微信查詢的信息, 判斷哪個openid在數據庫裏面存在不存在, 判斷是否爲老用戶, 還是新用戶, 新用戶就做註冊, 老用戶就登入, 關於微信小程序, 服務器如果保持登入態, 點擊這裏