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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| const { Controller } = require('egg');
const axios = require('axios'); const jsSHA = require('jssha');
const appid = 'xxx'; const appsecret = 'xxx';
let jsapiTicket = ''; let ticketExpiresAt = 0;
async function getAccessToken(ctx) { try { const response = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`); const accessToken = response.data.access_token; return accessToken; } catch (error) { ctx.logger.info('Failed to get access token:', error.response.data); throw error; } }
async function getJsApiTicket(ctx) { try { const accessToken = await getAccessToken(ctx); const response = await axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`); const ticket = response.data.ticket; return ticket; } catch (error) { ctx.logger.info('Failed to get jsapi ticket:', error.response.data); throw error; } } var raw = function (args) { var keys = Object.keys(args); keys = keys.sort(); var newArgs = {}; keys.forEach(function (key) { newArgs[key.toLowerCase()] = args[key]; });
var string = ''; for (var k in newArgs) { string += '&' + k + '=' + newArgs[k]; } string = string.substr(1); return string; };
class ShareController extends Controller {
async getWechatSignature() { const { ctx } = this; const url = ctx.query.href;
const timestamp = parseInt(new Date().getTime() / 1000); const noncestr = Math.random().toString(36).substr(2, 15);
if (!jsapiTicket || timestamp >= ticketExpiresAt) { jsapiTicket = await getJsApiTicket(ctx); ticketExpiresAt = timestamp + 7000; }
var ret = { jsapi_ticket: jsapiTicket, nonceStr: noncestr, timestamp: timestamp + '', url: url, };
var string = raw(ret); var shaObj = new jsSHA(string, 'TEXT'); const signature = shaObj.getHash('SHA-1', 'HEX');
ctx.body = { code: 0, result: { timestamp: timestamp, nonceStr: noncestr, signature: signature, appId: appid, }, }; } }
module.exports = ShareController;
|