-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
53 lines (48 loc) · 2.02 KB
/
index.ts
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import * as express from "express";
import * as request from "request";
import sha1 = require("sha1");
let app = express();
// Insert metadata
let appId = ''; // Insert your appId
let appsecret = ''; // insert your appsecret
let url = ''; // insert host url, e.g. http://wxapp.azurewebsites.net/
let nonceStr = ''; // insert any string
// define an interface containing params for wx.config
interface configObj {
appId: string,
timestamp: string,
nonceStr: string,
signature: string
}
// handshake with WeChat server and get signature for wx.config
function getWXConfig(cb) {
request.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+appId+'&secret='+appsecret, (err, res, body) => {
request.get('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+JSON.parse(body).access_token+'&type=jsapi', (err, res, body) => {
let ticket = JSON.parse(body).ticket;
let o: configObj = {
appId: appId,
nonceStr: nonceStr,
timestamp: new Date().getTime() / 1000 + '',
signature: ''
};
o.signature = sha1('jsapi_ticket='+ticket+'&noncestr='+o.nonceStr+'×tamp='+o.timestamp+'&url='+url).toString();
cb(o);
});
});
}
app.engine('.html', require('ejs').__express); // set up ejs as view engine
app.set('views', __dirname + '/views'); // set views dir
app.set('view engine', 'html'); // use .html for ejs files
app.use(express.static('public')) // expose assets in /public
app.get('/', function (req, res) {
getWXConfig(config => {
// handshake with WeChat server and render index.html with the returned signature
res.render('index', {
appId: config.appId,
timestamp: config.timestamp,
nonceStr: config.nonceStr,
signature: config.signature,
});
})
});
app.listen(8080);