微信掃描二維碼登入第三方平臺
嗯。。。。。。
最近做了一個微信掃碼登陸第三方平臺功能,說下步驟就行,反正原理你們網上直接百度,我這裡寫了,估計也沒幾個人有耐心看
第一步 生成一個連結
https://open.weixin.qq.com/connect/qrconnect?appid=xxxxxxxxf&redirect_uri=xxxxxxxxxxxx&response_type=code&scope=snsapi_login&state=#wechat_redirect
訪問這個連結的時候,就會返回一張二維碼 xxxxx地方是引數,,appid需要你開通微信開放平臺,開通之後就會有,還有一個secret,,這2個都需要,這裡需要注意,微信還有一個公眾平臺也有這2個引數,他們是不一樣的。你開發的時候要區分是開放平臺還是公眾平臺,不要掉進坑裡 ,redirect_uri=這個是說,你掃描二維碼之後,要跳轉的地址,這裡跳轉回帶上code和state 2個引數,所以你編寫的時候需要這樣
@RequestMapping(value = "/code", params = { "code", "state" }, method = RequestMethod.GET)
@ResponseBody
public Object getAuth(HttpServletRequest request, @RequestParam String code, @RequestParam String state)
throws JSONException {
///這裡第一步,首先需要通過appid,secret ,code 去獲取token
https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret="
+ SECRET + "&code=" + code + "&grant_type=authorization_code";//獲取token的地址,
這裡我使用的是 apache下的httpclient
DefaultHttpClient client = new DefaultHttpClient();
try {
HttpGet getRequest = new HttpGet(access_token_url);
HttpResponse response = client.execute(getRequest);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(response.getEntity());
logger.info("-------jsonResult-------" + strResult);
JSONObject jsonResult = new JSONObject(strResult);
if (jsonResult.has("unionid")){
unionid= (String) jsonResult.get("unionid");
}
這個引數非常的重要,但是我也懶得講了,你們自己百度吧,就是要記住一點,這個引數是唯一的,
}
然後經過你後臺的鑑權通過之後,跳轉,至於鑑權方式,就看你自己額
你可以通過 unionid 去資料庫尋找使用者,,智力需要說明,,unionid是之前就獲取到了使用者的,然後初始化到資料庫了得,至於怎麼查詢unionid,需要通過openid
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN。這個是獲取unionid 的,至於這個openid,你獲取token 的時候,就會有的,反正你寫個指令碼,把他們儲存資料庫,當作初始化,
if (SecurityUtils.getSubject().isAuthenticated()) {
logger.info(" 二維碼登入成功 : " + openid);
logger.info(" 二維碼登入成功 username : " + (String) SecurityUtils.getSubject().getPrincipal());
return new ModelAndView("redirect:x'x'x'x'x'x'x'x'x");
}