获取ticket是需要拼接url,url中需要获得的tocken
1、先判断有无tocken;若有则拼接url;
2、请求url;
a、处理回调数据,注意时间戳和签名处理方式,此两项并未存到ticket中,
b、存储回调数据,存储时将时间戳和签名存到ticket中;注意此两项并未存到数据库,而是在存储时动态生成的时间戳和签名,签名还有一个签名函数;
c、返回存储数据。
1 function refreshTicket(appid, appsecret, page, ticket, res) { 2 getToken(appid, appsecret, function (token, err) { 3 if (err === null) { 4 if (!_.isEmpty(token.access_token)) { 5 // 获取 jsapi_ticket 6 var ticket_url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + token.access_token + '&type=jsapi'; 7 8 request.get(ticket_url, function (error, response, body) { 9 var t = ticket === null ? new WeChatTicket() : ticket; 10 var data = JSON.parse(body); 11 12 if(!data.ticket) res.json({error: response}); 13 else { 14 t.appid = appid; 15 t.ticket = data.ticket; 16 t.noncestr = sha1(new Date()); 17 t.expires_in = data.expires_in; 18 t.at = parseInt(new Date().getTime() / 1000); 19 20 var timestamp = parseInt(new Date().getTime() / 1000); 21 var signature = wechatSignature(t, page, timestamp); 22 23 t.save(function (err) { 24 var json = t.toJSON(); 25 json.at = timestamp; 26 json.signature = signature; 27 res.json({ticket: json, error: err}); 28 }); 29 } 30 }); 31 } else res.json({error: err}); 32 } else res.json({error: err}); 33 }); 34 } 35 36 /* 微信签名实现 */ 37 function wechatSignature(t, page, timestamp) { 38 var string = "jsapi_ticket=" + t.ticket + "&noncestr=" + t.noncestr + "×tamp=" + timestamp + "&url=" + page; 39 return sha1(string); 40 }