//引入 koa模块 //实例化
var Koa = require('koa');
var app = new Koa();
var router = require('koa-router')(); /*引入是实例化路由** 推荐*/
var axios = require("axios")
var sha1 = require('node-sha1');
var fs = require('fs');
// 设置跨域,和默认设置
app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set("Content-Type", "application/json")
await next();
});
const appId = 'wx31bea5f7647b6597'
const secret = 'cfa26d3e3681d11aaa630c14fb4cda21'
const AccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret
const jsapiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token="
//随机字符串
function randomString(len) {
len = len || 32; var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
var maxPos = $chars.length;
var pwd = '';
for (i = 0; i < len; i++) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
router.get('/wx', async (ctx) => {
// 先判断存的签名是否到期
let data = await new Promise(function (resolve, reject) {
fs.readFile('./hello.json', function (error, data) {
if (error) {
console.log('读取文件失败,当前未保存凭证')
resolve(0)
} else {
let obj = JSON.parse(data.toString())
let second = parseInt((Date.now() - obj.timestamp) / 1000);
if (second < 7200) {
console.log("读取成功,凭证在有效期内")
resolve(obj)
} else {
console.log("读取成功,凭证已经过期了")
resolve(0)
}
}
})
})
if (data != 0) {
ctx.body = data
} else {
let AccessToken = ''
let jsapi_ticket = ''
let signature = ''
// 生成20位随机字符串
let noncestr = randomString(17)
// 获取当前时间戳
let timestamp = Date.now();
// 获取到前端当前的url
let url = ctx.request.header.referer
// 获取到acctoken
await axios.get(AccessTokenUrl)
.then(function (response) {
AccessToken = response.data
})
.catch(function (error) {
console.log(error);
})
//通过access_token 获取到ticket
await axios.get(jsapiUrl + AccessToken.access_token)
.then(function (response) {
jsapi_ticket = response.data.ticket
})
.catch(function (error) {
console.log(error);
})
// 拼接signature
let string1 = 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url
signature = await sha1(string1)
data = {
nonceStr: noncestr,
timestamp: timestamp,
signature: signature,
appId: 'wx31bea5f7647b6597',
}
ctx.body = data
//最后存入hello.json
data = JSON.stringify(data)
fs.writeFile('./hello.json', data, function (error) {
if (error) {
console.log('写入失败')
} else {
console.log('写入成功')
}
})
}
})
app.use(router.routes()); /*启动路由*/
// app.use(router.allowedMethods());
/*
* router.allowedMethods()作用: 这是官方文档的推荐用法,我们可以
* 看到 router.allowedMethods()用在了路由匹配 router.routes()之后,所以在当所有
* 路由中间件最后调用.此时根据 ctx.status 设置 response 响应头
*
*/
app.listen(3000, () => {
console.log('start in port -> 3000')
});
微信公众号开发文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
微信测试公众号申请:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
网友评论