Giter Club home page Giter Club logo

Comments (11)

JacksonTian avatar JacksonTian commented on September 24, 2024

It’s sample code. use redis/db instead of.

在 2016年3月31日,下午5:26,dc <[email protected] mailto:[email protected]> 写道:

Your examples don't seem to work to get started...

'use strict';

let debug = require('debug')('wechat-api');
let path = require('path');
let fs = require('fs');

let AppConfig = require('../../private/AppConfig');

var WechatAPI = require('wechat-api');

let tokenFilePath = path.join(__dirname, 'access_token.txt');

debug('init', tokenFilePath);

var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET, function (callback) {
// 传入一个获取全局token的方法
fs.readFile(tokenFilePath, 'utf8', function (err, txt) {
debug('read token ', tokenFilePath, txt);
if (err) {return callback(err);}
callback(null, JSON.parse(txt));
});
}, function (token, callback) {
// 请将token存储到全局,跨进程、跨机器级别的全局,比如写到数据库、redis等
// 这样才能在cluster模式及多机情况下使用,以下为写入到文件的示例
debug('write token to ', tokenFilePath, token);
fs.writeFile(tokenFilePath, JSON.stringify(token), callback);
});

// var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET);
api.updateRemark('open_id', 'remarked', function (err, data, res) {
debug('updateRemark', data, res);
});
results:

wechat-api init +56ms /Users/dc/dev/rikai/boteditor/lib/wechat/access_token.txt
wechat-api read token +11ms /Users/dc/dev/rikai/boteditor/lib/wechat/access_token.txt undefined
wechat-api updateRemark +1ms undefined undefined

so no token is being created or read.


You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub #136

from wechat-api.

dcsan avatar dcsan commented on September 24, 2024

so this code does not return a token or a usable API?

from wechat-api.

dcsan avatar dcsan commented on September 24, 2024

If i obtain a token by my own code, can it be passed to this API for using the api.send ... methods?

from wechat-api.

dcsan avatar dcsan commented on September 24, 2024

this code works fine to obtain a token

but how to then use wechat-api with this token?

'use strict';

let syncRequest = require('sync-request');

let debug = require('debug')('WcTokenManager');
let AppConfig = require('../../private/AppConfig');
let WcTokenManager = {};


// TODO - store this in DB so we can access across multiple servers...
let tokenObj = null;


WcTokenManager.checkToken = function() {

  if (!tokenObj) {
    tokenObj = WcTokenManager.getNewAccessToken();
  }

  // else get a new token
  var nowTime = Math.floor(new Date().getTime() / 1000);
  var diff = tokenObj.expiresAt - nowTime;
  if (diff <= 100) {
    tokenObj = WcTokenManager.getNewAccessToken();
  }
  return tokenObj;
};

// // TODO - save to db
// WcTokenManager.saveAccessToken = function(accessToken) {
//
//   // expiresIn = 10; // for test expiresIn immediately
//   var expiresIn = accessToken.expiresIn || 7200;
//
//   var currentTime = Math.floor(new Date().getTime() / 1000);
//
//   var tokenObj = {
//       appId: ServerConfig.appId,
//       token: accessToken.access_token,
//       getTokenAt: currentTime,
//       expiresIn: expiresIn,
//       expiresAt: currentTime + expiresIn,
//       createdAt: new Date()
//   };
//
//   WcTokenManager.remove({ appId: ServerConfig.appId });
//   WcTokenManager.insert(tokenObj);
//
//   Logger.log('saveAccessToken', tokenObj);
//   tokenCache = tokenObj;
//   return tokenObj;
// };
//

// https://mp.weixin.qq.com/wiki/11/0e4b294685f817b95cbed85ba5e82b8f.html

