開(kāi)放平臺(tái)需要企業(yè)認(rèn)證才能注冊(cè),正好這次公司提供了一個(gè)賬號(hào),調(diào)通以后拴还,就順便寫(xiě)一篇博客吧。
公眾平臺(tái)與開(kāi)放平臺(tái)的區(qū)別
微信開(kāi)放平臺(tái)
主要面對(duì)移動(dòng)應(yīng)用/網(wǎng)站應(yīng)用開(kāi)發(fā)者欧聘,為其提供微信登錄片林、分享、支付等相關(guān)權(quán)限和服務(wù)。
微信公眾平臺(tái)
微信公眾平臺(tái)用于管理费封、開(kāi)放微信公眾號(hào)(包括訂閱號(hào)焕妙、服務(wù)號(hào)、企業(yè)號(hào))弓摘,簡(jiǎn)單的說(shuō)就是微信公眾號(hào)的后臺(tái)運(yùn)營(yíng)焚鹊、管理系統(tǒng)。
這里想吐槽一下韧献,微信基本注冊(cè)全都要郵箱末患,公眾號(hào)一個(gè)、小程序一個(gè)势决、開(kāi)放平臺(tái)一個(gè)阻塑、我哪他媽有這么多郵箱啊,又記不住密碼果复,下面正題陈莽。
準(zhǔn)備工作
網(wǎng)站應(yīng)用微信登錄是基于OAuth2.0協(xié)議標(biāo)準(zhǔn)構(gòu)建的微信OAuth2.0授權(quán)登錄系統(tǒng)。
在進(jìn)行微信OAuth2.在進(jìn)行微信OAuth2.0授權(quán)登錄接入之前虽抄,在微信開(kāi)放平臺(tái)注冊(cè)開(kāi)發(fā)者帳號(hào)走搁,并擁有一個(gè)已審核通過(guò)的網(wǎng)站應(yīng)用,并獲得相應(yīng)的AppID和AppSecret迈窟,申請(qǐng)微信登錄且通過(guò)審核后私植,可開(kāi)始接入流程。
點(diǎn)擊創(chuàng)建網(wǎng)站應(yīng)用
按照要求填寫(xiě)信息车酣,等待審核通過(guò)就可以獲取appid和appsecret
然后找到回調(diào)授權(quán)域名這一項(xiàng) 修改成要回調(diào)的域名曲稼,例如:www.baidu.com 不要加http://或https://
好了需要提前準(zhǔn)備的東西就完事了,下面就是代碼部分了湖员。
這是完整的調(diào)用圖
我這里用的spring boot項(xiàng)目進(jìn)行測(cè)試的贫悄,但是代碼都大致相同
第一步:請(qǐng)求CODE
這是自己用到的HttpClientUtils工具類(lèi)
package com.lj.demo.controller.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.HttpClients;
import java.net.SocketTimeoutException;
import java.security.GeneralSecurityException;
import java.io.IOException;
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;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.commons.io.IOUtils;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
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.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
/**
* @author LvJun
* @create 2018-03-16 17:51
**/
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ā)送一個(gè) Post 請(qǐng)求, 使用指定的字符集編碼.
*
* @param url
* @param body RequestBody
* @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
* @param charset 編碼
* @param connTimeout 建立鏈接超時(shí)時(shí)間,毫秒.
* @param readTimeout 響應(yīng)超時(shí)時(shí)間,毫秒.
* @return ResponseBody, 使用指定的字符集編碼.
* @throws ConnectTimeoutException 建立鏈接超時(shí)異常
* @throws SocketTimeoutException 響應(yīng)超時(shí)
* @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 請(qǐng)求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執(zhí)行 Http 請(qǐng)求.
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<org.apache.http.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 請(qǐng)求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執(zhí)行 Http 請(qǐng)求.
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ā)送一個(gè) GET 請(qǐng)求
*
* @param url
* @param charset
* @param connTimeout 建立鏈接超時(shí)時(shí)間,毫秒.
* @param readTimeout 響應(yīng)超時(shí)時(shí)間,毫秒.
* @return
* @throws ConnectTimeoutException 建立鏈接超時(shí)
* @throws SocketTimeoutException 響應(yīng)超時(shí)
* @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 請(qǐng)求.
client = createSSLInsecureClient();
res = client.execute(get);
} else {
// 執(zhí)行 Http 請(qǐng)求.
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;
}
}
}
微信有兩種方式認(rèn)證一種是調(diào)轉(zhuǎn)到微信域名下,還一種是直接把二維碼嵌套到自己網(wǎng)站中娘摔。
這里是跳轉(zhuǎn)到微信的認(rèn)證方式
首先在頁(yè)面做一個(gè)簡(jiǎn)單的按鈕 觸發(fā)事件獲取認(rèn)證code
<button onclick="login()">微信登錄</button>
js調(diào)用部分
<script>
function login() {
$.ajax({
type: "POST",
//這個(gè)路徑根據(jù)自己的情況填寫(xiě)
url: "/demo-wechat/wechat/getCode",
success: function (data) {
console.log(data);
if (data.code == 200) {
window.location.href = (data.result);
} else {
alert("認(rèn)證失敗");
}
},
error: function (data) {
alert("認(rèn)證失敗");
}
});
}
</script>
后臺(tái)代碼url參數(shù)都要根據(jù)自己的實(shí)際情況進(jìn)行修改
@RequestMapping("/getCode")
public void getCode() throws Exception {
//拼接url
StringBuilder url = new StringBuilder();
url.append("https://open.weixin.qq.com/connect/qrconnect?");
//appid
url.append("appid=" + "appid");
//回調(diào)地址 ,回調(diào)地址要進(jìn)行Encode轉(zhuǎn)碼
String redirect_uri = "回調(diào)地址"
//轉(zhuǎn)碼
url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));
url.append("&response_type=code");
url.append("&scope=snsapi_login");
HttpClientUtils.get(url.toString(), "GBK");
}
參數(shù) | 是否必填 | 說(shuō)明 |
---|---|---|
appid | 是 | 應(yīng)用唯一標(biāo)識(shí) |
redirect_uri | 是 | 請(qǐng)使用urlEncode對(duì)鏈接進(jìn)行處理 |
response_type | 是 | 填code |
scope | 是 | 網(wǎng)頁(yè)應(yīng)用目前僅填寫(xiě)snsapi_login即可 |
state | 否 | 安全性相關(guān)具體可以參考官方文檔這里可以不填 |
參數(shù)說(shuō)明
redirect_uri 這個(gè)參數(shù)是用戶掃碼確認(rèn)以后微信調(diào)用自己的路徑例如:https://www.baidu.com/wechat/callback
拼完路徑可以打印出來(lái)看一下 完整的路徑應(yīng)該是這樣
https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect
到此獲取code就完成了窄坦,用戶確認(rèn)以后回調(diào)自己的時(shí)候會(huì)帶兩個(gè)參數(shù),
1.code
2.state
如果調(diào)用沒(méi)有傳遞state就不會(huì)返回state 用戶拒絕了登錄請(qǐng)求凳寺,返回的結(jié)果不會(huì)有code
第二步:通過(guò)code獲取access_token
接下來(lái)完成回調(diào)的方法直接上代碼
/**
* 微信回調(diào)
*/
@RequestMapping("/callback")
public ModelAndView callback(String code,String state) throws Exception {
System.out.println("===="+code+"==="+state+"====");
if(StringUtils.isNotEmpty(code)){
StringBuilder url = new StringBuilder();
url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
url.append("appid=" + "appid");
url.append("&secret=" + "secret");
//這是微信回調(diào)給你的code
url.append("&code=" + code);
url.append("&grant_type=authorization_code");
String result = HttpClientUtils.get(url.toString(), "UTF-8");
System.out.println("result:" + result.toString());
}
return new ModelAndView("login");
}
返回說(shuō)明
正確的返回:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
錯(cuò)誤返回樣例:
{"errcode":40029,"errmsg":"invalid code"}
這個(gè)時(shí)候我們拿到用了用戶的一些必要的信息鸭津,剩下的就根據(jù)自己具體的業(yè)務(wù)進(jìn)行后面的操作吧。
這里是第二種 認(rèn)證方式肠缨,把二維碼嵌套到自己的網(wǎng)站
這里只需要改前臺(tái)代碼
創(chuàng)建一個(gè)放二維碼的容器
<div id="login_container" style="width: 500px;height: 500px;"></div>
導(dǎo)入微信的JS
//我這種寫(xiě)法是spring boot對(duì)應(yīng)的 根據(jù)自己前端框架導(dǎo)入
<script th:src="@{http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js}"></script>
在JS里面實(shí)例這么一段代碼
var obj = new WxLogin({
id:"login_container",
appid: "appid",
scope: "snsapi_login",
redirect_uri: "回調(diào)地址",
state: "",
style: "",//這個(gè)是二維碼樣式
href: ""
});
這樣打開(kāi)這個(gè)頁(yè)面就會(huì)自動(dòng)加載微信二維碼逆趋。掃碼認(rèn)證后 后面流程不變,返回的也是code怜瞒,根據(jù)code獲取token父泳。