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 | 'use strict' var Promise = require( 'bluebird' ); var request = Promise.promisify(require( 'request' )); var prefix = 'https://api.weixin.qq.com/cgi-bin/' ; var api = { accessToken: prefix + 'token?grant_type=client_credential' }; function Wechat(opts) { var that = this ; this .appID = opts.appID; this .appSecret = opts.appSecret; this .getAccessToken = opts.getAccessToken; this .saveAccessToken = opts.saveAccessToken; this .getAccessToken().then( function (data) { try { data = JSON.parse(data); } catch (e) { return that.updateAccessToken(that.appID, that.appSecret); } if (that.isValidAccessToken(data)) { Promise.resolve(data); } else { return that.updateAccessToken(that.appID, that.appSecret); } }).then( function (data) { that.access_token = data.access_token; that.expires_in = data.expires_in; that.saveAccessToken(data); }); } Wechat.prototype.isValidAccessToken = (data) => { if (!data || !data.access_token || !data.expires_in) { return false ; } var access_token = data.access_token; var expires_in = data.expires_in; var now = ( new Date().getTime()); if (now < expires_in) { return true ; } else { return false ; } }; Wechat.prototype.updateAccessToken = (appID, appSecret) => { var url = api.accessToken + '&appid=' + appID + '&secret=' + appSecret; console.log( '*************************url**************************' ); console.log(url); console.log( '*************************url**************************' ); return new Promise((resolve, reject) => { request({url: url, json: true }).then((response) => { console.log( '*************************response**************************' ); console.log(response); console.log( '*************************response**************************' ); var data = response[1]; var now = ( new Date().getTime()); var expires_in = now + (data.expires_in - 20) * 1000; data.expires_in = expires_in; resolve(data); }); }); }; module.exports = Wechat; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | { "name" : "wechat" , "version" : "1.0.0" , "description" : "Jack wechat test" , "main" : "app.js" , "scripts" : { "test" : "echo \"Error: no test specified\" && exit 1" }, "author" : "Jack Qiu" , "license" : "ISC" , "devDependencies" : { "bluebird" : "^3.3.5" , "koa" : "^1.2.0" , "path" : "^0.12.7" , "raw-body" : "^2.1.6" , "request" : "^2.71.0" , "sha1" : "^1.1.1" , "xml2js" : "^0.4.16" } } |
请问为什么我的this关键字不好用在updateAccessToken方法中,另一个是updateAccessToken中的response[1]是undefined
登录后可查看更多问答,登录/注册