对接钉钉应用的开发过程中遇到的问题
1、在header里放入钉钉监控中心代码块
<script>
var isDingtalk = navigator && /DingTalk/.test(navigator.userAgent);
var isProductEnv = window &&window.location &&window.location.host
&& window.location.host.indexOf('127.0.0.1')===-1
&& window.location.host.indexOf('localhost')===-1
&& window.location.host.indexOf('192.168.')===-1
// 如果有其它测试域名,请一起排掉,减少测试环境对生产环境监控的干扰
if (isProductEnv) { !(function(c,i,e,b){var h=i.createElement("script");
var f=i.getElementsByTagName("script")[0];
h.type="text/javascript";
h.crossorigin=true;
h.onload=function(){c[b]||(c[b]=new c.wpkReporter({bid:"dta_2_118828"}));
c[b].installAll()};
f.parentNode.insertBefore(h,f);
h.src=e})(window,document,"https://g.alicdn.com/woodpeckerx/jssdk??wpkReporter.js","__wpk");
}</script>
<script type="text/javascript">
; (function () {
if (sessionStorage.getItem('eruda') !== 'true') return;
var src = 'https://cdn.bootcss.com/vConsole/3.2.0/vconsole.min.js';
document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>');
document.write('<scr' + 'ipt>var vConsole = new VConsole();</scr' + 'ipt>');
})();
</script>
2、vue开发install 钉钉dingtalk-jsapi
npm install dingtalk-jsapi --save
在需要的地方引入
import*asddfrom'dingtalk-jsapi';
3、在APP.VUE中添加鉴权
<script>
import * as dd from 'dingtalk-jsapi'
import api from './api/dd'
export default {
created(){
this.getAuth()
},
watch:{
$route(to,from){
// console.log(from.path) // 从哪来
// console.log(to.path) // 到哪去
this.getAuth()
}
},
methods: {
getAuth(){
let params = {
url: 'http://10.xx.xx.xx/meal/', // 这个地址要与网站访问地址保持一致
appTypeEnum: 'MEAL_ORDER'
}
api.queryAuthSign(params).then((res) => {
dd.config({
agentId: res.data.data.agentId, // 必填,微应用ID
corpId: res.data.data.corpId,//必填,企业ID
timeStamp: res.data.data.timeStamp, // 必填,生成签名的时间戳
nonceStr: res.data.data.nonceStr, // 必填,自定义固定字符串。
signature: res.data.data.signature, // 必填,签名
type:0, //选填。0表示微应用的jsapi,1表示服务窗的jsapi;不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
jsApiList : [
'biz.util.uploadAttachment', // 上传附件到钉盘/从钉盘选择文件
'biz.cspace.preview', // 图片预览
] // 必填,需要使用的jsapi列表,注意:不要带dd。
});
dd.error(function (err) {
alert('dd error: ' + JSON.stringify(err));
console.log('dd error: ' + JSON.stringify(err));
})//该方法必须带上,用来捕获鉴权出现的异常信息,否则不方便排查出现的问题
})
}
},
}
</script>
4、钉钉应用免登陆的实现
<script>
import axios from "axios";
import { corpidLogin, isComToken } from "@/api/login";
import Cookies from "js-cookie";
import { getToken, setToken, removeToken } from '@/utils/auth'
import { encrypt, decrypt } from "@/utils/jsencrypt";
import * as dd from "dingtalk-jsapi"; // 此方式为整体加载,也可按需进行加载
export default {
render: function(h) {
return h(); // avoid warning message
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
},
},
name: "dingLogin",
data() {
return {
code: "",
corpid: "", //钉钉企业id
channel: "", //钉钉应用渠道
pcLogin: "", //是否pc登陆
tokenValue: "",
dingLogin: "" //判断是否是pc登录 TRUE 为钉钉登录
};
},
created() {
let _this = this;
let urlParam = window.location.href; //获取当前url
let paramData = urlParam.split("?")[1];
let getcs = new URLSearchParams("?" + paramData); //将参数放在URLSearchParams函数中
console.log('getcs',getcs)
_this.channel = getcs.get("channel");
_this.corpid = getcs.get("corpid");
_this.pcLogin = getcs.get("pcLogin");
_this.dingLogin = getcs.get("dingLogin");
_this.tokenValue = Cookies.get("Admin-Token");
if(_this.tokenValue == 'undefined' || _this.tokenValue == undefined){
_this.tokenValue = ''
}
Cookies.set("dingLogin", _this.dingLogin, { expires: 30 });
let encodeUrl = encodeURIComponent(urlParam)
let url2 = 'http://auth.dingtalk.com/login?redirectUri=' + encodeUrl
let encodeUrl2 = encodeURIComponent(url2)
let url3 = 'https://login.dingtalk.com/oauth2/auth?response_type=code&client_id=dingwa4tibze6jwz7mgv&scope=openid&state=dddd&redirect_uri=' + encodeUrl2
// window.location.href = url3;
if (_this.dingLogin == 'true') {
axios
.get(
"https://devtest.cloudjoys.com/ding/login/tokenWhetherBelongCorp?token=" +
_this.tokenValue + '&corpId=' + _this.corpid + '&channel=' + _this.channel
)
.then(res => {
if (res.data.data === false || res.data.data == false) { //判断是否是当前组织的token
dd.runtime.permission.requestAuthCode({
corpId: _this.corpid,
onSuccess: function(info) {
_this.code = info.code; // 通过该免登授权码可以获取用户身份
// alert("code",info.code)
// _this.getCorpidLogin();
corpidLogin(info.code, _this.corpid, _this.channel, _this.pcLogin).then(
response => {
// alert('corpidLogin+'+JSON.stringify(response))
_this.tokenValue =response.data + '';
localStorage.setItem('token', _this.tokenValue)
Cookies.set("Admin-Token",_this.tokenValue, { expires: 30 });
setToken(_this.tokenValue)
// setToken(res.data.token)
_this.$router.push({ path: "/index" });
// this.$router.push({ path: "/app/apps/walkman" });
// setTimeout(function() {
// },500)
}
);
},
onFail: function(err) {
alert('fail');
alert(JSON.stringify(err));
}
});
} else {
console.log('true')
// _this.$router.push({ path: "/app/apps/walkman" });
_this.$router.push({ path: "/index" });
}
});
} else {
console.log('00')
this.$router.push({ path: "/login" }).catch(() => {});
}
// this.getCorpidLogin()
},
mounted() {
// // H5嵌入钉钉
// dd.config({
// corpId:this.corpid,//必填,企业ID
// type:0,
// jsApiList : [ 'runtime.info', 'biz.contact.choose','biz.contact.chooseMobileContacts',
// 'device.notification.confirm', 'device.notification.alert',
// 'device.notification.prompt', 'biz.ding.post','biz.util.previewImage',
// 'biz.util.openLink','device.geolocation.start','device.geolocation.get','biz.util.uploadImageFromCamera','biz.util.uploadImage' ,
// 'device.audio.startRecord','device.audio.stopRecord','device.audio.play','device.audio.pause','device.audio.download','device.audio.translateVoice','device.audio.onPlayEnd'
// ] // 必填,需要使用的jsapi列表,注意:不要带dd。
// });
// //为防止在非钉钉环境下报错做出的if判断
// if (dd.env.platform !== "notInDingTalk") {
// alert("notInDingTalk",this.corpid);
// //进行钉钉登录操作
// dd.runtime.permission.requestAuthCode({
// corpId: this.corpid,//企业ID,必填
// onSuccess: function(result) {
// //获取到免登录码,我这边是直接弹出弹窗可以直观看到是否获取到code
// alert("result==",result.code);
// this.code = result.code;
// // axios.get('https://devtest.cloudjoys.com/ding/login?code=' + this.code + '&corpId=' +this.corpid + '&channel=' + this.channel + '&pcLogin=' + this.pcLogin) .then(res => {
// // alert(1)
// // })
// localStorage.setItem("code", result.code)
// corpidLogin(result.code, this.corpid, this.channel, this.pcLogin).then(
// res => {
// console.log("res", res);
// alert('corpidLogincorpidLogincorpidLogin', res)
// this.tokenValue = res.data.data;
// Cookies.set("Admin-Token", this.tokenValue, { expires: 30 });
// console.log( this.tokenValue,'是否有token')
// this.$router.push({ path: "/index" });
// // this.$router.push({ path: "/app/apps/walkman" });
// // setTimeout(function() {
// // },500)
// });
// // this.getCorpidLogin();
// // axios.get('https://devtest.cloudjoys.com/ding/login?code=' + this.code + '&corpId=' +this.corpid + '&channel=' + this.channel + '&pcLogin=' + this.pcLogin) .then(res => {
// // alert(1)
// // })
// },
// onFail: function(err) {
// //返回错误信息
// }
// });
// }
},
methods: {
//获取token
getCorpidLogin() {
let _this = this;
_this.code = '3336d54ea4f032dab142ed3b118adc81'
_this.channel = 'enjoyWelfare'
_this.corpid = 'dingb574dbd6a141ddc5acaaa37764f94726'
_this.pcLogin = true
alert('corpidLogincorpidLogincorpidLogin', _this.code)
corpidLogin(_this.code, _this.corpid, _this.channel, _this.pcLogin).then(
res => {
console.log("res", res);
// _this.tokenValue = res.data.data;
_this.tokenValue = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl90ZW5hbnRfa2V5IjoiNCIsInVzZXJpZCI6MTUxMjc0NDc1NTcsImxvZ2luX3VzZXJfa2V5IjoiN2VjNDZkOWItNzk0MC00ZWIxLWJkMDctMzI0YzdiNGQ4ZWJmIn0.HrYYLbgl3hH1SpRgWPriY_oZca-aKBHld-JXn6_5RFjEs04ezgTse4WE3M6ZiVl830sEtnovDpM4h7dmapYYFg'
Cookies.set("Admin-Token", _this.tokenValue, { expires: 30 });
this.$router.push({ path: "/index" });
}
);
}
}
};
</script>
遇到的一个坑 在钉钉pc客户端的应用dd.ready()不生效,需要去掉dd.ready(),直接调取dd.runtime.permission.requestAuthCode方法获取免登code码