Last active
December 1, 2016 05:29
-
-
Save ZZR-china/bfcaaed93e252ee9d90dc21c12708985 to your computer and use it in GitHub Desktop.
a function to get wx access_token which will nerver expires
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const router = require('express').Router(), | |
Promise = require("bluebird"), | |
readFileAsync = Promise.promisify(require("fs").readFile), | |
writeFileAsync = Promise.promisify(require("fs").writeFile), | |
request_get = Promise.promisify(require('request').get); | |
router.route('/accesstoken') | |
.get((req, res) => { | |
readFileAsync("accesstoken.txt","utf8") | |
.then(data =>{ | |
const token = JSON.parse(data); | |
const token_url = global.token_url;//wechat token url | |
const iao = token.iao; | |
const now_time = (new Date()).getTime(); | |
if (now_time >= iao) { | |
return request_get(token_url) | |
}else{ | |
res.send(data); | |
} | |
}) | |
.then(result =>{ | |
if(result){ | |
let body = result[0].body; | |
res.send(body); | |
body = JSON.parse(body); | |
let token_iao = new Date(); | |
body.iao = token_iao.setSeconds(token_iao.getSeconds() + body.expires_in, 0); | |
body.data = body.access_token; | |
return writeFileAsync('accesstoken.txt', JSON.stringify(body), 'utf-8'); | |
}else{ | |
} | |
}) | |
.catch(err => { | |
console.error(err); | |
}); | |
}) | |
module.exports = function(app) { | |
app.use('/', router) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment