參考地址微信公衆號開發文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1445241432
前提:需要申請認證的微信公衆號;獲取對應的APPID和APPSECRET;並且還需要獲取到用戶信息權限(點擊“修改“添加服務器的域名地址),前期工作安裝測試賬號爲例給大家展示下:
1)、公衆測試賬號獲取
訪問上面的連接,選擇“接口測試號申請”獲得直接打開http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index通過微信客戶端掃碼登錄即可登錄。
登錄完即可獲取到一個測試公衆賬號的信息。主要有appId和appsecret兩個參數,這將唯一標示一個公衆號,並且需要將他們作爲參數獲取用戶的信息。
2)、關注公衆號
還是在剛剛的頁面,有一個“網頁授權獲取用戶基本信息”,點擊後面的修改
一。授權開發的流程(詳情的東西請以官網爲準,在此就不多說了):具體而言,網頁授權流程分爲四步:
1、引導用戶進入授權頁面同意授權,獲取code
2、通過code換取網頁授權access_token(與基礎支持中的access_token不同)
3、如果需要,開發者可以刷新網頁授權access_token,避免過期
4、通過網頁授權access_token和openid獲取用戶基本信息(支持UnionID機制)
二.按照如上流程我就不多說廢話直接粘代碼供大家參考,請大家多多指教(代碼裏的所有APPID,APPSECRET都是使用的官網提供測試賬號)
1.設計一個公用網絡請求工具類:
package com.wxutil.auth;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class WXAuthUtil {
public static final String APPID="wx9b39273dce55dc2f";
public static final String APPSECRET ="06f175852111045f81ebf62db28a44a0";
private static final String TOKEN = "immco";
public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
JSONObject jsonObject =null;
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet =new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity =response.getEntity();
if(entity!=null)
{
//把返回的結果轉換爲JSON對象
String result =EntityUtils.toString(entity, "UTF-8");
jsonObject =JSON.parseObject(result);
}
return jsonObject;
}
}
2.微信登錄的實現類(裏面包含引導action和確認登錄後的回調函數):
package com.wxutil.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.alibaba.fastjson.JSONObject;
import com.wxutil.auth.SHA1;
import com.wxutil.auth.WXAuthUtil;
/**
* @author lbh
* @date 創建時間:2018年1月18日 下午12:35:11
* @version 1.0
* @parameter
* @since
* @return
*/
@Controller
@RequestMapping("/wx")
public class WXLoginController {
private static final Logger logger = Logger.getLogger(WXLoginController.class);
/**
* 公衆號微信登錄授權
* @param request
* @param response
* @return
* @throws ParseException
* @author lbh
* @date 創建時間:2018年1月18日 下午7:33:59
* @parameter
*/
@RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
public String wxLogin(HttpServletRequest request,
HttpServletResponse response)
throws ParseException {
//這個url的域名必須要進行再公衆號中進行註冊驗證,這個地址是成功後的回調地址
String backUrl="http://d84e26b6.ngrok.io/WX_auth/wx/callBack";
// 第一步:用戶同意授權,獲取code
String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WXAuthUtil.APPID
+ "&redirect_uri="+URLEncoder.encode(backUrl)
+ "&response_type=code"
+ "&scope=snsapi_userinfo"
+ "&state=STATE#wechat_redirect";
logger.info("forward重定向地址{" + url + "}");
//response.sendRedirect(url);
return "redirect:"+url;//必須重定向,否則不能成功
}
/**
* 公衆號微信登錄授權回調函數
* @param modelMap
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
* @author lbh
* @date 創建時間:2018年1月18日 下午7:33:53
* @parameter
*/
@RequestMapping(value = "/callBack", method = RequestMethod.GET)
public String callBack(ModelMap modelMap,HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
* start 獲取微信用戶基本信息
*/
String code =req.getParameter("code");
//第二步:通過code換取網頁授權access_token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WXAuthUtil.APPID
+ "&secret="+WXAuthUtil.APPSECRET
+ "&code="+code
+ "&grant_type=authorization_code";
System.out.println("url:"+url);
JSONObject jsonObject = WXAuthUtil.doGetJson(url);
/*
{ "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
*/
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
String refresh_token = jsonObject.getString("refresh_token");
//第五步驗證access_token是否失效;展示都不需要
String chickUrl="https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
JSONObject chickuserInfo = WXAuthUtil.doGetJson(chickUrl);
System.out.println(chickuserInfo.toString());
if(!"0".equals(chickuserInfo.getString("errcode"))){
// 第三步:刷新access_token(如果需要)-----暫時沒有使用,參考文檔https://mp.weixin.qq.com/wiki,
String refreshTokenUrl="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+openid+"&grant_type=refresh_token&refresh_token="+refresh_token;
JSONObject refreshInfo = WXAuthUtil.doGetJson(chickUrl);
/*
* { "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE" }
*/
System.out.println(refreshInfo.toString());
access_token=refreshInfo.getString("access_token");
}
// 第四步:拉取用戶信息(需scope爲 snsapi_userinfo)
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
+ "&openid="+openid
+ "&lang=zh_CN";
System.out.println("infoUrl:"+infoUrl);
JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
/*
{ "openid":" OPENID",
" nickname": NICKNAME,
"sex":"1",
"province":"PROVINCE"
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
*/
System.out.println("JSON-----"+userInfo.toString());
System.out.println("名字-----"+userInfo.getString("nickname"));
System.out.println("頭像-----"+userInfo.getString("headimgurl"));
/*
* end 獲取微信用戶基本信息
*/
//獲取到用戶信息後就可以進行重定向,走自己的業務邏輯了。。。。。。
//接來的邏輯就是你係統邏輯了,請自由發揮
return "login";
}
}