WcTokenManager.getNewAccessToken = function() {

  var params = {
    appid: AppConfig.APP_ID,
    secret: AppConfig.APP_SECRET,
    grant_type: 'client_credential'
  };

  var url = AppConfig.API_ENDPOINT + '/cgi-bin/token';
  url += `?grant_type=client_credential&appid=${params.appid}&secret=${params.secret}`;
  // debug('getNewAccessToken url', url);

  var res = syncRequest('GET', url);
  // debug('res', res);
  var body = res.getBody().toString();
  var rawToken = JSON.parse(body);

  var expires_in = rawToken.expires_in || 7200;
  var currentTime = Math.floor(new Date().getTime() / 1000);

  var tokenObj = {
      appId: AppConfig.APP_ID,
      access_token: rawToken.access_token,
      expires_in: expires_in,
      expires_at: currentTime + expires_in,
      createdAt: new Date(),
      createdAtSecs: currentTime
  };
  debug('gotToken', tokenObj);
  return tokenObj;
};


WcTokenManager.tokenString = function() {
  var token = WcTokenManager.checkToken().access_token;
  return token;
};

// startup
WcTokenManager.checkToken();

module.exports = WcTokenManager;

from wechat-api.

JacksonTian avatar JacksonTian commented on September 24, 2024
'use strict';

let debug = require('debug')('wechat-api');
let path = require('path');
let redisClient = ...

let AppConfig = require('../../private/AppConfig');

var WechatAPI = require('wechat-api');

debug('init', tokenFilePath);

var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET, function (callback) {
  redisClient.get('token_key', function (err,data) {
    if (err) {return callback(err);}
    callback(null, data && JSON.parse(data));
  });
}, function (token, callback) {
  redis.set('token_key', JSON.stringify(token),callback);
});

// var api = new WechatAPI(AppConfig.APP_ID, AppConfig.APP_SECRET);
api.updateRemark('open_id', 'remarked', function (err, data, res) {
  debug('updateRemark', data, res);
});

from wechat-api.

JacksonTian avatar JacksonTian commented on September 24, 2024

WechatAPI can auto get new token. You just need provide a save/get interface.

from wechat-api.

dcsan avatar dcsan commented on September 24, 2024

so

  redisClient.get('token_key', function (err,data) {
    callback(null, data && JSON.parse(data));

^ this is the command that calls the API of your library?

callback - passed in API
null - your API expects a null for first argument?

data && JSON.parse(data) - what is this???

I don't understand why the third param needs to && with the JSON.parse version??
what is the API expecting?
is there any actual documentation on this?

it seems very obfuscated in order to use this API?

from wechat-api.

dcsan avatar dcsan commented on September 24, 2024

here is some simple code to call WeChat APIs.

dataObject is a wechat JSON package.

WcApi.sendMessageToUser = function(dataObject) {
  var accessToken = WcTokenManager.tokenString();

  var url = AppConfig.API_ENDPOINT + '/cgi-bin/message/custom/send?access_token=' + accessToken;

  debug('sendMessageToUser:' + JSON.stringify(dataObject, null, 2));
  debug('url:', url);

  request.post(
      url,
      {
        body: dataObject,
        json: true
      }
    , function(error, result) {

from wechat-api.

looping84 avatar looping84 commented on September 24, 2024

@dcsan

callback(null, data && JSON.parse(data));
//equals
if(data) {
  callback(null, JSON.parse(data));
} else {
    callback(null)
}

from wechat-api.

dcsan avatar dcsan commented on September 24, 2024

thanks @looping84

but I'm interested why the sample code doesn't work.

first callback: readToken - returns undefined.

but the second callback to write the token is never called.

it should be possible to read/write to a file with fs?

so, changing this to use redis/db won't actually fix the problem as far as i can see.

from wechat-api.

looping84 avatar looping84 commented on September 24, 2024

@dcsan

https://github.com/node-webot/wechat-api/blob/master/lib/api_common.js#L154

if readToken returns undefined, the saving token method will be called

if save token can't be called , please debug your code.

from wechat-api.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.