Giter VIP home page Giter VIP logo

weibo's Introduction

node-weibo Build Status

NPM

logo

A weibo(like twitter) API SDK, use on browser client and nodejs server.

Please see the API Documents first.

Supports APIs

Nodejs Install

$ npm install weibo

How to use

entry.js

var weibo = require('weibo');

// change appkey to yours
var appkey = 'your appkey';
var secret = 'your app secret';
var oauth_callback_url = 'your callback url';
weibo.init('weibo', appkey, secret, oauth_callback_url);

var user = { blogtype: 'weibo' };
var cursor = {count: 20};
weibo.public_timeline(user, cursor, function (err, statuses) {
  if (err) {
    console.error(err);
  } else {
    console.log(statuses);
  }
});

Demo on nodejs and browser just the same code.

Thanks for browserify, let us to use the same code on nodejs and browser.

Browser: Phonegap, Chrome extension or node-webkit.

NOTICE: browser must enable cross-domain request.

browserify to bundle.js

$ browserify entry.js -o bundle.js

Include bundle.js to your html.

<html>
  <head>
    <title>Weibo Hello world</title>
    <script src="bundle.js"></script>
  </head>
  <body>
    Hello world.
  </body>
</html>

Use weibo.oauth middleware

handler oauth login middleware, use on connect, express.

/**
 * oauth middleware for connect
 *
 * example:
 *
 *  connect(
 *    connect.query(),
 *    connect.cookieParser('I\'m cookie secret.'),
 *    connect.session({ secret: "oh year a secret" }),
 *    weibo.oauth()
 *  );
 *
 * @param {Object} [options]
 *   - {String} [homeUrl], use to create login success oauth_callback url with referer header,
 *     default is `'http://' + req.headers.host`;
 *   - {String} [loginPath], login url, default is '/oauth'
 *   - {String} [logoutPath], default is '/oauth/logout'
 *   - {String} [callbackPath], default is login_path + '/callback'
 *   - {String} [blogtypeField], default is 'type',
 *       if you want to connect weibo, login url should be '/oauth?type=weibo'
 *   - {Function(req, res, callback)} [afterLogin], when oauth login success, will call this function.
 *   - {Function(req, res, callback)} [beforeLogout], will call this function before user logout.
 */

Example: A simple web with oauth login.

var connect = require('connect');
var weibo = require('../');

/**
 * init weibo api settings
 */

weibo.init('weibo', '$appkey', '$secret');
weibo.init('tqq', '$appkey', '$secret');
weibo.init('github', '$ClientID', '$ClientSecret');

/**
 * Create a web application.
 */

var app = connect(
  connect.query(),
  connect.cookieParser('oh year a cookie secret'),
  connect.session({ secret: "oh year a secret" }),
  // using weibo.oauth middleware for use login
  // will auto save user in req.session.oauthUser
  weibo.oauth({
    loginPath: '/login',
    logoutPath: '/logout',
    blogtypeField: 'type',
    afterLogin: function (req, res, callback) {
      console.log(req.session.oauthUser.screen_name, 'login success');
      process.nextTick(callback);
    },
    beforeLogout: function (req, res, callback) {
      console.log(req.session.oauthUser.screen_name, 'loging out');
      process.nextTick(callback);
    }
  }),
  connect.errorHandler({ stack: true, dump: true })
);

app.use('/', function (req, res, next) {
  var user = req.session.oauthUser;
  res.writeHeader(200, { 'Content-Type': 'text/html' });
  if (!user) {
    res.end('Login with <a href="/login?type=weibo">Weibo</a> | \
      <a href="/login?type=tqq">QQ</a> | \
      <a href="/login?type=github">Github</a>');
    return;
  }
  res.end('Hello, <img src="' + user.profile_image_url + '" />\
    <a href="' + user.t_url +
    '" target="_blank">@' + user.screen_name + '</a>. ' +
    '<a href="/logout">Logout</a>');
});

app.listen(8088);
console.log('Server start on http://localhost:8088/');

Test

$ npm install
$ npm test

jscoverage: 79%

Authors

Below is the output from git-summary.

