最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解SpringBoot如何實現(xiàn)整合微信登錄

 更新時間:2021年12月22日 10:18:29   作者:LL.LEBRON  
本文主要介紹了SpringBoot實現(xiàn)整合微信登錄的過程詳解,文中的示例代碼介紹的非常詳細,對我們的學習過工作有一定的參考價值,需要的朋友可以關注下

1.準備工作

1.1 獲取微信登錄憑證

前往官網(wǎng)微信開放平臺 (qq.com),完成以下步驟:

1.注冊

2.郵箱激活

3.完善開發(fā)者資料

4.開發(fā)者資質(zhì)認證

5.創(chuàng)建網(wǎng)站應用

1.2 配置文件

在配置文件application.properties添加相關配置信息:

# 微信開放平臺 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 響應超時時間,毫秒.
    * @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);
         }
         // 設置參數(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ù)
         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  響應超時時間,毫秒.
    * @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 {
         // 設置參數(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)站應用微信登錄開發(fā)指南](準備工作 | 微信開放文檔 (qq.com))

2.1 具體流程

  1. 第三方發(fā)起微信授權登錄請求,微信用戶允許授權第三方應用后,微信會拉起應用或重定向到第三方網(wǎng)站,并且?guī)鲜跈嗯R時票據(jù)code參數(shù)
  2. 通過code參數(shù)加上AppID和AppSecret等,通過API換取access_token
  3. 通過access_token進行接口調(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() {

        //微信開放平臺授權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進行URLEncoder編碼
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new GuliException(20001, e.getMessage());
        }
        //設置%s的值
        String url = String.format(
            baseUrl,
            ConstantWxUtils.WX_OPEN_APP_ID,
            redirectUrl,
            "atguigu"
        );

        //重定向到請求微信地址
        return "redirect:" + url;
    }

}

訪問:http://localhost:8160/api/ucenter/wx/login

訪問授權url后會得到一個微信登錄二維碼:

用戶掃描二維碼會看到確認登錄的頁面:

