Preface
Recently, the company is doing small program development, in which the micro-signal binding Weichat logon personal feel good, want to record it.
This document is about the related use of the Weichat login widget.
Development preparation
1. Wechat Developer Tools (Front-end Development Utilities)
2.idea (back-end development)
3. JDK1.8 (this is optional)
4.spring boot project (in fact, the interface for handling Wechat requests, as long as it is the interface, you are free)
Circulation chart
Process introduction
Note: The developer server is the same as the developer business server (equivalent to controller and service)
Widget - > widget: wx.login() to get code (login credentials) Applet - > applet: wx.getUserInfo() gets {encryptedData, iv} Program - > Developer Server: Send Request (code, encrypted Data, iv) Developer Server - > Micromessaging Interface Service: Send Request (appid,secret,js_code,grant_type) Wechat Interface Service - > Developer Server: Response Data (openId,session_key) Developer Server - > Developer Business Server: Encrypted Data, session_key, iv, UTF-8 Developer Server - > Developer Business Server: Business Processing (to determine whether there is a database such as openId) Developer Server - > Small Program: 1. Existence, Return to Login Successfully Developer Server - > applet: 2. No, return to the first login needs to bind the mobile phone or registration note: put the Wechat message into the cache for later use (key) Program - > Developer Server: Send Request (Data: Mobile Phone Number) Developer Server - > Small Program: Send Verification Code Program - > Developer Server: Send Request (Data: Mobile Phone Number, Validation Code, Cache key) Developer Server - > Developer Business Server: Check Mobile Verification Code Information (Yes: Next No: End) Developer Server - > Developer Server: Determining whether a mobile phone number exists Developer Server - > Developer Business Server: 1. Existence: The mobile account is bound to the data of the Wechat cache key. Developer Server - > applet: 1.1 login Developer Server - > Developer Business Server: 1. No Developer Server - > applet: 1.1 prompt unregistered Program - > Developer Server: Initiate Request (Registered User Data) Developer Server - > Developer Business Server: Adding Accounts to Wechat Information Binding Developer Server - > applet: 2.1 login
Small Program Side
html
<button open-type="getUserInfo" class="wxbutton" style="background-color:#fff;border-radius:0px;color:#6e6d6b;font-size:29rpx;" bindgetuserinfo="wxLogin"> <image src='/images/weixin.png' style="height:40rpx;width:40rpx;"></image> //Wechat login </button>
js
/User login function userLogin() { wx.checkSession({ success: function () { //Existent landing state }, fail: function () { //No landing state exists //Calling login function can actually use the following } }) }
wxLogin: function (e) { if (e.detail.userInfo == undefined) { app.globalData.hasLogin = false; util.showErrorToast('Wechat login failed'); return; } var that = this // Sign in wx.login({ success: res => { // Send res.code to the background for openId, session Key, unionId var code = res.code// Logon Credentials //---------------------------------------------------------------------- //Getting User Information wx.getUserInfo({ //When you get user information, a pop-up box pops up to see if authorization is allowed. //Click here on the way to allow departure success: function (res2) { //that.globalData.userInfo = res2.userInfo // Prepare the data (the following parameters are required parameters, please don't ask why, look at the documentation) var data = { encryptedData: res2.encryptedData, iv: res2.iv, code: code } // Request your own server (here I encapsulate the request request request with promise, and I'll share the method below) var url ="/api-login-shiro/login/getWexInfo"; httpPost(url, data, function (res3) { console.log(res3); }) }, fail: function (res2) { app.globalData.hasLogin = false; util.showErrorToast('Wechat login failed'); } }); //---------------------------------------------------------------------- } }) }
Cofing.js (configuration file for applets)
const localhost = 'http://169.254.235.123'; const config = { hostApi: `http://localhost:8200 `, // Your domain name // hostApi: `${localhost}:9120 `, // your domain name hostFile: `${localhost}:8080/files/thumbnails/`, //file httpCode:{ success:'000000000' }, navigationBar: { backgroundColor: "#0D88FF", textStyle: "white" }, checkFrequency: { // 2:day, 3:week, 4:month, 5:season, 6:year 2: { field: 'dayCount',label:'day'}, 3: { field: 'weekCount', label:'week'}, 4: { field: 'monthCount', label:'month'}, 5: { field: 'quarterCount', label:'season'}, 6: { field: 'yearCount', label:'year'} } } module.exports = config
Server
@PostMapping("/getWexInfo") @ApiOperation(value = "Acquisition based on encrypted files UnionID Equivalent information") @ApiImplicitParam(name = "wexDTO", value = "List of parameters:" + "<br/>iv: iv Initial Vector Requirements for Encryption Algorithms " + "<br/>code: wx.login When acquired, later used serssion_key Must fill " + "<br/>encryptedData: Ciphertext, encrypted data must be filled in " , dataType = "WexDTO", required = true) public ResultResponse getWexInfo(@Validated(WexDTO.ValidSave.class) @RequestBody WexDTO wexDTO, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return ResultResponse.wrap(bindingResult.getFieldError().getDefaultMessage()); } ResultResponseresultResponse = this.accountService.getWexInfo(wexDTO); if (resultResponse.getCode().equals(IfConstant.SERVER_SUCCESS.getCode())) { Account account = (Account) resultResponse.getData(); AccountDTO accountDTO = new AccountDTO(); accountDTO.setMobilephone(account.getMobilephone()); accountDTO.setPassword(account.getPassword()); return loginQyForApp(accountDTO, bindingResult); } return resultResponse; }
Attention: Just thinking
Lack of classes: WexDTO, accountDTO, ResultResponse,
@Value("${appid}") public String appid; @Value("${secret}") public String secret; @Override public ResultResponse getWexInfo(WexDTO wexDTO) { try { String url = "https://api.weixin.qq.com/sns/jscode2session"; Map<String, String> requestUrlParam = new HashMap<String, String>(); requestUrlParam.put("appid", appid); //appId in Developer Settings requestUrlParam.put("secret", secret); //appSecret in Developer Settings requestUrlParam.put("js_code", wexDTO.getCode()); //The widget calls the code returned by wx.login requestUrlParam.put("grant_type", "authorization_code"); //The default parameter authorization_code String result = HttpUtils.sendPost(url,requestUrlParam); if (null != result && !"".equals(result)) { JSONObject returnInfoObject =JSON.parseObject(result); String openid = returnInfoObject.getString("openid"); String session_key = returnInfoObject.getString("session_key"); String decryptResult = AesCbcUtil.decrypt(wexDTO.getEncryptedData(), session_key, wexDTO.getIv(), "UTF-8"); JSONObject userInfo = HttpUtils.getUserInfo(wexDTO.getEncryptedData(), session_key, wexDTO.getIv()); if (null != userInfo ) { System.out.println(userInfo); System.out.println(userInfo.get("openId")); Account account=new Account(); account.setIsDelete(0); account.setOpenid(userInfo.getString("openId")); /*if(userInfo.getString("unionid")!=null){ account.setUnionid(userInfo.getString("unionid")); }*/ //Determine whether openId exists in the database if(accountMapper.selectCount(account)==1){ return ResultResponse.wrap(accountMapper.selectOne(account),IfConstant.SERVER_SUCCESS); }else{ Long key=IdWorkerBuider.IDWORKER.nextId(); redisService.set(key.toString(),userInfo.toJSONString()); redisService.expire(key.toString(), VALID_MINUTE * 60); return ResultResponse.wrap(key,IfConstant.USER_IS_RE_REGISTER); } } } }catch (Exception e){ e.printStackTrace(); } return null; }
There's more missing here.
Forget it: don't do this.
> Note: If you see any questions here, you can leave a message.