一、需求
在PC端的登錄頁面加個微信掃碼的按鈕,點擊按鈕彈出二維碼,實現微信掃碼登錄網站的功能。如圖:
二、調研
掃碼登錄屬於微信開放平臺提供的API,不是微信公衆平臺。這裏需要註冊等配置,暫不贅述。
同時也要注意,如果你也需要微信公衆號內的登錄授權操作,那麼用戶唯一標識不應該是openId,而應該是unionId,因爲微信公衆平臺和微信開放平臺的openId是不一樣的。
三、開始開發
1.後臺新增生成二維碼圖片的接口,因爲我這裏掃碼後跳轉的地址不是固定的,所以也用到了這個state參數,如果固定可以寫死這個跳轉地址。
/**
* 返回二維碼
*
* @param state 掃碼成功後跳轉的鏈接
* @return
*/
@ResponseBody
@RequestMapping(value = "/getQrCode", method = RequestMethod.GET)
public String getQrCode(String state) {
try {
state = StringUtils.isBlank(state) ? "state" : state;
//redirectUri 是掃碼回調的地址 下一個方法oauth
String encodeUri = URLEncoder.encode(redirectUri, "UTF-8");
String url = "https://open.weixin.qq.com/connect/qrconnect?" +
"appid={appId}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_login&state={state}#wechat_redirect";
String urlReplace = url.replace("{appId}", appId).replace("{redirect_uri}", encodeUri)
.replace("{state}", state);
log.info("-----微信開放平臺掃碼登錄url-----" + urlReplace);
return urlReplace;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
2.前端調用接口,打開二維碼的頁面
//wx_login 是按鈕的id
$("#wx_login").on("click", function () {
$.ajax({
url: '二維碼接口/getQrCode',
async: true,
dataType: 'json',
type: 'get',
success: function (data) {
location.href = data;
}
});
});
3.後端新增掃描二維碼回調的方法,其中主要做了:
①:微信後臺回調該方法,傳入code參數,用來獲取 accessToken和openId
②:調用微信授權接口即getUserAuthInfo,獲取 accessToken和openId
請求方式:GET
URL: https://api.weixin.qqcom/sns/oauth2/access_token?appid={APP_ID}&secret={APP_SECRET}&code={CODE}&grant_type=authorization_code
③:調用微信用戶信息接口即getWxAuthUser,獲取用戶的unionId,暱稱等信息。
請求方式:GET
URL: https://api.weixin.qq.com/sns/userinfo?access_token={ACCESS_TOKEN}&openid={OPENID}&lang=zh_CN
/**
* pc掃碼登錄跳轉
*
* @return
*/
@RequestMapping(value = "/oauth", method = RequestMethod.GET)
public RedirectView oauth(HttpServletRequest request, HttpServletResponse response) {
String code = request.getParameter("code");
String state = request.getParameter("state");
//appId appSecret 在微信開放平臺找到
Map<String, String> userAuthMap = userInfoService.getUserAuthInfo(code, appId, appSecret);
String accessToken = userAuthMap.get("access_token");
String openid = userAuthMap.get("openid");
WxAuthUser wxAuthUser = WechatUtil.getWxAuthUser(accessToken, openid);
if (wxAuthUser == null) {
return null;
}
//你的登錄邏輯
String jsonResult = doLogin(wxAuthUser);
log.info("-----微信開放平臺掃碼跳轉url-----" + state);
RedirectView redirectView = new RedirectView(state);
redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
return redirectView;
}
最後:總體來說流程比較簡單,所以代碼貼的不是很全,但是都有講到。
有一些注意的點比如微信開放平臺需要綁定公衆號、回調域名等配置。