企业微信扫码登录

一.官方说明及业务流程

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;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>
原文地址:https://www.cnblogs.com/XueTing/p/15070276.html