微信登錄之前還需要瞭解OAuth2知識 前期準備 註冊微信開放平臺 郵箱激活 完善開發者資料(暫不支持個體用戶) 開發者資質認證:營業執照、1-2個工作如審批、300元 網站應用:最好是已經部署到伺服器上的項目,7個工作日審批 審核通過之後會有AppID和AppSecret兩個值 AppID: 申請 ...
- 微信登錄之前還需要瞭解OAuth2知識
- 前期準備
- 註冊微信開放平臺
- 郵箱激活
- 完善開發者資料(暫不支持個體用戶)
- 開發者資質認證:
營業執照
、1-2個工作如審批
、300元
- 網站應用:最好是已經部署到伺服器上的項目,7個工作日審批
- 審核通過之後會有AppID和AppSecret兩個值
AppID
:申請的ID
AppSecret
:申請的Secret
- 說明:微信登錄二維碼是以彈出層的形式打開,所以前端需要做一些引入
- 在頁面中引入js文件:
https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js
- 在需要使用微信登錄的地方實例js對象
- 在頁面中引入js文件:
var obj = new WxLogin(
{
self_redirect: true,
id: "放置二維碼的容器id",
appid: "",
scope: "",
redirect_uri: "",
state: "",
style: "",
href: ""
}
);
- 整個過程
- 通過調用後端的介面,將上面js對象所需要的參數返回給前端頁面
- 前端頁面獲取到所需要的參數即可生成二維碼
- 用戶掃描二維碼重定向(回調)到當前後端返回的redirect_uri
- 回調成功則微信登錄成功
- 從這個過程中發現微信登錄過程中至少需要兩個介面
- SpringBoot實現
- application.properties添加微信登錄的一些配置,其中redirect_uri應該是在申請微信登錄的時候會存在一個映射關係(這裡博主也不是很懂),
目前微信登錄支持localhost,埠應該是尚矽谷
老師設定了(有可能是博主的映射關係(狗頭)),後面的映射路徑就是回調介面的映射路徑
- application.properties添加微信登錄的一些配置,其中redirect_uri應該是在申請微信登錄的時候會存在一個映射關係(這裡博主也不是很懂),
wx.open.app_id=上面提供的AppID
wx.open.app_secret=上面提供的AppSecret
wx.open.redirect_uri=http://localhost:8160/api/user/wx/callback
web.base_url=http://localhost:3000
- 新建常量類,讀取配置文件中微信的配置信息
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class WxConstantProperties implements InitializingBean {
@Value("${wx.open.app_id}")
private String appId;
@Value("${wx.open.app_secret}")
private String appSecret;
@Value("${wx.open.redirect_uri}")
private String redirectUrl;
@Value("${web.base_url}")
private String yyghBaseUrl;
public static String WX_OPEN_APP_ID;
public static String WX_OPEN_APP_SECRET;
public static String WX_OPEN_REDIRECT_URL;
public static String WEB_BASE_URL;
@Override
public void afterPropertiesSet() throws Exception {
WX_OPEN_APP_ID = appId;
WX_OPEN_APP_SECRET = appSecret;
WX_OPEN_REDIRECT_URL = redirectUrl;
WEB_BASE_URL = yyghBaseUrl;
}
}
- 第一個介面:返回前端生成二維碼的參數
import java.util.HashMap;
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {
@GetMapper("/getWxParam")
@ResponseBody
public Result<Map<String, Object>> getParam() {
try {
Map<String, Object> map = new HashMap<>();
map.put("appid", WxConstantProperties.WX_OPEN_APP_ID);
// 固定值
map.put("scope", "snsapi_login");
String wxOpenRedirectUrl = WxConstantProperties.WX_OPEN_REDIRECT_URL;
// 應微信開放平臺要求,需要使用URLEncoder規範url
wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
map.put("redirect_uri", wxOpenRedirectUrl);
// 隨意值
map.put("state", System.currentTimeMillis() + "");
return Result.ok(map);
} catch (Exception e) {
e.printStackTrace();
return Result.fail();
}
}
}
- 前端創建兩個文件
- 請求後端介面的js文件
import request from '@/utils/request'
export default {
getWxParam() {
return request({
url: `/api/user/wx/getWxParam`,
method: 'get'
})
}
}
- 當前登錄頁面的vue組件
<template></template>
<script>
<!-- 引入上面的js文件 -->
import wxApi from '@/api/wx/wxApi.js'
export default {
data() {
return {}
},
mounted() {
// 註冊全局登錄事件對象
window.loginEvent = new Vue();
// (註冊)監聽登錄事件
loginEvent.$on('loginDialogEvent', function () {
document.getElementById("loginDialog").click();
})
// 觸發事件,顯示登錄層:loginEvent.$emit('loginDialogEvent')
//初始化微信js(包好上面提及的登錄js文件)
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
document.body.appendChild(script)
// 微信登錄回調處理
let self = this;
window["loginCallback"] = (name,token, openid) => {
self.loginCallback(name, token, openid);
}
},
methods: {
// 第一個介面:獲取參數,生成二維碼
wxLogin() {
// 可以忽略的文本信息
this.dialogAtrr.showLoginType = 'weixin'
wxApi.getWxParam().then(response => {
var obj = new WxLogin({
self_redirect:true,
id: 'weixinLogin', // 需要顯示的容器id
appid: response.data.appid, // 公眾號appid wx*******
scope: response.data.scope, // 網頁預設即可
redirect_uri: response.data.redirect_uri, // 授權成功後回調的url
state: response.data.state, // 可設置為簡單的隨機數加session用來校驗
style: 'black', // 提供"black"、"white"可選。二維碼的樣式
href: '' // 外部css文件url,需要https
})
})
},
// 第二個介面:重定向到某個頁面並保存cookie信息
loginCallback(name, token, openid) {
// 打開手機登錄層,綁定手機號,改邏輯與手機登錄一致
if(openid != '') {
this.userInfo.openid = openid
this.showLogin()
} else {
this.setCookies(name, token)
}
},
setCookies(name, token) {
cookie.set('token', token, { domain: 'localhost' })
cookie.set('name', name, { domain: 'localhost' })
window.location.reload()
},
}
}
</script>
<style></style>
- 在編寫第二個介面前,需要瞭解一個服務端向另一個服務端發送請求,往往是需要一個工具類
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HttpClientUtils {
public static final int CONN_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 10000;
public static final String CHARSET = "UTF-8";
public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
private static HttpClient client;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(128);
cm.setDefaultMaxPerRoute(128);
client = HttpClients.custom().setConnectionManager(cm).build();
}
public static String postParameters(String url, String params) throws Exception {
return post(url, params, CONTENT_TYPE, CHARSET, CONN_TIMEOUT, READ_TIMEOUT);
}
public static String postParameters(String url, String params, String charset, Integer connTimeout, Integer readTimeout) throws Exception {
return post(url, params, CONTENT_TYPE, charset, connTimeout, readTimeout);
}
public static String postParameters(String url, Map<String, String> params) throws Exception {
return postForm(url, params, null, CONN_TIMEOUT, READ_TIMEOUT);
}
public static String postParameters(String url, Map<String, String> params, Integer connTimeout, Integer readTimeout) throws 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, CONN_TIMEOUT, READ_TIMEOUT);
}
/**
* 發送一個get請求
* @param url 請求地址
* @param charset 字元集編碼
* @param connTimeout 連接超時時間
* @param readTimeout 響應超時時間
* @return String
* @throws Exception ConnectTimeoutException、SocketTimeoutException等其他異常
*/
public static String get(String url, String charset, Integer connTimeout, Integer readTimeout) throws Exception {
HttpClient client = null;
HttpGet get = new HttpGet(url);
String result = "";
try {
// 設置參數
getHttpRequestBase(get, connTimeout, readTimeout);
// 獲取響應信息
HttpResponse res = getHttpResponse(url, get, client);
result = IOUtils.toString(res.getEntity().getContent(), charset);
}finally {
get.releaseConnection();
if (url.startsWith("https") && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
}
/**
* 發送一個post請求
* @param url 請求地址
* @param body 請求體
* @param mimeType 類似於Content-Type
* @param charset 字元集編碼
* @param connTimeout 連接超時時間
* @param readTimeout 響應超時時間
* @return String
* @throws Exception ConnectTimeoutException、SocketTimeoutException等其他異常
*/
public static String post(String url, String body, String mimeType, String charset, Integer connTimeout, Integer readTimeout) throws Exception {
HttpClient client = null;
HttpPost post = new HttpPost(url);
String result = "";
try {
if(!StringUtils.isEmpty(body)) {
HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
post.setEntity(entity);
}
// 設置參數
getHttpRequestBase(post, connTimeout, readTimeout);
// 獲取響應信息
HttpResponse res = getHttpResponse(url, post, client);
result = IOUtils.toString(res.getEntity().getContent(), charset);
} finally {
post.releaseConnection();
if (url.startsWith("https") && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
}
/**
* form表單提交方式請求
* @param url 請求地址
* @param params 表單參數
* @param headers 請求頭
* @param connTimeout 連接超時時間
* @param readTimeout 響應超時時間
* @return String
* @throws Exception ConnectTimeoutException、SocketTimeoutException等其他異常
*/
public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout, Integer readTimeout) throws Exception {
HttpClient client = null;
HttpPost post = new HttpPost(url);
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> formParams = new ArrayList<>();
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());
}
}
// 設置參數
getHttpRequestBase(post, connTimeout, readTimeout);
// 獲取響應信息
HttpResponse res = getHttpResponse(url, post, client);
return IOUtils.toString(res.getEntity().getContent(), String.valueOf(StandardCharsets.UTF_8));
}finally {
post.releaseConnection();
if (url.startsWith("https") && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
}
/**
* 設置參數
* @param base 協議請求對象
* @param connTimeout 連接超時時間
* @param readTimeout 響應超時時間
*/
private static void getHttpRequestBase(HttpRequestBase base, Integer connTimeout, Integer readTimeout) {
Builder customReqConf = RequestConfig.custom();
if(connTimeout != null) customReqConf.setConnectTimeout(connTimeout);
if(readTimeout != null) customReqConf.setSocketTimeout(readTimeout);
base.setConfig(customReqConf.build());
}
/**
* 獲取響應信息
* @param url 請求地址
* @param base 協議請求對象
* @return HttpResponse
* @throws Exception 異常信息
*/
private static HttpResponse getHttpResponse(String url, HttpRequestBase base, HttpClient client) throws Exception{
if (url.startsWith("https")) {
// 執行 Https 請求.
client = createSSLInsecureClient();
} else {
// 執行 Http 請求.
client = HttpClientUtils.client;
}
return client.execute(base);
}
/**
* 創建SSL連接供https協議請求
* @return CloseableHttpClient
* @throws GeneralSecurityException 安全異常
*/
private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public void verify(String s, SSLSocket sslSocket) throws IOException {}
@Override
public void verify(String s, X509Certificate x509Certificate) throws SSLException {}
@Override
public void verify(String s, String[] strings, String[] strings1) throws SSLException {}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
} catch (GeneralSecurityException e) {
throw e;
}
}
/**
* 從 response 里獲取 charset
* @param response 響應信息
*/
@SuppressWarnings("unused")
private static String getCharsetFromResponse(HttpResponse response) {
// Content-Type:text/html; charset=GBK
if (response.getEntity() != null && response.getEntity().getContentType() != null && response.getEntity().getContentType().getValue() != null) {
String contentType = response.getEntity().getContentType().getValue();
if (contentType.contains("charset=")) {
return contentType.substring(contentType.indexOf("charset=") + 8);
}
}
return null;
}
}
- 第二個介面:處理掃碼之後的介面(一般是獲取當前掃碼用戶的信息)
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {
@GetMapping("/callback")
public String callback(String code, String state) {
// 根據臨時票據code和微信id及密鑰請求微信固定地址,獲取兩個值(access_token和openid)
StringBuffer baseAccessTokenUrl = new StringBuffer()
.append("https://api.weixin.qq.com/sns/oauth2/access_token")
.append("?appid=%s").append("&secret=%s")
.append("&code=%s").append("&grant_type=authorization_code");
String accessTokenUrl = String.format(
baseAccessTokenUrl.toString(), ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET, code);
try {
// 使用HttpClientUtils工具類請求地址
String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
String accessToken = jsonObject.getString("access_token");
String openid = jsonObject.getString("openid");
// 如果資料庫表中存在openid值,
UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
if(userInfo == null) {
// 根據access_token和openid獲取掃碼人信息
String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
"?access_token=%s" + "&openid=%s";
String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
String userInfoResult = HttpClientUtils.get(userInfoUrl);
JSONObject userObject = JSONObject.parseObject(userInfoResult);
String nickname = userObject.getString("nickname");
String headImageUrl = userObject.getString("headimgurl");
// 信息保存到資料庫中(省略)
}
// 最後重定向到前端某一個頁面,期間可以隨帶一些重要的信息
return "redirect:" + WxConstantProperties.WEB_BASE_URL + "/weixin/callback?token=" +
token + "&openid=" + openid + "&name=" + URLEncoder.encode(name, "utf-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}