新浪微博Node.js sdk

jopen 11年前發布 | 23K 次閱讀 Node.js Node.js 開發

新浪微博node sdk

特點

  • api可配置化

  • 接口采用promise

  • 最少依賴,專注新浪微博OAuth2.0認證

使用方法

安裝

npm install iweibo

配置

引入iweibo

var iweibo = require('iweibo'); var Weibo = iweibo.Weibo;

配置app信息

  • iweibo.set(name, options); //設置單條

  • iweibo.set(optionsObject);  //設置多條

iweibo.set({
 appkey: 'xxx',
 appsecret: 'xxxxxxxxxx'
 })

支持的配置:

var CONFIG = {
 appkey: '',
 appsecret: '',
 oauth_host: 'https://api.weibo.com/oauth2/authorize',
 access_url: 'https://api.weibo.com/oauth2/access_token',
 api_url: 'https://api.weibo.com/2/'
 }

配置api接口

  • iweibo.setAPI(apiname, options); //設置單條api

  • iweibo.setAPI(optionsObject);  //設置多條api

iweibo.setAPI('statuses/update', {
 method: 'post',
 params: {
 status: 'hello, world',
 visible: 0
 } });

配置下微博接口(由于太多,并且不時更新,所以我就沒全配置),配置下自己使用的接口,方法參考下件,基本如下:

'接口名稱': {
 method: 'get', //請求方法,post或者get(get可省略),參考api文檔
 params: { //默認參數,不用填寫appkey和access_token,程序會自動補上
 } }

可以講接口統一寫到一個json或者js文件中,然后使用 require 引入,直接給 setAPI 傳入

使用

參考 examples/app.js 文件(需要先在本目錄執行 npm install 安裝依賴模塊)

修改host,添加下面內容:

127.0.0.1 testapp.cn

進入 open.weibo.com 設置應用回調地址到 http://testapp.cn/callbak

獲取登錄鏈接

weibo.getAuthorizeURL(backURL);

獲取access_token

weibo.getAccessToken('code', {
 code: code,
 redirect_uri: backURL }).done(function(err, data) {
 var realpath = templateDir + 'callback.html';
 html = fs.readFileSync(realpath);
 data = JSON.parse(data);
 data.refresh_token = data.refresh_token || '';
 req.session.refresh_token = data.refresh_token;
 req.session.access_token = data.access_token;
 req.session.uid = data.uid;
 html = bdTemplate(html, data);
 res.end(html); }).fail(function(err, data) {
 var html;
 if (err) {
 html = fs.readFileSync(templateDir + 'error.html');
 } 
    res.end(html); });

使用api接口

//所有API都支持promise接口
 weibo.api('users/show', urlObj).done(function(err, result) {
 console.log(result);
 res.end(JSON.stringify(result));
 });

測試方法

  • 進入examples

  • 修改config.json,回調地址需要在open.weibo.com配置好,然后修改自己的host,將回調地址指到127.0.0.1

  • 執行 npm install

  • 訪問自己在config.json配置的網站

項目主頁:http://www.baiduhome.net/lib/view/home/1408696816678

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!