需求
在钉钉里面内嵌一个自定义的h5应用,点击微应用获取到用户信息,实现微应用免登录访问

vue + 钉钉

  • 先安装 npm install dingtalk-jsapi --save

vue根据钉钉企业id获取微应用免登授权码code

import * as dd from 'dingtalk-jsapi'

/* eslint-disable */
export function GetCode(callback) {
  const corpId = 'xxxxxxxxx' //钉钉企业id
  if (dd.env.platform !== 'notInDingTalk') {
    dd.ready(() => {
      dd.runtime.permission.requestAuthCode({
        corpId: corpId,
        onSuccess: (info) => {
          callback(info.code)
        },
        onFail: (err) => {
          alert('fail')
          alert(JSON.stringify(err))
        }
      })
    })
  }
}

使用
import { GetCode } from '@/views/dingTalk/Dingding.js'

GetCode((code: any) => {
  console.log(code, 123)
})

获取用户信息【建议用户信息保存在前端缓存中(dd.setStorage)或者cookie中,避免每次进入应用都调用钉钉接口进行免登。】

 async loadData() {
    const userInfos = this.$cookie.get('userinfos')
    if (!userInfos) {
      await GetCode((code: any) => {
        this.serviceType = code
      })
      // 获取企业内部应用的access_token,
      let access_token = await axios
        .get(
          '/gettoken?appkey=xxxx&appsecret=xxxx'
        )
        .then((response: { data: any }) => {
          return response.data.access_token
        })
        .catch((err: Error) => {})
      // 通过免登码和access_token获取用户信息
      let userId = await axios
        .get(
          `/user/getuserinfo?access_token=${access_token}&code=${this.serviceType}`
        )
        .then((res: { data: any }) => {
          return res.data.userid
        })
        .catch((err: Error) => {})
      // 通过userId和access_token获取用户详情
      axios
        .get(`/user/get?access_token=${access_token}&userid=${userId}`)
        .then((res: { data: any }) => {
          this.message = JSON.stringify(res.data)
          this.$cookie.set('userinfos', JSON.stringify(res.data), {
            expires: 7
          })
        })
        .catch((err: Error) => {})
    } else {
      this.message = '获取缓存在cookie中的数据' + userInfos
    }
  }

vue.config.js 配置

devServer: {
 proxy: {
   '/': {
     target: 'https://oapi.dingtalk.com/',
     autoRewrite: true,
     cookieDomainRewrite: {
       '*': ''
     },
     pathRewrite: {
       ['^' + '/']: ''
     }
   }
 }
}
Logo

前往低代码交流专区

更多推荐