利用WxJava實現網站集成微信登錄功能,核心代碼竟然不超過10行


最近網站PC端集成微信掃碼登錄,踩了不少坑,在此記錄下實現過程和注意事項。

本文目錄

一、微信開放平台操作步驟

  1.創建“網站應用”

  2.獲取AppID和AppSecret

二、開發指南三、開發實戰

  1、pom.xml引入jar包

  2、配置文件添加對應的配置

  3、初始化配置

  4、控制層核心代碼

四、運行效果

  1.構造pc端鏈接

  2.微信掃描生成的二維碼

  3.獲取微信用戶信息

一、微信開放平台操作步驟

微信開放平台地址:https://open.weixin.qq.com

一定要注意,網站集成微信登錄需要在微信開放平台操作,它和微信公眾平台不一樣,雖然雙方最后的用戶唯一標識都是openId,但是是不互通的。如果開發平台想和公眾平台相互通,兩個平台得互相綁定,然后獲取唯一識別的unionId。

下面說下在開放平台上的操作步驟:

1.創建“網站應用”

由於到對接PC網站登錄,所以創建“網站應用”,操作截圖如下:



新建網站應用截圖

2.獲取AppID和AppSecret

等微信審核通過后,會分配對應的AppId,AppSecret需要管理員掃描生成,生成后截圖如下:

二、開發指南

微信OAuth2.0授權登錄讓微信用戶使用微信身份安全登錄第三方應用或網站,在微信用戶授權登錄已接入微信OAuth2.0的第三方應用后,第三方可以獲取到用戶的接口調用憑證(access_token),通過access_token可以進行微信開放平台授權關系接口調用,從而可實現獲取微信用戶基本開放信息和幫助用戶實現基礎開放功能等,整體流程為:

1. 第三方發起微信授權登錄請求,微信用戶允許授權第三方應用后,微信會拉起應用或重定向到第三方網站,並且帶上授權臨時票據code參數;
2. 通過code參數加上AppID和AppSecret等,通過API換取access_token;
3. 通過access_token進行接口調用,獲取用戶基本數據資源或幫助用戶實現基本操作。

三、開發實戰

項目中使用了開源項目WxJava,WxJava源碼地址(https://github.com/Wechat-Group/WxJava);

先新建要給Spring Boot項目

新建好項目后,繼續按照下面步驟操作即可。

1、pom.xml引入jar包

<!-- 微信登錄jar -->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-mp</artifactId>
    <version>4.2.0</version>
</dependency>

2、配置文件添加對應的配置

配置appId和appSecret,application.yml內如下:

wx:
mp:
useRedis: true
configs:
- appId: xxxxxxxxxxxxx
secret: xxxxxxxxx
token: xxxxxxxxxxxx
aesKey: xxxxxxxxxxx

3、初始化配置

WxMpProperties.java代碼如下:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

/**
 * wechat mp propertie【微信公眾號】
 *
 * @author xiaoqiang
 */
@Data
@ConfigurationProperties(prefix = "wx.mp")
public class WxMpProperties {
    /**是否使用redis存儲access token*/
    private boolean useRedis;

    /**redis 配置*/
    private RedisConfig redisConfig;

    @Data
    public static class RedisConfig {
        /**redis服務器 主機地址*/
        private String host;

        /**redis服務器 端口號*/
        private Integer port;
    }

    /**多個公眾號配置信息*/
    private List<MpConfig> configs;

    @Data
    public static class MpConfig {
        /**設置微信公眾號的appid*/
        private String appId;

        /**設置微信公眾號的app secret*/
        private String secret;

        /**設置微信公眾號的token*/
        private String token;

        /**設置微信公眾號的EncodingAESKey*/
        private String aesKey;
    }
}

 

WxMpConfiguration.java代碼如下:

import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.config.impl.WxMpRedisConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 公眾號配置
 * weChat mp configuration
 *
 * @author xiaoqiang
 */
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {
    private final WxMpProperties properties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean
    public WxMpService wxMpService() {
     // 代碼里 getConfigs()處報錯的同學,請注意仔細閱讀項目說明,你的IDE需要引入lombok插件!!!!
final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs(); if (configs == null) { throw new RuntimeException("添加相關配置"); } WxMpService service = new WxMpServiceImpl(); service.setMultiConfigStorages(configs .stream().map(a -> { WxMpDefaultConfigImpl configStorage; if (this.properties.isUseRedis()) { configStorage = new WxMpRedisConfigImpl(new RedisTemplateWxRedisOps(redisTemplate), a.getAppId()); } else { configStorage = new WxMpDefaultConfigImpl(); } configStorage.setAppId(a.getAppId()); configStorage.setSecret(a.getSecret()); configStorage.setToken(a.getToken()); configStorage.setAesKey(a.getAesKey()); return configStorage; }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o))); return service; } }

4、控制層核心代碼

@Slf4j
@Controller
@RequestMapping("/redirect/{appid}")
public class WxRedirectController {

    /**
     * 獲取用戶信息
     *
     */
    @RequestMapping("/getUserInfo")
    public void getBase(HttpServletRequest request, HttpServletResponse response, @PathVariable String appid, @RequestParam("code") String code) {
        WxMpService mpService = WxMpConfiguration.getMpServices().get(appid);
        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            log.info("accessToken={}", JSON.toJSONString(accessToken));
            WxMpUser wxMpUser = mpService.oauth2getUserInfo(accessToken, null);
            log.info("wxMpUser={}", JSON.toJSONString(wxMpUser));
        } catch (Exception e) {
            log.error("獲取用戶信息異常!", e);
        }
    }
}

 

四、運行效果

1.構造pc端鏈接

https://open.weixin.qq.com/connect/qrconnect?appid=wx12345678redirect_uri=http%3a%2f%2fwww.test.com%2fredirect%2fwx12345678%2fgetUserInfo&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect

打開上面鏈接后截圖如下:


2.微信掃描生成的二維碼

微信掃描后手機端截圖如下:


微信用戶使用微信掃描二維碼並且確認登錄后,PC端會跳轉到

http://www.test.com/redirect/wx12345678/getUserInfo?code=CODE&state=STATE

3.獲取微信用戶信息

控制層代碼可以接收到上code和state參數,根據這兩個參數可以獲取微信用戶信息,請求過來后打印用戶信息的日志如下:

[http-nio-8104-exec-2] INFO  c.t.m.s.c.WxRedirectController - accessToken={"accessToken":"24_vWnvRSV9vmR7qOqhJKRoER93bhsPg","expiresIn":7200,"openId":"oRXsdsUh6scaKof3D1I4d3c","refreshToken":"24_WmknxCn9ff2Pl2xhLFw-kY96p6zgiqFJy8LMIOP_CaMZOHEM","scope":"snsapi_login","unionId":"oJxUkwfFOSyu1oC6oF2h6pTI"}
[http-nio-8104-exec-2] INFO  c.t.m.s.c.WxRedirectController - wxMpUser={"city":"","country":"","headImgUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4ibeAsuoVIf3qr4QxjnNWh4Q1WiawCFNfzkGMzVqubPOnr0hA3Micwsu1LtblQ7phImdYSC2nic6OUicQ/132","language":"","nickname":"阿白","openId":"oRXsdsUh6scaKof3D1I4d3c","privileges":[],"province":"","sex":0,"sexDesc":"未知","unionId":"oaDUkwVfCpMJOSyu1oC2oF2h6pTI"}
到此PC網站集成微信登錄已經全部實現完成了,有問題歡迎留言溝通哦!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM