一.官方說明及業務流程
1.基礎配置:
參照官方文檔:https://work.weixin.qq.com/api/doc/90000/90135/91025
2.企業微信掃碼登錄流程:
二.具體實現
1.填寫pom文件
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.18</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.74</version> </dependency> </dependencies>
2.工具類
import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.commons.io.IOUtils; /** * 遠程調用接口 */ public class JHttpUtils { public static String doGet(String url, String charset, Map<Object, Object> params) { StringBuffer param = new StringBuffer(); int i = 0; for (Object key : params.keySet()) { if (i == 0) param.append("?"); else param.append("&"); param.append(key).append("=").append(params.get(key)); i++; } url += param; String result = null; HttpClient httpClient = HttpClients.createSystem(); try { HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); result = IOUtils.toString(instream, charset); } } catch (IOException e) { e.printStackTrace(); } return result; } }
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.entity.AccessToken; import com.entity.Result; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class WeiXinQiYeUtil { //企業ID private final String corpid = "wx5e494ca5e5c0e161"; //應用的憑證密鑰 private final String corpsecret = "juaDSt6I-yqTXvevI38vrQtoaV3nz1FoSoNrLm2WpTk"; //應用ID private final String agentId = "1000004"; // 獲取token的url public final String accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"; // 獲取用戶信息的url public final String oauth2Url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE&agentid=AGENTID"; /** * 獲取 accessToken * @return */ public AccessToken getAccessToken() { Map<Object, Object> params = new HashMap<>(); params.put("corpid", corpid); params.put("corpsecret", corpsecret); String token = JHttpUtils.doGet(accessTokenUrl, "UTF-8", params); AccessToken accessToken = JSON.parseObject(token, AccessToken.class); return accessToken; } public String getUserId(String token, String code) { Result result = new Result(); String menuUrl = oauth2Url.replace("ACCESS_TOKEN", token).replace("CODE", code).replace("AGENTID", agentId + ""); String userinfo = JHttpUtils.doGet(menuUrl,"UTF-8", new HashMap()); JSONObject jsonObject = JSON.parseObject(userinfo); return jsonObject.getString("UserId"); } }
3.實體類
import lombok.Data; @Data public class AccessToken { // 錯誤code private String errcode; // 錯誤msg private String errmsg; // 獲取到的憑證 private String accessToken; // 憑證有效時間,單位:秒 private int expiresIn; }
import lombok.Data; @Data public class Result { private String UserId; //成員UserID private String DeviceId; //手機設備號(由企業微信在安裝時隨機生成,刪除重裝會改變,升級不受影響) private String errcode; //返回碼 private String errmsg; //對返回碼的文本描述內容 }
4.控制層
import com.entity.AccessToken; import com.service.UserService; import com.utils.WeiXinQiYeUtil; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; import java.util.Set; @RestController @AllArgsConstructor @RequestMapping("wx") public class WechatController { private final UserService userService; private final WeiXinQiYeUtil weiXinQiYeUtil; /** * 掃碼回調接口 * 實現細節: * 1.遠程調用獲取 accessToken * 2.遠程調用獲取 userId * 3.通過userId實現自己的業務細節 * @param code * @return */ @GetMapping("redirect") public Map<String,Object> redirect(@RequestParam(value = "code", required = true) String code){ AccessToken accessToken =weiXinQiYeUtil.getAccessToken(); String userId = weiXinQiYeUtil.getUserId(accessToken.getAccessToken(),code); //這里模擬從數據中獲取數據 Set<String> roles = userService.getRoles(userId); Set<String> menus = userService.getMenus(userId); Map<String,Object> result = new HashMap<>(); result.put("roles",roles); result.put("menus",menus); return result; } }
5.業務層,模擬從數據庫中拿數據
import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.Set; @Service public class UserService { public Set<String> getRoles(String userId){ Set<String> set = new HashSet<>(); set.add("admin"); set.add("test"); return set; } public Set<String> getMenus(String userId){ Set<String> set = new HashSet<>(); set.add("/user"); set.add("/role"); set.add("/menu"); return set; } }
6.html代碼,用來顯示二維碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="test" style="height:100px;width:100px;"></div> </body> <script> !function(a,b,c){function d(c){var d=b.createElement("iframe"),e="https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid="+c.appid+"&agentid="+c.agentid+"&redirect_uri="+c.redirect_uri+"&state="+c.state+"&login_type=jssdk";e+=c.style?"&style="+c.style:"",e+=c.href?"&href="+c.href:"",d.src=e,d.frameBorder="0",d.allowTransparency="true",d.scrolling="no",d.width="300px",d.height="400px";var f=b.getElementById(c.id);f.innerHTML="",f.appendChild(d),d.onload=function(){d.contentWindow.postMessage&&a.addEventListener&&(a.addEventListener("message",function(b){ b.data&&b.origin.indexOf("work.weixin.qq.com")>-1&&(a.location.href=b.data)}),d.contentWindow.postMessage("ask_usePostMessage","*"))}}a.WwLogin=d}(window,document); window.WwLogin({ "id" : "test", "appid" : "wx5e494ca5e5c0e161", "agentid" : "1000004", "redirect_uri" :"你的回調接口地址", "state" : "weblogin@gyoss9", "href" : "", }); </script> </html>