$ git summary

 project  : node-weibo
 repo age : 3 years
 active   : 73 days
 commits  : 173
 files    : 53
 authors  :
   156  fengmk2                 90.2%
     7  hpf1908                 4.0%
     3  chemzqm                 1.7%
     2  QLeelulu                1.2%
     1  hbbalfred               0.6%
     1  im007boy                0.6%
     1  iwillwen                0.6%
     1  mk2                     0.6%
     1  xydudu                  0.6%

License

(The MIT License)

Copyright (c) 2011-2014 fengmk2 <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

weibo's People

Contributors

chemzqm avatar fengmk2 avatar hbbalfred avatar hpf1908 avatar im007boy avatar iwillwen avatar qleelulu avatar xydudu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

weibo's Issues

授权redirect_url不匹配

先提一个小错误,oauth_middleware.js里

options.logoutPath = options.logoutPath || '/ouath/logout';

缺省参数拼错了 oauth

我主要想说的是,一开始我是在localhost:3000下测试的,因为要绑定域名,再没有重启服务器的时候,直接改了host然后从test.com进入程序,但此时options.homeUrl依旧是之前的localhost:3000(设置路由的时候没有指定homeUrl)导致var authCallback = getAuthCallback(options); 的host部分不是test.com从而出现问题。

情况比较奇葩...不过似乎把login里对homeUrl的判断去掉,每次从header里更新,也没什么问题?

腾讯微博发微博接口返回null

tapi.init 'tqq',appkey,secret,oauth_callback_url  #appkey,secret,cb设置完成
.....#获取acess_token并验证没有问题   

user={
      blogType: 'tqq',
      authtype: 'oauth',
      oauth_token_key: '7077c78abe474b2c8caecea93ed71236' #获取的acess_token
      oauth_token_secret: 'ea241d8b6eb834605feb59a9a1cf527e'
      }

