钉钉小程序连接后台

1、下载官方提供后台java代码

 https://github.com/open-dingtalk/org-mini-program-tutorial-java.git

1.1idea 打开后编辑AppCondtant.java

在钉钉开发者后台找到appkey和appsecret,写入appCondant.java中,进行绑定。
在这里插入图片描述

在这里插入图片描述

1.2分析代码

(1)constant包中存放各种静态常量
(2)mainController 根据授权码 获取登录权限

  public RpcServiceResult login(@RequestParam(value = "authCode") String authCode) {
        try {
            // 1. 获取用户id
            String userId = userManager.getUserId(authCode);
            // 2. 获取用户名称
            String userName = userManager.getUserName(userId);
            // 3. 返回用户身份
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userId", userId);
            resultMap.put("userName", userName);
            return RpcServiceResult.getSuccessResult(resultMap);
        } catch (Exception ex) {
            return RpcServiceResult.getFailureResult("-1", "login exception");
        }
    }

UserMannager 相当于service业务层

    public String getUserId(String authCode) throws ApiException {
        // 1. 获取access_token
        String accessToken = AccessTokenUtil.getAccessToken();
        // 2. 获取用户信息
        DingTalkClient client = new DefaultDingTalkClient(UrlConstant.GET_USER_INFO_URL);
        OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
        req.setCode(authCode);
        OapiV2UserGetuserinfoResponse rsp = client.execute(req, accessToken);

        // 3. 返回用户id
        return rsp.getResult().getUserid();
    }

    /**
     * 根据用户id获取用户名称
     *
     * @param userId 用户id
     * @return
     */
    public String getUserName(String userId) throws ApiException {
        // 1. 获取access_token
        String accessToken = AccessTokenUtil.getAccessToken();

        // 2. 获取用户详情
        DingTalkClient client = new DefaultDingTalkClient(UrlConstant.USER_GET_URL);
        OapiV2UserGetRequest req = new OapiV2UserGetRequest();
        req.setUserid(userId);
        req.setLanguage("zh_CN");
        OapiV2UserGetResponse rsp = client.execute(req, accessToken);

        // 3. 返回用户名称
        return rsp.getResult().getName();
    }

AccessTokenUtil

public static String getAccessToken() throws ApiException {
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.GET_ACCESS_TOKEN_URL);
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(AppConstant.APP_KEY);
        request.setAppsecret(AppConstant.APP_SECRET);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        return response.getAccessToken();
    }

2钉钉内网穿透

使用钉钉内网穿透工具生成公网域名进行测试,
工具网址:https://github.com/open-dingtalk/pierced.git
cmd 打开
在这里插入图片描述
执行

ding -config=ding.cfg -subdomain=***** 端口号

例如:ding -config=ding.cfg -subdomain=dingdinga 4444
在这里插入图片描述
成功之后访问:http://dingdinga.vaiwan.com/4444会映射到http://127.0.0.1:8080/xxxxx

3钉钉开发者后台安全中心配置域名

在这里插入图片描述

4前端代码下载

https://github.com/open-dingtalk/org-mini-program-tutorial-front-end.git

4.1编辑index.js 修改domain为安全域名

在这里插入图片描述

5运行后台程序成功 获取用户信息

在这里插入图片描述

6从后台查询数据

在此基础上连上数据库使小程序显示数据

6.1配置java程序

资源文件 application.properties

server.port = 4444
#server.servlet.context-path=/dingtest
#数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/dz?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#mybatis 扫描包配置
mybatis.mapper-locations=classpath*:/mapper/**/*.xml

6.2前端代码编辑

在app.json中增加一个下方导航栏

{
  "pages": [
    "page/index/index",
    "page/query/index"
  ],
  "window": {
    "enableWK": "YES",
    "enableDSL": true,
    "defaultTitle": "东方国信",
    "backgroundColor": "#fefefe",
    "pullRefresh": false,
    "allowsBounceVertical": true
  },
  "tabBar": {
    "textColor": "#404040",
    "selectedColor": "#108ee9",
    "backgroundColor": "#F5F5F9",
    "items": [
       {
        "pagePath": "page/index/index",
        "icon": "image/icon_component.png",
        "activeIcon": "image/icon_component_HL.png",
        "name": "登录"
      },
      {
        "pagePath": "page/query/index",
        "icon": "image/icon_API.png",
        "activeIcon": "image/icon_API_HL.png",
        "name": "数据查询"
      }
      
    ]
  },
  "debug": true
}

新建一个query文件夹 index.acss中写样式

.row{
    font-size: 30rpx;
    margin-bottom: 10rpx;
    margin-left: 10rpx;
}
/* @import '../../components/list/index.acss'; */

.table {

border: 1px solid rgb(128, 28, 28);

}

.tr {

display: flex;

width: 100%;

justify-content: center;

height: 1rem;

align-items: center;

}

.td {

width:30%;

justify-content: center;

text-align: center;


}

.bg-w{

background: snow;

}

.bg-g{

background: #E6F3F9;

}

.th {

width: 40%;

justify-content: center;

background: #3366FF;

color: #fff;

display: flex;

height: 1rem;

align-items: center;

}

index.axml中写 写页面 view

<view>
  <button type="warn" size="" onTap="query"> 数据查询</button>

  <view class="table"  hidden="{{hideList}}">

    <view class="tr bg-w">

      <view class="th">地区编码</view>
      <view class="th">产品名称</view>

      <view class="th">节点</view>

      <view class="th ">内存</view>

    </view>

    <block a:for="{{dataList}}" a:key="{{code}}">

      <view class="tr bg-g">

        <view class="td">{{item.regionCode}}</view>
        <view class="td">{{item.instanceName}}</view>
        <view class="td">{{item.nodeNumber}}</view>
        <view class="td">{{item.memory}}</view>

      </view>

     

    </block>

  </view>

</view>

index.js中写逻辑

 let app = getApp();


// 内网穿透工具: https://developers.dingtalk.com/document/resourcedownload/http-intranet-penetration?pnamespace=app
// 替换成开发者后台设置的安全域名
let domain = "http://dingdinga.vaiwan.com";
let url = domain + '/instancesList';
Page({
    data:{

        hideList: true,
    },
    query() {
        dd.showLoading();
        dd.httpRequest({
                    url: url,                                                
                    success: (res) => {
                        if (res && res.data.success) {
                            console.log('httpRequest success --->', res);
                            // let regionCode = res.data.data.regionCode;
                            // let nodeNumber = res.data.data.nodeNumber;
                            // let memory = res.data.data.memory;
                            // let instanceName = res.data.data.RegionName;
                            let dataList = res.data.data;
                            this.setData({
                                // regionCode:regionCode,
                                // instanceName:instanceName,
                                // memory:memory,
                                // nodeNumber:nodeNumber,
                                dataList:dataList,

                                hideList:false
                            })
                        } else {
                            console.log("httpRequest failed --->", res);
                            dd.alert({content: JSON.stringify(res)});
                        }
                    },
                    
                    fail: (res) => {
                        console.log("httpRequest failed --->", res);
                        dd.alert({content: JSON.stringify(res)});
                    },
                    complete: (res) => {
                        dd.hideLoading();
                    }
                    
                });
    },
    onLoad(){
        let _this = this;
        this.setData({
          
        })        
    }
})

6.3成果

在这里插入图片描述


版权声明:本文为weixin_44019875原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。