用戶點擊“確認登錄”后,微信服務器會向谷粒學院的業(yè)務服務器發(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 應用唯一標識,在微信開放平臺提交應用審核通過后獲得
secret 應用密鑰AppSecret,在微信開放平臺提交應用審核通過后獲得
code 填寫第一步獲取的code參數(shù)
grant_type 填authorization_code

2.從返回結果獲取兩個值access_token、openid

3.通過openid查詢數(shù)據(jù)庫判斷該用戶是不是第一次登錄

4.如果是第一次登錄,根據(jù)access_token和openid再去訪問微信的資源服務器,獲取用戶信息,存入數(shù)據(jù)庫

5.使用jwt根據(jù)member對象生成token字符串,最后返回首頁面,通過路徑傳遞token字符串

/**
 * 獲取掃描人信息,添加數(shù)據(jù)
 * @param code 類似于手機驗證碼,隨機唯一的值
 * @param state 用于保持請求和回調(diào)的狀態(tài),授權請求后原樣帶回給第三方
 * @return
 */
@GetMapping("callback")
public String callback(String code, String state) {
    try {
        //獲取code值,臨時票據(jù)類似于驗證碼
        //拿著code請求微信固定的地址,得到兩個值
        //1.向認證服務器發(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ā)送請求,得到返回結果(json形式的字符串)
        String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        //從accessTokenInfo字符串獲取兩個值access_token、openid
        //把accessTokenInfo字符串轉(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再去訪問微信的資源服務器,獲取用戶信息
            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)整合微信登錄的詳細內(nèi)容,更多關于SpringBoot整合微信登錄的資料請關注腳本之家其它相關文章!

相關文章

  • Java中異常打印輸出的常見方法總結

    Java中異常打印輸出的常見方法總結

    Java異常是在Java應用中的警報器,下面這篇文章主要給大家介紹了關于Java中異常打印輸出的常見方法的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-07-07
  • 深入理解Netty?FastThreadLocal優(yōu)缺點及實現(xiàn)邏輯

    深入理解Netty?FastThreadLocal優(yōu)缺點及實現(xiàn)邏輯

    本文以線上詭異問題為切入點,通過對比JDK ThreadLocal和Netty FastThreadLocal實現(xiàn)邏輯以及優(yōu)缺點,并深入解讀源碼,由淺入深理解Netty FastThreadLocal
    2023-10-10
  • IDEA如何將Java項目打包成可執(zhí)行的Jar包

    IDEA如何將Java項目打包成可執(zhí)行的Jar包

    在Java開發(fā)中,我們通常會將我們的項目打包成可執(zhí)行的Jar包,以便于在其他環(huán)境中部署和運行,本文將介紹如何使用IDEA集成開發(fā)環(huán)境將Java項目打包成可執(zhí)行的Jar包,感興趣的朋友一起看看吧
    2023-07-07
  • HTTP 415錯誤-Unsupported media type詳解

    HTTP 415錯誤-Unsupported media type詳解

    這篇文章主要介紹了HTTP 415錯誤-Unsupported media type詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • SpringBoot3.x中spring.factories?SPI?服務發(fā)現(xiàn)機制的改變問題小結

    SpringBoot3.x中spring.factories?SPI?服務發(fā)現(xiàn)機制的改變問題小結

    spring.factories其實是SpringBoot提供的SPI機制,底層實現(xiàn)是基于SpringFactoriesLoader檢索ClassLoader中所有jar引入的META-INF/spring.factories文件,這篇文章主要介紹了SpringBoot3.x中spring.factories?SPI?服務發(fā)現(xiàn)機制的改變,需要的朋友可以參考下
    2023-05-05
  • 如何解決Mybatis--java.lang.IllegalArgumentException: Result Maps collection already contains value for X

    如何解決Mybatis--java.lang.IllegalArgumentException: Result Maps

    這兩天因為項目需要整合spring、struts2、mybatis三大框架,但啟動的時候總出現(xiàn)這個錯誤,困擾我好久,折騰了好久終于找到問題根源,下面小編給大家分享下問題所在及解決辦法,一起看看吧
    2016-12-12
  • 詳解SpringBoot中JdbcTemplate的事務控制

    詳解SpringBoot中JdbcTemplate的事務控制

    JdbcTemplate是spring-jdbc提供的數(shù)據(jù)庫核心操作類,那對JdbcTemplate進行事務控制呢,本文就詳細的介紹一下
    2021-09-09
  • Java8中的Stream流式操作教程之王者歸來

    Java8中的Stream流式操作教程之王者歸來

    這篇文章主要給大家介紹了關于Java8中Stream流式操作的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Java8具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-09-09
  • 深入了解Java GC的工作原理

    深入了解Java GC的工作原理

    下面小編就為大家?guī)硪黄钊肓私釰ava GC的工作原理。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-06-06
  • SpringBoot增量/瘦身部署jar包的方式

    SpringBoot增量/瘦身部署jar包的方式

    SpringBoot 項目的部署一般采用全量jar 包方式部署相關項目,如果我們對相關的Contrller層進行相關業(yè)務調(diào)整就需要重新編譯全量jar 包太麻煩了,所以本文給大家介紹了使用SpringBoot 的增量/瘦身部署方式,需要的朋友可以參考下
    2024-01-01

最新評論

瑞丽市| 涟源市| 清徐县| 苍南县| 调兵山市| 社旗县| 望江县| 龙山县| 合阳县| 尉氏县| 连州市| 大城县| 盘山县| 东乡县| 巩留县| 灌云县| 安阳县| 哈密市| 印江| 历史| 唐山市| 丽江市| 白水县| 长宁县| 海口市| 铁岭县| 高雄市| 小金县| 三穗县| 新乡市| 秦皇岛市| 永年县| 垣曲县| 页游| 若尔盖县| 宁陵县| 沁源县| 于田县| 常德市| 郸城县| 库尔勒市|