钉钉 jsapi-node (1)

基于express的钉钉微应用探索

建立服务

首先已经默认已经安装了node环境和npm工具

 1 2 
 //使用express工具创建dingtalk项目,使用ejs模板 express dingtalk --ejs 

安装ding_jsapi_redis库

 1 
 cnpm install ding_jsapi_redis --save 

在项目更目录创建config.js配置文件,文件内容包含如下

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 
 //钉钉的相关配置信息 exports.ding = { corpId:"", //必填 secret:"",//必填 prefix:"" //必填,该参数是用于区分redis服务器中的多个token和ticket准备的 ,例如ding_ }; //ridis服务器相关配置 exports.redis = { port:6379, host :'192.168.1.218', auth:{} }; exports.domain = "http://192.168.1.6:3000" 

创建controller

在根目录下新建文件夹controllers,
在controllers文件夹中新建IndexController.js

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
 //首先导入config配置文件 var config = require("../config"); //导入ding_jsapi_redis var ding = require("ding_jsapi_redis"); //将config文件中的参数传入到ding库中 ding.conf.ding = config.ding; ding.conf.redis = config.redis; module.exports = { index:function(req,res){ var url = config.domain+req.url; // {redis:config.redis,ding:config.ding} var params = { id:"31441266" } var url = "http://192.168.1.6:3000/"; ding.getSignature(url).then(function(data){ console.log(data); res.render('index', { title: 'Express',dd_config:data }); }).catch(function (err) { console.log(err) }) } } 

编辑index.ejs

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
 <!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> <script type="text/javascript" src="http://g.alicdn.com/ilw/ding/0.7.3/scripts/dingtalk.js"></script> <script type="text/javascript"> var corpId = '<%=dd_config.corpId%>' ; var timeStamp = '<%=dd_config.timeStamp%>' ; var nonceStr = '<%=dd_config.nonceStr%>' ; var signature = '<%=dd_config.signature%>' ; </script> <script type="text/javascript" src="javascripts/index.js"></script> </head> <body> <p>Welcome to <%= title %></p> <button id="scan" onclick="scan()">scan</button> </body> <script type="text/javascript"> </script> </html> 

在javascripts中创建index.js文件

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 
 dd.config({ agentId: '82143702', corpId:corpId, timeStamp: timeStamp, nonceStr: nonceStr, signature: signature, jsApiList: [ 'biz.util.scan', ] }); dd.ready(function () { alert("dd ready"); dd.error(function(err) { alert('dd error: ' + JSON.stringify(err)); }); }) dd.error(function(err) { alert('dd error: ' + JSON.stringify(err)); }); function scan() { alert("i am scan"); dd.biz.util.scan({ type: "barCode",//type为qrCode或者barCode onSuccess: function(data) { //onSuccess将在扫码成功之后回调 alert(data.text); console.log(data); /* data结构 { 'text': String} */ }, onFail : function(err) { alert(err); } }) } 

至此,一个简单的基于钉钉的express服务器就搭建好了。主要核心在于获取ticket,目前已经在ding_jsapi_reids中封装好,直接使用即可。如果有更好的方法请联系我。谢谢。

原文:大专栏  钉钉 jsapi-node (1)

相关文章