tapi.update {blogType: 'tqq',status:'one tweet',user:user},(err,r,r2)->
      console.log err,r`

结果总是null,null

这是打印的请求(一些字段值省略)

url,args: http://open.t.qq.com/api/t/add { type: 'POST',
play_load: 'status',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8;' },
url: '/t/add',
data:
{ blogType: 'tqq',
source: '',
format: 'json',
content: 'upload a pic',
oauth_consumer_key: '
'
oauth_version: '1.0',
oauth_token: '',
oauth_timestamp: 1332110736,
oauth_nonce: '
'
oauth_signature_method: 'HMAC-SHA1',
oauth_signature: '' },
user:
{ blogType: 'tqq',
authtype: 'oauth',
oauth_token_key: '
',
oauth_token_secret: '*' } }

README.md 中的 entry.js 无法正常运行

你好,我的nodejs版本是v0.10.4 按照你README中说的方法,在执行 node entry.js 后:

{ [PublicTimelineError: source paramter(appkey) is missing]
data:
{ error: 'source paramter(appkey) is missing',
error_code: 10006,
request: '/2/statuses/public_timeline.json' },
name: 'PublicTimelineError' }

但是,我在weibo.init()中明明有填入appkey。

TypeError: Object #<Object> has no method 'oauth'

谢谢你的贡献,这是一个非常有用的项目。

我在运行演示的时候

node connect_with_oauth_middleware

出现以下错误,请问是什么原因?

TypeError: Object # has no method 'oauth'
at Object. (/data/www/node/node_modules/weibo/examples/connect_with_oauth_middleware.js:30:9)

谢谢

oauth callback返回Internal Server Error

在oauthCallback的時候經常返回500錯誤,我已經被老大罵了好多次了,但這個是間歇性的,很難debug。
中間件代碼跟demo是差不多的,就是加了customHome和acope

500 VerifyCredentialsError: check sign error

使用中间件来进行授权时,在QQ授权页面中登录并跳转回 /oauth//callback 时出错:

(使用新浪微博没问题,只在使用QQ时除了第一次成功外,后来每次都是出错)

Express
500 VerifyCredentialsError: check sign error
at TQQAPI.detect_error (x:\node_modules\weibo\lib\tqq.js:118:11)
at x:\node_modules\weibo\lib\tbase.js:306:16
at done (x:\node_modules\weibo\node_modules\urllib\lib\urllib.js:228:5)
at x:\node_modules\weibo\node_modules\urllib\lib\urllib.js:399:9
at decodeContent (x:\node_modules\weibo\node_modules\urllib\lib\urllib.js:276:14)
at IncomingMessage. (x:\node_modules\weibo\node_modules\urllib\lib\urllib.js:377:7)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)

git summary

看到 Readme 中 每个 author 代码量的统计, 很直观, 请问是什么tool 统计出来的, 能给个链接不?

@fengmk2

是否支持腾讯微博的私信?

快速了翻了下源码, 好像是有direct_message_create的,而且tqq也有.
但是写了个测试,


  weibo.direct_message_create({
    "oauth_token": "some token",
    "oauth_token_secret": "some secret",
    "blogtype": "tqq",
    "authtype": "oauth"
  },'some id','some content',function(err,result){
    console.log(err,result)
  })

报错是: TypeError: Object #<TQQAPI> has no method 'direct_message_create'

通过这些修改,才能运行起来[新浪微薄]

lib/oauth_middleware.js

r173:
//options.home_url = home_url.replace(//+$/, '');
options.home_url = options.home_url.replace(//+$/, '');

r179:

if(!options.callback_path) {
    options.callback_path = options.login_path + '_callback';
}

lib/tapi.js

r51 下插入

user.blogType = user.blogType == 'undefined' ? undefined : user.blogType;

README中的例子有误

原例子中的代码不正确:

var params = {
        user:user ,
        data:{
            status:'test'
        }
    }

    tapi.update(params , function(err , data , res){
        if(err)
            console.log('error');
        else
            console.log(data);
    });

实际上params应该为这样才可以正确发表微博(新浪微博,其它的我没试)的:

var params = {
        user:user ,
        status:'test'
    }

tapi.js 的update方法

234 update: function(data, callback, context) {
235 if (!data.pic) {
236 this.api_dispatch(data).update(data, callback, context);
237 }
238 // 包含图片
239 var pic = data.pic;
240 delete data.pic;
241 this.api_dispatch(data).upload(data, pic, callback, context);
242 },

如果没有pic的话,应该在update后跟一个return吧?

verify_credentials接口参数错误

verify_credentials: function (user, callback)

参数user的结构必须为:
user = { blogtype : 'weibo', accesstoekn: 31y979, uid: 123131231}
或者
user = { blogtype : 'weibo', accesstoekn: 31y979, id: 123131231}
文档有误

upload的建议

/**
* 上传图片
* data: {user: user1, source: xxx, status: xxx, ...}
* pic: filepath
* callback: finish callback function
**/
upload: function(data, pic, callback, context) {
...
this.read_file(pic, function(file_buffer) {
......
}

//
read_file: function(pic, callback) {
if(typeof(pic) === 'string') {
fs.stat(pic, function(err, stats) {
fs.readFile(pic, function (err, file_buffer) {
if(!err)
callback(file_buffer);
});
});
} else {
callback(pic);
}
},
在read_file函数里面,如果传入的不是string类型的呢,直接callback,我的想法是 pic可能是直接传入pic的二进制内容,你这里做这样的处理,所以,觉得在注释中,pic的字段可以传入一个object,我尝试直接传入一个pic的二进制,发现能够上传成功,但是在构造请求体的时候
builder += '; filename="' + this.url_encode(fileinfo.name) + '"';
..
builder += 'Content-Type: '+ fileinfo.content_type + ';';
这里会不正确,因为当传入的pic为二进制时,

fileinfo: function(file) {
var name, content_type;
if(typeof(file) === 'string') {
var ext = path.extname(file);
content_type = this.FILE_CONTENT_TYPES[ext];
name = path.basename(file);
} else {
name = file.name || file.fileName;
content_type = file.fileType || file.type;
}
return {name: name, content_type: content_type};
},

这个参数不能取得 。。。从这里的写法可以看出,你是期待用户传入一个json对象,里面包含了 name或者type字段,但是如果是期待的是个json对象,为什么在read_file 函数里面是直接callback(pic)的呢,那回调的将是一个json对象,不可能上传json对象吧,感觉就很奇怪了。。。或许是我的理解错误,
我给的建议
/**
* 上传图片
* data: {user: user1, source: xxx, status: xxx, ...}
* pic: filepath/{type:'jpg',name:'1.jpg',data:buffer}
* callback: finish callback function
**/

read_file: function(pic, callback) {
    if(typeof(pic) === 'string') {
        fs.stat(pic, function(err, stats) {
            fs.readFile(pic, function (err, file_buffer) {
        if(!err)
                    callback(file_buffer);
            });
        });
    } else {
        callback(pic.data);
    }
},

调用的方法
本地路径
upload(params,"/home/rench/aa.jpg",function(err,data,response){

})

自己获取的图片二进制内容/可扩展性,可以抓取远程图片upload到微博
upload(params,{type:"jpg",name:"a.jpg",data:buffer},function(err,data,response){

})

[email protected]

oauth_middleware

oauth_middleware里面的options里面的参数callback_path 你写死了,不能传参数

options.callback_path = options.login_path + '_callback';

modify:

options.callback_path = options.callback_path || options.login_path + '_callback';

tsina.js的1008行有bug

this._send_request(params, callbac, contextk);
我猜应该是:
this._send_request(params, callback, context);

貌似 weibo 跟 sugar 有冲突

/usr/local/bin/node dev.js
TypeError: Object #<Object> has no method 'init'
    at Object.<anonymous> (/Users/XadillaX/code/huaban/pinit/lib/share.js:27:6)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (/Users/XadillaX/code/huaban/pinit/lib/people.js:13:13)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)

大致是 tapi 跟它冲突了。看看有没有可能解决下冲突?

SugarJS

如何正确update微博

Hi:

请教正确的使用办法。我尝试在readme的example基础上update微博:

app.use('/', function(req, res, next) {
var user = req.session.oauthUser;
res.writeHeader(200, {
'Content-Type' : 'text/html'
});
if (!user) {
res.end('Login first, please.');
return;
}
weibo.tapi.update({
status : "hi"
}, function(err, statuses) {
if (err) {
console.error(err);
} else {
console.log(statuses);
}
});
res.end('Hello, @' + user.screen_name + '. ' + 'Logout');
});

返回的是error: '40302:Error: auth faild!', 错误。

谢谢。

The "sys" module is now called "util". It should have a similar interface.

在NAE上使用A simple web with oauth login.,产生这个错误。

The "sys" module is now called "util". It should have a similar interface.
TypeError: Object # has no method 'oauth'
at Object. (/home/admin/cnae/git/cnode-app-engine/apps/datamine/server.js:17:11)
at [object Object]._compileFile (/home/admin/cnae/git/cnode-app-engine/lib/sandbox.js:347:49)
at Object..js (/home/admin/cnae/git/cnode-app-engine/lib/sandbox.js:391:9)
at [object Object].load (/home/admin/cnae/git/cnode-app-engine/lib/sandbox.js:150:17)
at Function._loadFile (/home/admin/cnae/git/cnode-app-engine/lib/sandbox.js:176:10)
at Function.run (/home/admin/cnae/git/cnode-app-engine/lib/sandbox.js:357:18)
at Array.0 (/home/admin/cnae/git/cnode-app-engine/lib/child.js:83:11)
at EventEmitter._tickCallback (node.js:192:40)

登录后后退报错

登录成功之后点击后退按钮,出现如下错误

500 TypeError: Cannot call method 'get_access_token' of undefined
at Object.module.exports.get_access_token (node_modules/weibo/lib/tapi.js:670:36)

README.md里面的server例子不能用

是不是doc老了?

var tapi = require('weibo').tapi;
tapi.init('tsina', appkey, secret);
tapi.public_timeline(function(error, data, response) {
    if(error) {
        console.error(error);
    } else {
        console.log(data);
    }
});

错误信息:

/path/to/node_modules/weibo/lib/tsina.js:191
        callback.call(context, error, data, res);
           ^
TypeError: Cannot call method 'call' of undefined
at Object.<anonymous> (/path/to/node_modules/weibo/lib/tsina.js:191:16)
at IncomingMessage.<anonymous> (/path/to/node_modules/weibo/lib/urllib.js:101:14)
at IncomingMessage.emit (events.js:81:20)
at HTTPParser.onMessageComplete (http.js:133:23)
at Socket.ondata (http.js:1213:22)
at Socket._onReadable (net.js:681:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)

有些api不支持

能不能提供一种易于扩展api的方式呢? 比如新浪微博有了新的api, 我可以很容易的就可以使用它

Use Everyauth as a middleware

I am writing an app and I use everyauth to manage all oauth process. I can do oauth login with weibo using everyauth then get accessToken. How could I use it directly with node-weibo to make api requests ? Any idea or advices?

Thanks for the good job anyway ! Very useful :)

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.