詳解SpringBoot如何實現(xiàn)整合微信登錄
1.準(zhǔn)備工作
1.1 獲取微信登錄憑證
前往官網(wǎng)微信開放平臺 (qq.com),完成以下步驟:
1.注冊
2.郵箱激活
3.完善開發(fā)者資料
4.開發(fā)者資質(zhì)認(rèn)證
5.創(chuàng)建網(wǎng)站應(yīng)用
1.2 配置文件
在配置文件application.properties添加相關(guān)配置信息:
# 微信開放平臺 appid wx.open.app_id=你的appid # 微信開放平臺 appsecret wx.open.app_secret=你的appsecret # 微信開放平臺重定向url wx.open.redirect_url=http://81/api/ucenter/wx/callback
1.3 添加依賴
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!--commons-io-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!--gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
1.4 創(chuàng)建讀取公共常量的工具類
創(chuàng)建讀取公共常量的工具類ConstantWxUtils:
/**
* @author xppll
* @date 2021/12/11 14:39
*/
@Component
public class ConstantWxUtils implements InitializingBean {
@Value("${wx.open.app_id}")
private String appId;
@Value("${wx.open.app_secret}")
private String appSecret;
@Value("${wx.open.redirect_url}")
private String redirectUrl;
public static String WX_OPEN_APP_ID;
public static String WX_OPEN_APP_SECRET;
public static String WX_OPEN_REDIRECT_URL;
@Override
public void afterPropertiesSet() throws Exception {
WX_OPEN_APP_ID = appId;
WX_OPEN_APP_SECRET = appSecret;
WX_OPEN_REDIRECT_URL = redirectUrl;
}
}
1.5 HttpClient工具類
/**
* 依賴的jar包有:commons-lang-2.6.jar、httpclient-4.3.2.jar、httpcore-4.3.1.jar、commons-io-2.4.jar
* @author zhaoyb
*
*/
public class HttpClientUtils {
public static final int connTimeout=10000;
public static final int readTimeout=10000;
public static final String charset="UTF-8";
private static HttpClient client = null;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(128);
cm.setDefaultMaxPerRoute(128);
client = HttpClients.custom().setConnectionManager(cm).build();
}
public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
}
public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
}
public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
SocketTimeoutException, Exception {
return postForm(url, params, null, connTimeout, readTimeout);
}
public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
SocketTimeoutException, Exception {
return postForm(url, params, null, connTimeout, readTimeout);
}
public static String get(String url) throws Exception {
return get(url, charset, null, null);
}
public static String get(String url, String charset) throws Exception {
return get(url, charset, connTimeout, readTimeout);
}
/**
* 發(fā)送一個 Post 請求, 使用指定的字符集編碼.
*
* @param url
* @param body RequestBody
* @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
* @param charset 編碼
* @param connTimeout 建立鏈接超時時間,毫秒.
* @param readTimeout 響應(yīng)超時時間,毫秒.
* @return ResponseBody, 使用指定的字符集編碼.
* @throws ConnectTimeoutException 建立鏈接超時異常
* @throws SocketTimeoutException 響應(yīng)超時
* @throws Exception
*/
public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
throws ConnectTimeoutException, SocketTimeoutException, Exception {
HttpClient client = null;
HttpPost post = new HttpPost(url);
String result = "";
try {
if (StringUtils.isNotBlank(body)) {
HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
post.setEntity(entity);
}
// 設(shè)置參數(shù)
Builder customReqConf = RequestConfig.custom();
if (connTimeout != null) {
customReqConf.setConnectTimeout(connTimeout);
}
if (readTimeout != null) {
customReqConf.setSocketTimeout(readTimeout);
}
post.setConfig(customReqConf.build());
HttpResponse res;
if (url.startsWith("https")) {
// 執(zhí)行 Https 請求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執(zhí)行 Http 請求.
client = HttpClientUtils.client;
res = client.execute(post);
}
result = IOUtils.toString(res.getEntity().getContent(), charset);
} finally {
post.releaseConnection();
if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
}
/**
* 提交form表單
*
* @param url
* @param params
* @param connTimeout
* @param readTimeout
* @return
* @throws ConnectTimeoutException
* @throws SocketTimeoutException
* @throws Exception
*/
public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
SocketTimeoutException, Exception {
HttpClient client = null;
HttpPost post = new HttpPost(url);
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
post.setEntity(entity);
}
if (headers != null && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
}
// 設(shè)置參數(shù)
Builder customReqConf = RequestConfig.custom();
if (connTimeout != null) {
customReqConf.setConnectTimeout(connTimeout);
}
if (readTimeout != null) {
customReqConf.setSocketTimeout(readTimeout);
}
post.setConfig(customReqConf.build());
HttpResponse res = null;
if (url.startsWith("https")) {
// 執(zhí)行 Https 請求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執(zhí)行 Http 請求.
client = HttpClientUtils.client;
res = client.execute(post);
}
return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
} finally {
post.releaseConnection();
if (url.startsWith("https") && client != null
&& client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
}
/**
* 發(fā)送一個 GET 請求
*
* @param url
* @param charset
* @param connTimeout 建立鏈接超時時間,毫秒.
* @param readTimeout 響應(yīng)超時時間,毫秒.
* @return
* @throws ConnectTimeoutException 建立鏈接超時
* @throws SocketTimeoutException 響應(yīng)超時
* @throws Exception
*/
public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
throws ConnectTimeoutException,SocketTimeoutException, Exception {
HttpClient client = null;
HttpGet get = new HttpGet(url);
String result = "";
try {
// 設(shè)置參數(shù)
Builder customReqConf = RequestConfig.custom();
if (connTimeout != null) {
customReqConf.setConnectTimeout(connTimeout);
}
if (readTimeout != null) {
customReqConf.setSocketTimeout(readTimeout);
}
get.setConfig(customReqConf.build());
HttpResponse res = null;
if (url.startsWith("https")) {
// 執(zhí)行 Https 請求.
client = createSSLInsecureClient();
res = client.execute(get);
} else {
// 執(zhí)行 Http 請求.
client = HttpClientUtils.client;
res = client.execute(get);
}
result = IOUtils.toString(res.getEntity().getContent(), charset);
} finally {
get.releaseConnection();
if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
}
/**
* 從 response 里獲取 charset
*
* @param ressponse
* @return
*/
@SuppressWarnings("unused")
private static String getCharsetFromResponse(HttpResponse ressponse) {
// Content-Type:text/html; charset=GBK
if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
String contentType = ressponse.getEntity().getContentType().getValue();
if (contentType.contains("charset=")) {
return contentType.substring(contentType.indexOf("charset=") + 8);
}
}
return null;
}
/**
* 創(chuàng)建 SSL連接
* @return
* @throws GeneralSecurityException
*/
private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
@Override
public void verify(String host, SSLSocket ssl)
throws IOException {
}
@Override
public void verify(String host, X509Certificate cert)
throws SSLException {
}
@Override
public void verify(String host, String[] cns,
String[] subjectAlts) throws SSLException {
}
});
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (GeneralSecurityException e) {
throw e;
}
}
public static void main(String[] args) {
try {
String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);
//String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");
/*Map<String,String> map = new HashMap<String,String>();
map.put("name", "111");
map.put("page", "222");
String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/
System.out.println(str);
} catch (ConnectTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.實現(xiàn)微信登錄
可以參考官方文檔:[網(wǎng)站應(yīng)用微信登錄開發(fā)指南](準(zhǔn)備工作 | 微信開放文檔 (qq.com))
2.1 具體流程

- 第三方發(fā)起微信授權(quán)登錄請求,微信用戶允許授權(quán)第三方應(yīng)用后,微信會拉起應(yīng)用或重定向到第三方網(wǎng)站,并且?guī)鲜跈?quán)臨時票據(jù)code參數(shù)
- 通過code參數(shù)加上AppID和AppSecret等,通過API換取access_token
- 通過access_token進(jìn)行接口調(diào)用,獲取用戶基本數(shù)據(jù)資源或幫助用戶實現(xiàn)基本操作
獲取access_token時序圖:

2.2 生成微信掃描的二維碼(請求CODE)
controller層:
/**
* @author xppll
* @date 2021/12/11 14:48
*/
@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
@Autowired
private UcenterMemberService memberService;
/**
* 生成微信掃描二維碼
* @return 定向到請求微信地址
*/
@GetMapping("login")
public String getWxCode() {
//微信開放平臺授權(quán)baseUrl
String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
"?appid=%s" +
"&redirect_uri=%s" +
"&response_type=code" +
"&scope=snsapi_login" +
"&state=%s" +
"#wechat_redirect";
//對redirect_url進(jìn)行URLEncoder編碼
String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
try {
redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new GuliException(20001, e.getMessage());
}
//設(shè)置%s的值
String url = String.format(
baseUrl,
ConstantWxUtils.WX_OPEN_APP_ID,
redirectUrl,
"atguigu"
);
//重定向到請求微信地址
return "redirect:" + url;
}
}
訪問:http://localhost:8160/api/ucenter/wx/login
訪問授權(quán)url后會得到一個微信登錄二維碼:

