1. 程式人生 > >【微信開放平臺】微信第三方掃碼登入(親測可用)

【微信開放平臺】微信第三方掃碼登入(親測可用)

開放平臺需要企業認證才能註冊,正好這次公司提供了一個賬號,調通以後,就順便寫一篇部落格吧。

公眾平臺與開放平臺的區別

微信開放平臺

主要面對移動應用/網站應用開發者,為其提供微信登入、分享、支付等相關許可權和服務。

微信公眾平臺

微信公眾平臺用於管理、開放微信公眾號(包括訂閱號、服務號、企業號),簡單的說就是微信公眾號的後臺運營、管理系統。

這裡想吐槽一下,微信基本註冊全都要郵箱,公眾號一個、小程式一個、開放平臺一個、我哪他媽有這麼多郵箱啊,又記不住密碼,下面正題。

官方文件連結

準備工作

網站應用微信登入是基於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,程式碼也有很多需要優化的地方,歡迎大家指正說明,最後感謝大家觀看。



作者:路西法Lucifer丶
連結:https://www.jianshu.com/p/89c43290d7f6
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。