開放平臺需要企業認證才能註冊,正好這次公司提供了一個賬號,調通以後,就順便寫一篇博客吧。
公衆平臺與開放平臺的區別
微信開放平臺
主要面對移動應用/網站應用開發者,爲其提供微信登錄、分享、支付等相關權限和服務。
微信公衆平臺
微信公衆平臺用於管理、開放微信公衆號(包括訂閱號、服務號、企業號),簡單的說就是微信公衆號的後臺運營、管理系統。
這裏想吐槽一下,微信基本註冊全都要郵箱,公衆號一個、小程序一個、開放平臺一個、我哪他媽有這麼多郵箱啊,又記不住密碼,下面正題。
準備工作
網站應用微信登錄是基於OAuth2.0協議標準構建的微信OAuth2.0授權登錄系統。
在進行微信OAuth2.在進行微信OAuth2.0授權登錄接入之前,在微信開放平臺註冊開發者帳號,並擁有一個已審覈通過的網站應用,並獲得相應的AppID和AppSecret,申請微信登錄且通過審覈後,可開始接入流程。
image.png
點擊創建網站應用
image.png
按照要求填寫信息,等待審覈通過就可以獲取appid和appsecret
image.png
然後找到回調授權域名這一項 修改成要回調的域名,例如:www.baidu.com 不要加http://或https://
image.png
好了需要提前準備的東西就完事了,下面就是代碼部分了。
image.png
這是完整的調用圖
我這裏用的spring boot項目進行測試的,但是代碼都大致相同
image.png
第一步:請求CODE
這是自己用到的HttpClientUtils工具類
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);
}
/**
* 發送一個 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 響應超時時間,毫秒.
* @return ResponseBody, 使用指定的字符集編碼.
* @throws ConnectTimeoutException 建立鏈接超時異常
* @throws SocketTimeoutException 響應超時
* @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);
}
// 設置參數
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")) {
// 執行 Https 請求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執行 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<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());
}
}
// 設置參數
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")) {
// 執行 Https 請求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 執行 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();
}
}
}
/**
* 發送一個 GET 請求
*
* @param url
* @param charset
* @param connTimeout 建立鏈接超時時間,毫秒.
* @param readTimeout 響應超時時間,毫秒.
* @return
* @throws ConnectTimeoutException 建立鏈接超時
* @throws SocketTimeoutException 響應超時
* @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 {
// 設置參數
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")) {
// 執行 Https 請求.
client = createSSLInsecureClient();
res = client.execute(get);
} else {
// 執行 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;
}
/**
* 創建 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;
}
}
}
微信有兩種方式認證一種是調轉到微信域名下,還一種是直接把二維碼嵌套到自己網站中。
這裏是跳轉到微信的認證方式
首先在頁面做一個簡單的按鈕 觸發事件獲取認證code
<button onclick="login()">微信登錄</button>
js調用部分
<script>
function login() {
$.ajax({
type: "POST",
//這個路徑根據自己的情況填寫
url: "/demo-wechat/wechat/getCode",
success: function (data) {
console.log(data);
if (data.code == 200) {
window.location.href = (data.result);
} else {
alert("認證失敗");
}
},
error: function (data) {
alert("認證失敗");
}
});
}
</script>
後臺代碼url參數都要根據自己的實際情況進行修改
@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");
//回調地址 ,回調地址要進行Encode轉碼
String redirect_uri = "回調地址"
//轉碼
url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));
url.append("&response_type=code");
url.append("&scope=snsapi_login");
HttpClientUtils.get(url.toString(), "GBK");
}
參數 | 是否必填 | 說明 |
---|---|---|
appid | 是 | 應用唯一標識 |
redirect_uri | 是 | 請使用urlEncode對鏈接進行處理 |
response_type | 是 | 填code |
scope | 是 | 網頁應用目前僅填寫snsapi_login即可 |
state | 否 | 安全性相關具體可以參考官方文檔這裏可以不填 |
參數說明
redirect_uri 這個參數是用戶掃碼確認以後微信調用自己的路徑例如:https://www.baidu.com/wechat/callback
拼完路徑可以打印出來看一下 完整的路徑應該是這樣
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就完成了,用戶確認以後回調自己的時候會帶兩個參數,
1.code
2.state
如果調用沒有傳遞state就不會返回state 用戶拒絕了登錄請求,返回的結果不會有code
第二步:通過code獲取access_token
接下來完成回調的方法直接上代碼
/**
* 微信回調
*/
@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");
//這是微信回調給你的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");
}
返回說明
正確的返回:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
錯誤返回樣例:
{"errcode":40029,"errmsg":"invalid code"}
這個時候我們拿到用了用戶的一些必要的信息,剩下的就根據自己具體的業務進行後面的操作吧。
這裏是第二種 認證方式,把二維碼嵌套到自己的網站
這裏只需要改前臺代碼
創建一個放二維碼的容器
<div id="login_container" style="width: 500px;height: 500px;"></div>
導入微信的JS
//我這種寫法是spring boot對應的 根據自己前端框架導入
<script th:src="@{http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js}"></script>
在JS裏面實例這麼一段代碼
var obj = new WxLogin({
id:"login_container",
appid: "appid",
scope: "snsapi_login",
redirect_uri: "回調地址",
state: "",
style: "",//這個是二維碼樣式
href: ""
});
這樣打開這個頁面就會自動加載微信二維碼。掃碼認證後 後面流程不變,返回的也是code,根據code獲取token。
這只是一個最簡單入門的Demo,代碼也有很多需要優化的地方,歡迎大家指正說明,最後感謝大家觀看。
微信開放平臺
轉載:https://www.jianshu.com/p/89c43290d7f6