原文地址:https://mp.weixin.qq.com/s/rT0xL9uAdHdZck_F8nyncg
來源:微信公眾號:java碎碎念
1. 微信開放平台操作步驟
微信開放平台地址:https://open.weixin.qq.com
一定要注意,網站集成微信登錄需要在微信開放平台操作,它和微信公眾平台不一樣,雖然雙方最后的用戶唯一標識都是openId,但是是不互通的。如果開發平台想和公眾平台相互通,兩個平台得互相綁定,然后獲取唯一識別的unionId。
下面說下在開放平台上的操作步驟:
1.1 創建“網站應用”
由於到對接PC網站登錄,所以創建“網站應用”,操作截圖如下:
1.2 獲取AppID和AppSecret
等微信審核通過后,會分配對應的AppId,AppSecret需要管理員掃描生成,生成后截圖如下:
2. 開發指南
微信OAuth2.0授權登錄讓微信用戶使用微信身份安全登錄第三方應用或網站,在微信用戶授權登錄已接入微信OAuth2.0的第三方應用后,第三方可以獲取到用戶的接口調用憑證(access_token),通過access_token可以進行微信開放平台授權關系接口調用,從而可實現獲取微信用戶基本開放信息和幫助用戶實現基礎開放功能等,整體流程為:
1. 第三方發起微信授權登錄請求,微信用戶允許授權第三方應用后,微信會拉起應用或重定向到第三方網站,並且帶上授權臨時票據code參數;
2. 通過code參數加上AppID和AppSecret等,通過API換取access_token;
3. 通過access_token進行接口調用,獲取用戶基本數據資源或幫助用戶實現基本操作。
3. 開發實戰
項目中使用了開源項目WxJava,WxJava源碼地址(https://github.com/Wechat-Group/WxJava);
先新建要給Spring Boot項目,新建好項目后,繼續按照下面步驟操作即可。
3.1 pom.xml引入jar包
<!-- 微信登錄jar --> <dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>3.3.0</version> </dependency>
3.2 配置文件添加對應的配置
配置appId和appSecret,application.yml內如下:
wx:
mp:
configs:
- appid: wx1********* secret: *********** token: aesKey: msgDataFormat:
3.3 初始化配置
WxMpProperties.java代碼如下:
@Data
@ConfigurationProperties(prefix = "wx.mp") public class WxMpProperties { 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代碼如下:
@Slf4j @Configuration @EnableConfigurationProperties(WxMpProperties.class) public class WxMpConfiguration { private static Map<String, WxMpService> mpServices = Maps.newHashMap(); public static Map<String, WxMpService> getMpServices() { return mpServices; } @Autowired private WxMpProperties properties; @Autowired private WxMpInRedisConfigStorageMy configStorage; @PostConstruct public void initServices() { // 代碼里 getConfigs()處報錯的同學,請注意仔細閱讀項目說明,你的IDE需要引入lombok插件!!!! final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs(); if (configs == null) { throw new RuntimeException("大哥,拜托先看下項目首頁的說明(readme文件),添加下相關配置,注意別配錯了!"); } mpServices = configs.stream().map(a -> { //redis configStorage.setAppId(a.getAppId()); configStorage.setSecret(a.getSecret()); configStorage.setToken(a.getToken()); configStorage.setAesKey(a.getAesKey()); WxMpService service = new WxMpServiceImpl(); service.setWxMpConfigStorage(configStorage); log.info("配置的appId={}",a.getAppId()); return service; }).collect(Collectors.toMap(s -> s.getWxMpConfigStorage().getAppId(), a -> a, (o, n) -> o)); } }
3.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); } } }
4. 運行效果
4.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
打開上面鏈接后截圖如下:
4.2 微信掃描生成的二維碼
微信掃描后手機端截圖如下:
微信用戶使用微信掃描二維碼並且確認登錄后,PC端會跳轉到
http://www.test.com/redirect/wx12345678/getUserInfo?code=CODE&state=STATE
4.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網站集成微信登錄已經全部實現完成了,有問題歡迎留言溝通哦!