用戶掃描二維碼會看到確認(rèn)登錄的頁面:

用戶點(diǎn)擊“確認(rèn)登錄”后,微信服務(wù)器會向谷粒學(xué)院的業(yè)務(wù)服務(wù)器發(fā)起回調(diào),因此接下來我們需要開發(fā)回調(diào)controller
2.3 回調(diào)
具體分幾步:
1.通過code獲取access_token
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
| 參數(shù) | 是否必須 | 說明 |
|---|---|---|
| appid | 是 | 應(yīng)用唯一標(biāo)識,在微信開放平臺提交應(yīng)用審核通過后獲得 |
| secret | 是 | 應(yīng)用密鑰AppSecret,在微信開放平臺提交應(yīng)用審核通過后獲得 |
| code | 是 | 填寫第一步獲取的code參數(shù) |
| grant_type | 是 | 填authorization_code |
2.從返回結(jié)果獲取兩個值access_token、openid
3.通過openid查詢數(shù)據(jù)庫判斷該用戶是不是第一次登錄
4.如果是第一次登錄,根據(jù)access_token和openid再去訪問微信的資源服務(wù)器,獲取用戶信息,存入數(shù)據(jù)庫
5.使用jwt根據(jù)member對象生成token字符串,最后返回首頁面,通過路徑傳遞token字符串
/**
* 獲取掃描人信息,添加數(shù)據(jù)
* @param code 類似于手機(jī)驗證碼,隨機(jī)唯一的值
* @param state 用于保持請求和回調(diào)的狀態(tài),授權(quán)請求后原樣帶回給第三方
* @return
*/
@GetMapping("callback")
public String callback(String code, String state) {
try {
//獲取code值,臨時票據(jù)類似于驗證碼
//拿著code請求微信固定的地址,得到兩個值
//1.向認(rèn)證服務(wù)器發(fā)送請求換取access_token
String baseAccessTokenUrl =
"https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=%s" +
"&secret=%s" +
"&code=%s" +
"&grant_type=authorization_code";
//拼接三個參數(shù):id 密鑰 和 code值
String accessTokenUrl = String.format(
baseAccessTokenUrl,
ConstantWxUtils.WX_OPEN_APP_ID,
ConstantWxUtils.WX_OPEN_APP_SECRET,
code
);
//2.請求拼接好的地址,得到返回的兩個值access_token和openid
//使用httpclient發(fā)送請求,得到返回結(jié)果(json形式的字符串)
String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
//從accessTokenInfo字符串獲取兩個值access_token、openid
//把a(bǔ)ccessTokenInfo字符串轉(zhuǎn)換為map集合,根據(jù)map里面的key獲取值
//這里使用json轉(zhuǎn)換工具Gson
Gson gson = new Gson();
HashMap accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
String access_token = (String) accessTokenMap.get("access_token");
String openid = (String) accessTokenMap.get("openid");
//3.判斷該用戶是不是第一次掃碼登錄
//通過openid判斷
UcenterMember member = memberService.getOpenIdMember(openid);
//4.只有第一次登錄才獲取信息
if (member == null) {
//根據(jù)access_token和openid再去訪問微信的資源服務(wù)器,獲取用戶信息
String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
"?access_token=%s" +
"&openid=%s";
String userInfoUrl = String.format(
baseUserInfoUrl,
access_token,
openid
);
//發(fā)送請求,得到用戶信息
String userInfo = HttpClientUtils.get(userInfoUrl);
System.out.println(userInfo);
//將用戶信息存入數(shù)據(jù)庫
//把json轉(zhuǎn)換為map
HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
//得到nickname
String nickname = (String) userInfoMap.get("nickname");
//得到微信頭像avatar
String headimgurl = (String) userInfoMap.get("headimgurl");
member = new UcenterMember();
member.setOpenid(openid);
member.setNickname(nickname);
member.setAvatar(headimgurl);
memberService.save(member);
}
//5.使用jwt根據(jù)member對象生成token字符串
String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
//最后返回首頁面,通過路徑傳遞token字符串
return "redirect:http://localhost:3000?token=" + jwtToken;
} catch (Exception e) {
throw new GuliException(20001, "微信登錄失敗");
}
}
判斷該用戶是不是第一次掃碼登錄
以上就是詳解SpringBoot如何實現(xiàn)整合微信登錄的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot整合微信登錄的資料請關(guān)注腳本之家其它相關(guān)文章!
- Springboot項目中實現(xiàn)微信小程序登錄案例(最新推薦)
- SpringBoot整合Mybatis-Plus實現(xiàn)微信注冊登錄的示例代碼
- 微信小程序使用uni-app和springboot實現(xiàn)一鍵登錄功能(JWT鑒權(quán))
- springboot實現(xiàn)微信掃碼登錄的項目實踐
- springboot+jwt+微信小程序授權(quán)登錄獲取token的方法實例
- 一篇文章帶你入門Springboot整合微信登錄與微信支付(附源碼)
- springboot 微信授權(quán)網(wǎng)頁登錄操作流程
- SpringBoot實現(xiàn)微信掃碼登錄的示例代碼
相關(guān)文章
使用Springboot實現(xiàn)獲取某個城市當(dāng)天的天氣預(yù)報
這篇文章主要為大家詳細(xì)介紹了使用Springboot實現(xiàn)獲取某個城市當(dāng)天的天氣預(yù)報的相關(guān)知識,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04
淺談Java內(nèi)存區(qū)域劃分和內(nèi)存分配策略
這篇文章主要介紹了淺談Java內(nèi)存區(qū)域劃分和內(nèi)存分配策略,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Java上傳文件進(jìn)度條的實現(xiàn)方法(附demo源碼下載)
這篇文章主要介紹了Java上傳文件進(jìn)度條的實現(xiàn)方法,可簡單實現(xiàn)顯示文件上傳比特數(shù)及進(jìn)度的功能,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下2015-12-12
Spring Boot接收單個String入?yún)⒌慕鉀Q方法
這篇文章主要給大家介紹了關(guān)于Spring Boot接收單個String入?yún)⒌慕鉀Q方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用spring boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
計算Java數(shù)組長度函數(shù)的方法以及代碼分析
在本篇內(nèi)容里,小編給大家整理了關(guān)于計算Java數(shù)組長度函數(shù)的方法以及代碼分析內(nèi)容,有興趣的朋友么可以學(xué)習(xí)參考下。2022-11-11

