钉钉 H5微应用开发 免密登录

近2年钉钉很火,很多企业在用,要做一个钉钉的微应用

打算用VUE做前端,springboot做后端。其中比较重要的就是钉钉的免密登录,网上资料比较少

而且很多都过时了,下面我这个官方SDK包是20190926发布的

钉钉微应用开发者文档: https://ding-doc.dingtalk.com/doc#/bgb96b/aw3h75

本博客项目源码: https://github.com/wushu0725/dingtalk-demo

基本流程如下图

钉钉 H5微应用开发 免密登录_第1张图片

相关代码:

前端:

import * as dd from 'dingtalk-jsapi';
try {
  dd.ready(function () {
    // dd.ready参数为回调函数,在环境准备就绪时触发,jsapi的调用需要保证在该回调函数触发后调用,否则无效。
    try {
      dd.runtime.permission.requestAuthCode({
        corpId: self.corpId,
        onSuccess: function (result) {
          //通过corpId,code获取userid
          self.getUserInfo(self.corpId,result.code);
        },
        onFail: function (err) {
          alert(JSON.stringify(err));
        }

      });
    } catch (e) {
      alert(e);
    }

  });

后端:

/**
 * 根据corpId 获取AccessToken
 * @param corpId
 * @return
 * @throws ApiException
 */
private String updateAccessToken(String corpId) throws ApiException {
    defaultDingTalkClient.resetServerUrl(DingTalkConstant.OAPI_GETTOKEN_HOST);
    OapiGettokenRequest request = new OapiGettokenRequest();
    request.setAppkey(DingTalkConstant.APP_KEY);
    request.setAppsecret(DingTalkConstant.APP_SECRET);
    request.setHttpMethod("GET");
    OapiGettokenResponse response =defaultDingTalkClient.execute(request);
    return response.getAccessToken();
}
/**
 * 获取用户详情
 * @param code
 * @param corpId
 * @return JSONObject
 */
public JSONObject getUserInfoDetail(String code,String corpId){
    try {
        String accessToken = updateAccessToken(corpId);
        log.info("获取token:"+accessToken);
        //获取用户钉钉基本信息
        JSONObject userJson = this.getUserInfo(code,accessToken);

        log.info("获取用户ID:"+userJson.getString("userId"));
        //获取用户详细信息
        defaultDingTalkClient.resetServerUrl(DingTalkConstant.OAPI_GETINFODETAIL_HOST);
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(userJson.getString("userId"));
        request.setHttpMethod("GET");
        OapiUserGetResponse response = defaultDingTalkClient.execute(request, accessToken);

        log.info("获取用户详情:"+response.getName());
        JSONObject retrunJson = new JSONObject();
        retrunJson.put("userId",userJson.getString("userId"));
        retrunJson.put("name",response.getName());
        retrunJson.put("mobile",response.getMobile());
        return retrunJson;
    } catch (ApiException e) {
        e.printStackTrace();
    }
    return null;
}

你可能感兴趣的:(前后端分离,学习)