0%

1.快速搭建

在全局下安装express

1
npm install -g express  

执行
1
2
3
4
express -v yourProject 	
或者
cd yourProject
express

就会快速在目录yourProject中搭建express,-v参数指定模板引擎,没写就默认为jade

2.express中间件

1
2
3
4
5
var app = requrie('express')();
app.use (function (req, res, next) {
...
next()
})

next()作用是交付控制权,前往下一个中间件
可以利用这一点做验证功能

3.MVC架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/app
/controllers
/models
/schemas
/views
/public
/libs
/css
/js
/router
router.js
app.js
package.json
.bowerrc
bower.json
gruntfile.js
.gitignore

以上就是项目的架构,按照MVC架构,后台代码都放在app下,schemas存放mongodb的模式,可以看作是一张张表,models放生成模型的文件,模型与模式对接起来。public存放静态文件,/libs存放前端框架如bootstrap。把router路由模块抽离放在router目录。
bower模块用来安装项目依赖的前端框架。需要在全局安装bower

1
npm install -g bower

安装bootstrap
1
2
bower init
bower install bootstrap

bower init 生成bower.json
然后安装bootstrap时,会根据.bowerrc文件
1
2
3
{
"directory": "public/libs"
}

把依赖的框架安装在public/libs下

4.项目管理工具grunt

gruntfile.js

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
module.exports = function(grunt) {

grunt.initConfig({
watch: {
jade: {
files: ['views/**'],
options: {
livereload: true
}
},
js: {
files: ['public/js/**', 'app/**/*.js'],
//tasks: ['jshint'],
options: {
livereload: true
}
},
uglify: {
files: ['public/**/*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
styles: {
files: ['public/**/*.less'],
tasks: ['less'],
options: {
nospawn: true
}
}
},

nodemon: {
dev: {
script: 'bin/www', //入口文件
options: {
nodeArgs: ['--debug'], //开启开发模式
args: [],
ignoredFiles: ['README.md', 'node_modules/**', 'public/libs/**', '.vscode'],
watchedExtensions: ['js'],
watchedFolders: ['./'], //监听定义的文件夹,根目录
debug: true,
delayTime: 1000,
env: {
PORT: 3000
},
cwd: __dirname
}
}
},

jshint: {
options: {
jshintrc: '.jshintrc',
ignores: ['public/libs/**/*.js']
},
all: ['public/javascripts/*.js', 'test/**/*.js', 'app/**/*.js']
},

less: {
development: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: {
'public/build/index.css' : 'public/less/index.less'
}
}
},

uglify: {
development: {
files: {
'public/build/admin.min.js': 'public/javascripts/admin.js',
'public/build/detail.min.js': [
'public/javascripts/detail.js'
]
}
}
},

mochaTest: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js']
},

concurrent: {
tasks: ['nodemon', 'watch', 'jshint', 'less', 'uglify'],
options: {
logConcurrentOutput: true
}
}
});

grunt.loadNpmTasks('grunt-contrib-watch'); //监控定义好的静态文件变动
grunt.loadNpmTasks('grunt-nodemon'); //监控入口文件变动
grunt.loadNpmTasks('grunt-concurrent'); //优化慢任务的构建时间,比如sass,less,并发执行多个阻塞的任务,比如nodemon和watch
grunt.loadNpmTasks('grunt-mocha-test'); //测试框架
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');

grunt.option('force', true); //避免程序因语法错误而终止执行

grunt.registerTask('default', ['concurrent']);
grunt.registerTask('test', ['mochaTest']);
}

前期开发只需要前面三个模块包即watch,nodemon,concurrent就行。

5.router模块

这里有两种方法
第一种是将路由分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.js
//挂载路由表
app.use('/', index);
app.use('/admin', admin);
app.use('/user', user)

user.js
var express = require('express');
var User = require('../models/user');
var router = express.Router();

//用户注册
router.post('/signup', function(req, res) {
...
}
module.exports = router;

当url以/user开头时就会进入user.js文件。
第二种是路由全部写在一个文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
app.js
require('./config/routers')(app); //不能传入express.Router(),它只能作为中间件用,如上

router.js
var Movie = require('../app/controllers/movie');
var Index = require('../app/controllers/index')


module.exports = function(app) {

//Index
app.get('/', Index.index);

//Movie
app.get('/movie/:id', Movie.detail);
app.get('/admin/movie/list',User.signinRequired,User.adminRequired, Movie.list);

};

6.数据库模块mongose

1
2
3
4
5
6
7
8
9
10
app.js
var mongoose = require('mongoose');
var dbURL = 'mongodb://localhost:27017/movieWeb';

//连接数据库
mongoose.Promise = global.Promise; //避免控制台输出Promise错误
mongoose.connect(dbURL) //数据库名为movieWeb
mongoose.connection.on('connected', function () { //绑定connected函数,连接成功时触发
console.log('Connection success!');
});

模式schemas(表)

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
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var MovieSchema = new mongoose.Schema({ //定义模式
doctor: String,
title: String,
language: String,
country: String,
summary: String,
flash: String,
poster: String,
year: String,
pv: {
type: Number,
default: 0
},
category: {
type: ObjectId,
ref: 'Category'
},
meta: {
createAt: {
type: Date,
default: Date.now()
},
updateAt: {
type: Date,
default: Date.now()
}
}
})

//每次存取数据之前,都调用save方法
MovieSchema.pre('save', function(next){
if(this.isNew) {
this.meta.createAt = this.meta.updateAt = Date.now()
} else {
this.meta.updateAt = Date.now()
}

next() //将流程走下去
})

MovieSchema.statics = { //实例化以后就会具有以下方法,相当于构造函数的成员方法
fetch: function(cb) {
return this
.find({})
.sort('meta.updateAt')
.exec(cb)
},
fetchById: function(id, cb) {
return this
.findOne({_id: id})
.exec(cb)
}
}

module.exports = MovieSchema

模型models(模式跟模型对接)
1
2
3
4
5
6
var mongoose = require('mongoose')
var MovieSchema = require('../schemas/movie')
var Movie = mongoose.model('Movie', MovieSchema) //模式和模型对接

module.exports = Movie


值得注意的是,使用mongodb之前,需要在电脑上安装mongodb,并注册成一个服务,方便使用前开启,具体参考笔记:mongodb错误

7.将session存放在mongodb里

session是会话支持,作为客户端的id,跟服务器交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//使用mongodb来储存sesion信息
var cookieParser = require('cookie-parser');
var session = require("express-session");
var MongoStore = require('connect-mongo')(session);

//配置session
app.use(cookieParser());
app.use(session({
secret: 'imoocMovieWeb',
store: new MongoStore({
url: dbURL,
collection: 'sessions'
}),
resave: true,
saveUninitialized: true
}))

其中呢,cookieParser()中间件是session和bodyParser的依赖的中间件
bodyParser是解析request请求的中间价
1
2
3
配置
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true})); //extended为true则可以解析字符串和数组以外的数据

8.前后台传数据

可以用res.render方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
controllers/movie.js

//获取后列表页
exports.list = function(req, res, next) {
Movie.fetch(function(err, movies) {
if(err) {
console.log(err)
}

res.render('list', {
title: '后台列表页',
movies: movies
});
})
};

还可以用res.locals,可以传递方法和变量
1
2
3
4
5
6
7
8
9
10
11
app.js

//前后台传递数据
app.use(function(req, res, next) {
res.locals.moment = moment; //向前台模板发送处理时间的moment方法

var _user = req.session.user;
res.locals.user = _user; //传递用户转态

next();
})

8.各种用到的中间件

  • flash

    1
    2
    3
    4
    5
    var flash = require('connect-flash') //存储变量的中间件,相当全局变量
    app.use(flash())

    使用
    var error = req.flash('error')
  • logger

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var logger = require('morgan'); //处理日志模块 

    //日志文件
    var fs = require('fs');
    var accessLogfile = fs.createWriteStream('access.log', {flags:'a'});
    var errorLogfile = fs.createWriteStream('error.log', {flags:'a'});

    app.set('env', 'production');
    app.use(logger({stream: accessLogfile})); //访问日志

    //处理错误日志,处理错误的中间件一定要写在路由后面
    if ('production' == app.get('env')) {
    app.use(function(err, req, res, next){
    var meta = '[' + new Date() + '] ' + req.url + '\n';
    errorLogfile.write(meta + err.stack + '\n');
    next();
    });
    }
  • moment

    1
    2
    3
    4
    5
    6
    7
    app.js
    var moment = require('moment'); //处理时间格式
    在中间件里
    res.locals.moment = moment; //向前台模板发送处理时间的moment方法

    jade模板文件
    moment(item.meta.updateAt).format('MM/DD/YYYY') //item.meta.updateAt是后台传过来的时间数据new Date()
  • bcrypt-nodejs 加盐模块

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var bcrypt = require('bcrypt-nodejs');
    var SALL_WORK_FACTOR = 10; //数值越大,破解越复杂
    bcrypt.genSalt(SALL_WORK_FACTOR, function(err, salt) {
    if(err) return next(err);

    bcrypt.hash(user.password, salt, null, function(err, hash) {
    if(err) return next(err);

    user.password = hash
    next() //将流程走下去
    })
    })
  • underscore (用到这模块的继承方法)

    1
    2
    var _ = require('underscore');
    _movie = _.extend(movie, movieObj)

9.jade模板引擎

1
2
3
4
5
6
7
8
9
10
11
12
layout.jade 公用的部份

doctype html
html
head
meta(charset="utf-8")
title #{title} - imoocMovie
include ./includes/head
body
include ./includes/header
block content
include ./includes/footer

引进用include
block content是主体内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
extends ../layout  //-扩展layout

block content
.container
.row
each cat in categories
.panel.panel-default
.panel-heading
h3
a(href='/results?cat=#{cat._id}&p=0') #{cat.name}
.panel-body
if cat.movies && cat.movies.length > 0
each item in cat.movies
.col-md-2
.thumbnail
a(href="/movie/#{item._id}")
if item.poster.indexOf('http:') > -1
img(src="#{item.poster}", alt="#{item.title}")
else
img(src="/upload/#{item.poster}", alt="#{item.title}")
.caption
h4 #{item.title}
p: a.btn.btn-primary(href="/movie/#{item._id}", role="button") 观看预告片
script(src='/build/admin.min.js')

  • request(发http请求)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    var request = require('request');

    //用法
    request({url: url, json: true}, function (error, response, body) {
    if (!error && response.statusCode === 200) {
    var data = body;
    var now = (new Date().getTime());
    var expires_in = now + (data.expires_in - 20) * 1000;
    data.expires_in = expires_in;
    resolve(data);
    //console.log(data);
    } else {
    reject('can not get ticket')
    }
    });

1

错误

1
request = Promise.promisify( require( ‘request’ ) )

调用
1
2
3
4
5
6
7
8
9
10
11
12
return new Promise(function(resolve, reject){
request({url: url, json: true} ).then (function ( 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);

})

})

**报错**:属性expires undefined

本来以为request promise化后可以用then函数,所以一开始没有怀疑then的使用

分析:expires没有定义,那么就跟data有关,data与response有关,假如没有获取的话,就会出错。那么,response是由request发请求后相应回来的数据,有理由怀疑是request使用的问题。
分析报错信息,一步步追根溯源,才能找出问题所在。

解决
Request的使用改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
return new Promise(function(resolve, reject){
request({url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var data = body;
var now = (new Date().getTime());
var expires_in = now + (data.expires_in - 20) * 1000;
data.expires_in = expires_in;
resolve(data);
console.log(data);
} else {
reject()
}
});
})

没有使用promise化的then函数

2

问题:客户端收不到微信服务器发来的消息,并显示”该公众号暂时无法提供服务“
为什么会这样呢?
第一步推断:假如微信服务器没有在5秒内接收到服务器发来的消息,会自动断开连接,重发请求,重复三次。所以可能是服务器或者代码程序的问题
进一步推断: 可是程序没有报错,昨天微信服务器是可以接受到第三方服务器的消息的。
反复的检查:发现发送过去的小xml格式如下:


<![CDATA[ o1PAWszjPU3zudiu7yxmNg7hLp00 ]]>
<![CDATA[ gh_4a832c2991ae ]]>

![CDATA][ ]里的内容是无法被服务器解析的,可是有一点很显眼,【】里面userId号的前面多了个空格,难道它连空格也不去除直接导致userId不正确,找不到用户吗??
二话不说,直接测试一下….
丫的,还果真如此!哈哈,xml格式还真TM的严格
以后一定要注意![CDATA][ ]里首字母不能有空格!

3

错误:上传永久素材时,回复客户端是出错,“改公众号无法提供服务”
解决:不一定是代码的问题,这是由于微信服务器在这一块不稳定,再试多一次就好了

前言

编写web离线应用,需要把应用文件和数据存在本地,也就是浏览器中。这主要用到了H5的三个重要的知识点,Application Cache(应用程序缓存), localStorage/sessionStorage(web存储), web SQL(web数据库)。

Application cache

如果要启用应用缓存,就需要在html标签加manifest属性

1
2
3
4
<!DOCTPYE HTML>
<html manifest="demo.appcache">
...
</html>

demo.appcache就是写需要缓存页面信息的manifest文件,文件的后缀名可以任写,但建议统一为.appcache。

manifest文件

告知浏览器需要(或不需要)缓存的文件,包括三部分:

  • CACHE MANIFEST 此标题下出现的文件将在首次下载后进行缓存
  • NETWORK 此标题下列出的文件需要在访问服务器,且不被缓存
  • FALLBACK 此标题下列出的文件是页面无法被访问时退回的页面

第一行写CACHE MANIFEST是必须的,写法为

1
2
3
4
CACHE MANIFEST
# 2017-06-10 v1.0.0
index.html
jqury.min.js

#后面的是注释,写上日期和版本号,当index.html等页面有更新时,改日期或者版本号,浏览器会将页面进行更新和缓存,方便。其中能应用默访问的页面,也就是index.html是默认被缓存的,不写也可以。一般写修改不频繁的文件

1
2
NETWORK:
*

一般写星号,也就是其他的页面都要通过访问服务器

1
2
FALLBACK:
/html/ /offline.html

如果无法建立因特网连接,则用 “offline.html” 替代 /html5/ 目录中的所有文件。

更新缓存的情况

  • 用户清空浏览器缓存
  • manifest文件被修改
  • 由程序文件来更新应用缓存

设置MIME-type

需要给manifest文件设置MIME-type为text/cache-manifest

  • 在Apache服务器
    可以在根目录下添加.htaccess文件
    1
    AddType text/cache-manifest manifest
    或者在manifest文件开头添加(前提是文件是php后缀名)
    1
    2
    3
    <?php
    header("Content-Type: text/cache-manifest");
    ?>
    ==貌似使用nodejs做后台不用设置MIME-type也可以将程序文件写进缓存==

localStorage/sessionStorage

在浏览器上(本地)储存用户的浏览数据
两者的区别就在于,localStorage储存的数据没有时间的限制,sessionStorage储存的数据,当关闭浏览器时,数据就没了。

两者的API都是相同的,主要有一下:

  • 保存数据:localStorage.setItem(key,value);
  • 读取数据:localStorage.getItem(key);
  • 删除单个数据:localStorage.removeItem(key);
  • 删除所有数据:localStorage.clear();
  • 得到某个索引的key:localStorage.key(index);
    保存数据还可以直接定义localStorage的属性,比如localStorage.resource = value
    一般储存变更频繁的文件

web SQL

位于浏览器中的关系型数据库
核心的方法就三个:

  • openDatabase:这个方法使用现有数据库或创建新数据库创建数据库对象。

  • transaction:这个方法允许我们根据情况控制事务提交或回滚,意思是可以划分事务。

  • executeSql:这个方法用于执行真实的SQL查询。

打开数据库

1
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

openDatebase方法接受五个参数,分别是:

  • 数据名称
  • 数据库版本(写死就行)
  • 数据库描述
  • 大小
  • 回调(可选)

插入和读取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "菜鸟教程")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "www.runoob.com")');
});

db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>查询记录条数: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;

for (i = 0; i < len; i++){
alert(results.rows.item(i).log );
}

}, null);
});

采用MVC思想写js代码

  • applicationcontroller.js //程序的入口程序主控制器,向外暴露一个start方法,作为程序的入口。其他的私有函数都是对次控制器暴露出的方法的调用

  • articlescontroller.js //操作articles模型,调用article暴露出的方法实现增删改查以及调用template的方法渲染页面

  • article.js //article模型,调用更底层的database对象(对数据库操作的封装)

  • database.js //更底层的M层,封装对数据库的操作

  • templates.js //V层,插入html节点

程序的入口就只有一个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//applicationController.js
//webapp的入口函数,类似C语言中的main,或者jq中的$(document).ready
function start(resources, storeResources) {
APP.database.open(function() {
//监听hash的变化
$(window).bind("hashchange", route);

//往DOM里添加CSS
$("head").append('<style>' + resources.css + '</style>');

//创造app应用名称节点
$('body').html(APP.templates.application());

//移除下载提示
$('#loading').remove();

route();
});

if(storeResources) {
localStorage.resources = JSON.stringify(resources);
}
}

在index.html调用
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
$(document).ready(function() {
console.log('ready %o', new Date()); //%o代替javascript对象

var APP_START_FAILED = "I'm sorry, the app can't start right now."

function startWithResources(resources, storeResources) {
//执行加载的js函数
try {
//eval(resources.js)
insertScript(resources.js);
setTimeout(function() {
APP.applicationController.start(resources, storeResources); //程序入口
}, 500);

} catch(e) {
alert(APP_START_FAILED);
console.log('%o', e);
}
}

function startWithOnlineResources(resources) {
startWithResources(resources, true);
}

function startWithOfflineResources() {
var resources;

//假如之前已经访问了并且js文件已经缓存进localStorage,执行以下
if(localStorage && localStorage.resources) {
resources = JSON.parse(localStorage.resources);
startWithResources(resources, false);

//否则输出提醒信息
}else {
alert(APP_START_FAILED);
}
}

function insertScript(script) {
var node = document.createElement('script');
node.innerHTML = script;
document.head.appendChild(node);
}

//假如设备离线,则执行离线操作
if(navigator && navigator.onLine === false) {
startWithOfflineResources();

//否则,下载资源并执行,假如成功就把资源添加进local storage。
}else {
$.ajax({
url: 'api/resources',
success: startWithOnlineResources,
error: startWithOfflineResources,
dataType: 'json'
});
}


})

程序的设计就类似于树形的结构:

1
2
3
4
5
6
graph TD
A[程序入口]-->B[主控制器]
B-->C[各种次控制器]
C-->D[模型]
C-->E[视图]
B-->E

主控制器的第一步工作是打开数据库

对象的封装

全局就一个APP对象,为window的全局变量

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
window.APP = {};
(function(APP){
APP.applicationController = (function(){
...

return {
start: start
}
}());

APP.articleController = (funcion(){
...

return {
synchronizeWithServer: synchronizeWithServer,
showArticle: showArticle,
showArticleList: showArticleList
}
}());



APP.templates = (function(){}(
...

return {
application: application,
home: home,
articleList: articleList,
article: article,
articleLoading: articleLoading
}

)()};

APP.database = (function(){}(
...

return {
open: open,
runQuery: runQuery
}
)()};

APP.article = (function(){}(
...

return {
deleteArticles: deleteArticles,
insertArticles: insertArticles,
selectBasicArticles: selectBasicArticles,
selectFullArticle: selectFullArticle
}
)()};
}(APP))

这里运用的JS的闭包思想,每一个(function(){…}()()};都是单独的作用域,代码不会被污染,全局就只有一个对象APP.

开发第一步

不是埋头就是实现各种逻辑,而是,划分好逻辑模块,思考各个模块的位置(目录位置),因为总不能将所有代码都放在app.js里,进而构成了整个项目的架构。

开发微信公众号,理解整个交互的流程。客户端 《 == 》微信服务器 《 == 》项目服务器

开发前的准备工作请详细看微信开发者文档,这里只讨论代码实现。

开始开发

我们使用koa框架。
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
'use strict'

var Koa = require('koa')
var wechat = require('./wechat/g') //可以看作是程序的第二个流程,实现验证 以及调用回复功能
var config = require('./config') //公众号的配置配置信息
var reply = require('./wx/reply') //处理客户发过来的消息,回复逻辑
var Wechat = require('./wechat/wechat') //回复各种消息类型获取的api,封装在Wechat对象中

var app = new Koa()

app.use(wechat(config.wechat, reply.reply))

app.listen(1234)
console.log("listening at port 1234...")

wechat/g.js

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
'use strict'

var sha1 = require('sha1')
var getRawBody = require('raw-body')
var Wechat = require('./wechat')
var util = require('./util')

module.exports = function(opts, handler) {
var wechat = new Wechat(opts)

return function *(next){

var token = opts.token
var signature = this.query.signature
var nonce = this.query.nonce
var timestamp = this.query.timestamp
var echostr = this.query.echostr
var str = [token, timestamp, nonce].sort().join('')
var sha = sha1(str)

if(this.method == 'GET'){
if(sha === signature){
this.body = echostr + ''
}
else{
this.body = 'wrong'
}
}
else if(this.method == 'POST'){
console.log(this.method)
if(sha !== signature){
this.body = 'wrong'

return false
}

var data = yield getRawBody(this.req, { //xml格式的数据
length: this.length,
limit: '1mb',
encoding: this.charset
})

//console.log(data.toString())
var content = yield util.parseXMLAsync(data) //转化为json格式的数据
//console.log(content)
var message = util.formatMessage(content.xml)
//console.log(message)

this.weixin = message

yield handler.call(this, next)

wechat.reply.call(this) //数据转化为最终的xml格式,客户端只能解析xml格式数据
}

}
}

wechat/wechat.js

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
'use strict'

var Promise = require('bluebird')
var request = require('request')
var util = require('./util')
var fs = require('fs')
var _ = require('lodash')

var prefix = 'https://api.weixin.qq.com/cgi-bin/'
var api = {
accessToken : prefix + 'token?grant_type=client_credential',
temporary: {
upload : prefix + 'media/upload?',
fetch: prefix + 'media/get?'
},
permanent: {
upload: prefix + 'material/add_material?',
fetch: prefix + 'material/get_material?',
uploadNews: prefix + 'material/add_news?',
uploadNewsPic:prefix + 'material/uploadimg?',
del: prefix + 'material/del_material?',
update: prefix + 'material/update_news?',
count: prefix + 'material/get_materialcount?',
batch: prefix + 'material/batchget_material?'
},
group: {
create: prefix + 'groups/create?',
fetch: prefix + 'groups/get?',
check: prefix + 'groups/getid?',
update:prefix + 'groups/update?',
move: prefix + 'groups/members/update?',
batchupdata: prefix + 'groups/members/batchupdate?',
del: prefix + 'groups/delete?'
},
user: {
remark: prefix + 'user/info/updateremark?',
fetch: prefix + 'user/info?',
batchFetch: prefix + 'user/info/batchget?',
list: prefix + 'user/get?'
},
mass: {
group: prefix + 'message/mass/sendall?',
openId: prefix + 'message/mass/send?',
del: prefix + 'message/mass/delete?',
preview: prefix + 'message/mass/preview?',
check: prefix + 'message/mass/get?'
},
menu: {
create: prefix + 'menu/create?',
get: prefix + 'menu/get?',
del: prefix + 'menu/delete?',
current: prefix + 'get_current_selfmenu_info?'
},
semantic: 'https://api.weixin.qq.com/semantic/semproxy/search?',
ticket: {
get : prefix + 'ticket/getticket?'
}

}

function Wechat(opts){
var that = this

this.appID = opts.appID
this.appSecret = opts.appSecret
this.getAccessToken = opts.getAccessToken
this.saveAccessToken = opts.saveAccessToken
this.getTicket = opts.getTicket
this.saveTicket = opts.saveTicket

this.fetchAccessToken()
}

//获取ticket
Wechat.prototype.fetchTicket = function(access_token){
var that = this

return this.getTicket()
.then(function(data){
try{
data = JSON.parse(data)
}
catch(e){
return that.updateTicket(access_token)
}

if(that.isValidTicket(data)){
return Promise.resolve(data)
}
else{
return that.updateTicket(access_token)
}
})
.then(function(data){
that.saveTicket(data)

return Promise.resolve(data)
})
}

Wechat.prototype.updateTicket = function(access_token){

var url = api.ticket.get + '&access_token=' + access_token + '&type=jsapi'

return new Promise(function(resolve, reject){
request({url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var data = body;
var now = (new Date().getTime());
var expires_in = now + (data.expires_in - 20) * 1000;
data.expires_in = expires_in;
resolve(data);
//console.log(data);
} else {
reject('can not get ticket')
}
});
})

}

Wechat.prototype.isValidTicket = function(data){
if(!data || !data.ticket || !data.expires_in){
return false
}

var ticket = data.ticket
var expires_in = data.expires_in
var now = (new Date().getTime())

if(ticket && now < expires_in){
return true
}
else{
return false
}
}

//获取access_token
Wechat.prototype.fetchAccessToken = function(data){
var that = this

if(this.access_token && this.expires_in){
if(this.isValidAccessToken(this)){
return Promise.resolve(this)
}
}

return this.getAccessToken()
.then(function(data){
try{
data = JSON.parse(data)
}
catch(e){
return that.updateAccessToken()
}

if(that.isValidAccessToken(data)){
return Promise.resolve(data)
}
else{
return that.updateAccessToken()
}
})
.then(function(data){
that.access_token = data.access_token
that.expires_in = data.expires_in

that.saveAccessToken(data)

return Promise.resolve(data)
})
}

Wechat.prototype.isValidAccessToken = function(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 = function(){
var appID = this.appID
var appSecret = this.appSecret
var url = api.accessToken + '&appid=' + appID + '&secret=' + appSecret

return new Promise(function(resolve, reject){
request({url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var data = body;
var now = (new Date().getTime());
var expires_in = now + (data.expires_in - 20) * 1000;
data.expires_in = expires_in;
resolve(data);
//console.log(data);
} else {
reject('can not get access_token')
}
});
})

}

Wechat.prototype.uploadMaterial = function(type, material, permanent){
var that = this
var form = {}
var uploadUrl = api.temporary.upload

if(permanent){
uploadUrl = api.permanent.upload

_.extend(form, permanent)
}

if(type === 'pic'){
uploadUrl = api.permanent.uploadNewsPic
}

if(type === 'news'){
uploadUrl = api.permanent.uploadNews
form = material
}
else{
form.media = fs.createReadStream(material)
}


return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = uploadUrl + 'access_token=' + data.access_token

if(!permanent) {
url += '&type=' + type
}
else{
form.access_token = data.access_token
}

var options = {
method: 'POST',
url: url,
json: true
}

if(type === 'news'){
options.body = form
}
else{
options.formData = form
}

request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}
//console.log(_data);
} else {
throw new Error('upload material fails')
}
})

})


})

}

Wechat.prototype.fetchMaterial = function(mediaId, type, permanent){
var that = this
var fetchUrl = api.temporary.fetch

if(permanent){
fetchUrl = api.permanent.fetch
}

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = fetchUrl + 'access_token=' + data.access_token
var form = {}
var options = {method:'POST', url: url, json: true}

if(permanent){
form.media_id = mediaId
form.access_token = data.access_token
options.body = form
}
else{
if(type === 'video'){
url = url.replace('https://', 'http://')
}
url += '&media_id=' + mediaId
}

if(type === 'news' || type === 'video'){
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('delete material fails')
}
})
}
else{
resolve(url)
}



})


})

}

Wechat.prototype.deleteMaterial = function(mediaId){
var that = this
var form = {
media_id:mediaId
}

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.permanent.del + 'access_token=' + data.access_token + '&media_id=' + mediaId

request({method:'POST', url: url, body:form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('delete material fails')
}
})
})
})
}

Wechat.prototype.updateMaterial = function(mediaId, news){
var that = this
var form = {
media_id:mediaId
}

_.extend(form, news)

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.permanent.update + 'access_token=' + data.access_token + '&media_id=' + mediaId

request({method:'POST', url: url, body:form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('delete material fails')
}
})
})
})
}

Wechat.prototype.countMaterial = function(){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.permanent.count + 'access_token=' + data.access_token

request({method:'GET', url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('count material fails')
}
})
})
})
}

Wechat.prototype.batchMaterial = function(options){
var that = this

options.type = options.type || 'image'
options.offset = options.offset || 0
options.count = options.count || 1

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.permanent.batch + 'access_token=' + data.access_token

request({method:'POST', url: url, body:options, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('batch material fails')
}
})
})
})
}

//用户分组
Wechat.prototype.createGroup = function(name){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.group.create + 'access_token=' + data.access_token
var form = {
group: {
name: name
}
}

request({method:'POST', url: url, body:form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('create group fails')
}
})
})
})
}

Wechat.prototype.fetchGroup = function(){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.group.fetch + 'access_token=' + data.access_token

request({url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('fetch group fails')
}
})
})
})
}

Wechat.prototype.checkGroup = function(openId){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.group.check + 'access_token=' + data.access_token
var form = {
openid : openId
}

request({method:'POST', url: url, body: form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('check group fails')
}
})
})
})
}

Wechat.prototype.updateGroup = function(id, name){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.group.update + 'access_token=' + data.access_token
var form = {
group: {
id: id,
name: name
}
}

request({method:'POST', url: url, body: form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('update group fails')
}
})
})
})
}

Wechat.prototype.moveGroup = function(openIds, to_groupid){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url
var form = {
to_groupid : to_groupid
}

if(_.isArray(openIds)){
url = api.group.batchupdata + 'access_token=' + data.access_token
form.openid_list = openIds
}
else{
url = api.group.move + 'access_token=' + data.access_token
form.openid = openIds
}

request({method:'POST', url: url, body: form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('move group fails')
}
})
})
})
}

Wechat.prototype.deleteGroup = function(id){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.group.del + 'access_token=' + data.access_token
var form = {
group: {
id: id
}
}

request({method:'POST', url: url, body: form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('delete group fails')
}
})
})
})
}

//获取用户信息
Wechat.prototype.remarkUser = function(openId, remark){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.user.remark + 'access_token=' + data.access_token
var form = {
openid: openId,
remark: remark
}

request({method:'POST', url: url, body: form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('remark user fails')
}
})
})
})
}

Wechat.prototype.fetchUser = function(openIds, lang){
var that = this

var lang = lang || 'zh_CN'


return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var options = {
json: true
}

if(_.isArray(openIds)){
options.url = api.user.batchFetch + 'access_token=' + data.access_token
options.method = 'POST'
options.body = {
user_list : openIds
}
}
else{
options.url = api.user.fetch + 'access_token=' + data.access_token + '&openid=' + openIds + '&lang=' + lang
}

request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('fetch users fails')
}
})
})
})
}

Wechat.prototype.listUsers = function(openId){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.user.list + 'access_token=' + data.access_token

if(openId){
url += '&next_openid=' + openId
}

request({method:'GET', url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('list users fails')
}
})
})
})
}

Wechat.prototype.sendByGroup = function(type, message, groupId){
var that = this
var msg = {
filter:{},
msgtype:type
}
msg[type] = message
if(!groupId){
msg.filter.is_to_all = true
}else{
msg.filter.is_to_all = false
msg.filter.group_id = groupId
}


return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.mass.group + 'access_token=' + data.access_token

request({method:'POST', url: url,body:msg, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('sell by group fails')
}
})
})
})
}

Wechat.prototype.sendByOpenId = function(type, message, openIds){
var that = this

var msg = {
touser:openIds,
msgtype:type
}

msg[type] = message

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.mass.openId + 'access_token=' + data.access_token

request({method:'POST', url: url, body:msg, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('sell by openid fails')
}
})
})
})
}

Wechat.prototype.deleteMass = function(msgId){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.mass.del + 'access_token=' + data.access_token
var form = {
msg_id : msgId
}

request({method:'POST', url: url,body:form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('delete Mass fails')
}
})
})
})
}

Wechat.prototype.previewMass = function(type, message, openId){
var that = this
var msg = {
touser:openId,
msgtype:type
}
msg[type] = message

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.mass.preview + 'access_token=' + data.access_token

request({method:'POST', url: url,body:msg, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('preview mass fails')
}
})
})
})
}

Wechat.prototype.checkMass = function(msgId){
var that = this
var form = {
msg_id : msgId
}

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.mass.check + 'access_token=' + data.access_token

request({method:'POST', url: url,body:form, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('check mass fails')
}
})
})
})
}

Wechat.prototype.createMenu = function(menu){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.menu.create + 'access_token=' + data.access_token

request({method:'POST', url: url,body:menu, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('create menu fails')
}
})
})
})
}

Wechat.prototype.getMenu = function(){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.menu.get + 'access_token=' + data.access_token

request({url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('get menu fails')
}
})
})
})
}

Wechat.prototype.deleteMenu = function(){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.menu.del + 'access_token=' + data.access_token

request({url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('delete menu fails')
}
})
})
})
}

Wechat.prototype.currentSelfMenu = function(){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.menu.current + 'access_token=' + data.access_token

request({url: url, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('get current selfmenu fails')
}
})
})
})
}

Wechat.prototype.semantic = function(semanticData){
var that = this

return new Promise(function(resolve, reject){
that
.fetchAccessToken()
.then(function(data){
var url = api.semantic + 'access_token=' + data.access_token
semanticData.appid = data.appID

request({method:'POST', url: url,body:semanticData, json: true}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var _data = body;

if(_data){
resolve(_data);
}

} else {
throw new Error('semantic data fails')
}
})
})
})
}

Wechat.prototype.reply = function(){ //实现完整的回复逻辑,放回给客户端xml格式数据
var content = this.body //此时的this.body是json数据格式
var message = this.weixin
var xml = util.tpl(content, message) //将content与message中的内容提出整合,此时已经变成了xml格式
//console.log('xml:'+ xml)

this.status = 200
this.type = 'application/xml'
this.body = xml

}

module.exports = Wechat

wx/reply.js 处理客户端消息

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
'use strict'

var config = require('../config')
var Wechat = require('../wechat/wechat')
var wechatApi = new Wechat(config.wechat)
var menu = require('./menu')

/*wechatApi.deleteMenu().then(function(){
return wechatApi.createMenu(menu)
}).then(function(msg){
console.log(msg)
})*/

exports.reply = function *(next){

var message = this.weixin

if(message.MsgType === 'event'){
if(message.Event === 'subscribe'){
if(message.EventKey) {
console.log('扫二维码进来:'+ message.EventKey +' '+ message.ticket)
}
this.body = '么么哒'
}
else if(message.Event === 'unsubscribe'){
console.log('无情取关!')
this.body = ' '
}
else if(message.Event === 'LOCATION'){
this.body = '您上报的位置是:' + message.Latitude + '/' + message.Longitude + '-' +message.Precision
}
else if(message.Event === 'CLICK'){
this.body = '您点击了菜单:'+ message.EventKey
}
else if(message.Event === 'SCAN'){
console.log('关注后扫二维码'+ message.EventKey + ' '+ message.Ticket)
this.body = '您扫了二维码哦'
}
else if(message.Event === 'VIEW'){
this.body = '您点击了菜单中的连接:'+ message.EventKey
}
else if(message.Event === 'scancode_push'){
console.log(message.ScanCodeInfo.ScanType)
console.log(message.ScanCodeInfo.ScanResult)
this.body = '您点击了菜单中的:'+ message.EventKey
}
else if(message.Event === 'scancode_waitmsg'){
console.log(message.ScanCodeInfo.ScanType)
console.log(message.ScanCodeInfo.ScanResult)
this.body = '您点击了菜单中的:'+ message.EventKey
}
else if(message.Event === 'pic_sysphoto'){
console.log(message.SendPicsInfo.Count)
console.log(message.SendPicsInfo.PicList)
this.body = '您点击了菜单中的:'+ message.EventKey
}
else if(message.Event === 'pic_photo_or_album'){
console.log(message.SendPicsInfo.Count)
console.log(message.SendPicsInfo.PicList)
this.body = '您点击了菜单中的:'+ message.EventKey
}
else if(message.Event === 'pic_weixin'){
console.log(message.SendPicsInfo.Count)
console.log(message.SendPicsInfo.PicList)
this.body = '您点击了菜单中的:'+ message.EventKey
}
else if(message.Event === 'location_select'){
console.log(message.SendLocationInfo.Location_X)
console.log(message.SendLocationInfo.Location_Y)
console.log(message.SendLocationInfo.Scale)
console.log(message.SendLocationInfo.Label)
console.log(message.SendLocationInfo.Poiname)
this.body = '您点击了菜单中的:'+ message.EventKey
}
}
else if(message.MsgType === 'text'){
var content = message.Content
var reply = '你说的“' + message.Content + '” 我们没有这样的服务'

if(content === '1'){
reply = '天下第一'
}
else if(content === '2'){
reply = '天下第二'
}
else if(content === '3'){
reply = '天下第三'
}
else if(content === '4'){
reply = [{
title: 'nodejs开发微信',
description: 'nodejs是服务器端的js脚本语言,用最火的技术开发微信公众号,你还等什么',
picUrl: 'http://www.aseoe.com/images/aseoe_nodejs_txal.jpg',
url: 'https://nodejs.org'
},{
title: '前端三大框架',
description: 'vue.js React.js angular.js是目前前端最火的三大框架',
picUrl: 'http://5xruby.tw/uploads/course/image/57/thumb_5x_VueJs-1024x768_5x.png',
url: 'https://cn.vuejs.org/'
}
]
}
else if(content === '5'){
var data = yield wechatApi.uploadMaterial('image', __dirname + '/2.jpg')

reply = {
type:'image',
mediaId: data.media_id
}
console.log(data.media_id)
}
else if(content === '6'){
var data = yield wechatApi.uploadMaterial('video', __dirname + '/6.mp4')

reply = {
type:'video',
title: '跪着唱征服',
description: '试试这是个怎样的感觉',
mediaId: data.media_id
}
}
else if(content === '7'){
var data = yield wechatApi.uploadMaterial('image', __dirname + '/2.jpg')

reply = {
type:'music',
title: '《李白》--李荣浩',
description: '轻松时刻',
musicUrl: 'http://link.hhtjim.com/163/27678655.mp3',
hqMusicUrl: 'http://link.hhtjim.com/163/27678655.mp3',
thumbMediaId: data.media_id
}
}
else if(content === '8'){
var data = yield wechatApi.uploadMaterial('image', __dirname + '/2.jpg',{type:'image'})

reply = {
type:'image',
mediaId: data.media_id
}
}
else if(content === '9'){
var data = yield wechatApi.uploadMaterial('video', __dirname + '/6.mp4',{type:'video', description:'{"title":"VIDEO_TITLE","introduction":"INTRODUCTION"}'})

reply = {
type:'video',
title: '跪着唱征服',
description: '试试这是个怎样的感觉',
mediaId: data.media_id
}
}
else if(content === '10'){
var picData = yield wechatApi.uploadMaterial('image', __dirname + '/2.jpg',{})

var media = {
articles:[{
title:'angularjs入门',
thumb_media_id:picData.media_id,
show_cover_pic:1,
author:'Leo',
digest:'关于angularjs摘要',
content:'augular是目前前端最火框架之一',
content_source_url:'https://docs.angularjs.org/'
}
]

}

var data = yield wechatApi.uploadMaterial('news', media, {})
console.log('我要的mediaId:'+ data.media_id)
data = yield wechatApi.fetchMaterial(data.media_id, 'news', {})

console.log(data)

var items = data.news_item
var news = []

items.forEach(function(item){
news.push({
title: item.title,
description: item.digest,
picUrl: picData.url,
url: item.url
})
})

reply = news

}
else if(content === '11'){
var counts = yield wechatApi.countMaterial()

console.log(JSON.stringify(counts))

var results = yield [
wechatApi.batchMaterial({
type: 'image',
offset: 0,
count: 10
}),
wechatApi.batchMaterial({
type: 'video',
offset: 0,
count: 10
}),
wechatApi.batchMaterial({
type: 'vioce',
offset: 0,
count: 10
}),
wechatApi.batchMaterial({
type: 'news',
offset: 0,
count: 10
})
]

console.log(JSON.stringify(results))

reply = 'ok'
}
else if(content === '12'){
/* var group1 = yield wechatApi.createGroup('wechat1')
console.log('新分组wechat1:')
console.log(group1)

var groups = yield wechatApi.fetchGroup()
console.log('加了wechat1的分组:')
console.log(groups)

var group2 = yield wechatApi.checkGroup(message.FromUserName)
console.log('查看自己的分组:')
console.log(group2)

var group3 = yield wechatApi.updateGroup(100, 'wechat_update')
console.log('把wechat1分组改为wechat_update')
console.log(group3)

groups = yield wechatApi.fetchGroup()
console.log('查看把wechat1分组改为wechat_update后的分组:')
console.log(groups)

var group4 = yield wechatApi.moveGroup(message.FromUserName, 2)
console.log('把我移动到2组')
console.log(group4)

groups = yield wechatApi.fetchGroup()
console.log('查看把我移动到2组后的分组:')
console.log(groups)

var group5 = yield wechatApi.moveGroup([message.FromUserName], 0)
console.log('批量移动 把我移动到0组')
console.log(group5)

var groups = yield wechatApi.fetchGroup()
console.log('查看 批量移动 把我移动到0组后的分组:')
console.log(groups)
*/
var groups = yield wechatApi.fetchGroup()
console.log(groups)
var group_delete = yield wechatApi.deleteGroup(101)
console.log('删除101')
console.log(group_delete)
groups = yield wechatApi.fetchGroup()
console.log('删除101后的分组')
console.log(groups)

reply = 'Groups done'

}
else if(content === '13'){
/* var remark = yield wechatApi.remarkUser(message.FromUserName, '超级大帅哥')
console.log(remark)
*/
var user = yield wechatApi.fetchUser(message.FromUserName)
console.log(user)

/* var openIds = [{
openid : message.FromUserName,
lang:'zh_CN'
}]
var users = yield wechatApi.fetchUser(openIds)
console.log(users)
*/
reply = JSON.stringify(user)

}
else if(content === '14'){
var list = yield wechatApi.listUsers()
console.log(list)

reply = list.total
}
else if(content === '15'){
var mpnews = {
media_id : 'fTn2AjmZW41YaIc0iw-86l9rCE_Ex4LNtT_SXvISNFQ'
}

var text = {
content: '天要下雨了'
}

var msgData = yield wechatApi.sendByGroup('text', text, 0)

console.log(msgData)
reply = '内容如下'
}
else if(content === '16'){
var mpnews = {
media_id : 'fTn2AjmZW41YaIc0iw-86l9rCE_Ex4LNtT_SXvISNFQ'
}

/* var text = {
content: '天一直在打雷还没下雨'
}
*/
var msgData = yield wechatApi.previewMass('mpnews', mpnews, 'okFRawx2UAkxdtKG1i9QNGzgXLA4')

console.log(msgData)
reply = '内容如下'
}
else if(content === '17'){
var msgData = yield wechatApi.checkMass('1000000010')
console.log(msgData)
reply = 'done'
}
else if(content === '18'){

wechatApi.createMenu(menu).then(function(msg){
console.log('菜单生成状态:'+ JSON.stringify(msg))
})
/*var createMenu = yield wechatApi.createMenu(menu)
console.log(createMenu)
*/
reply = 'done'
}
else if(content === '19'){
var semanticData = {
query:"查一下明天从北京到上海的南航机票",
city:"北京",
category: "flight,hotel",
uid: message.FromUserName
}

var _semantic = yield wechatApi.semantic(semanticData)
console.log(_semantic)
reply = JSON.stringify(_semantic)
}

this.body = reply
}


yield next
}

在koa中使用ejs模板 与 heredoc模块

heredoc模块是作用是封装模板
比如:

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
'use strict'

var ejs = require('ejs')
var heredoc = require('heredoc')

var tpl = heredoc(function(){/*
<xml>
<ToUserName><![CDATA[<%= toUserName %>]]></ToUserName>
<FromUserName><![CDATA[<%= fromUserName %>]]></FromUserName>
<CreateTime> <%= createTime %> </CreateTime>
<MsgType><![CDATA[<%= msgType%>]]></MsgType>
<% if (msgType === 'text') {%>
<Content><![CDATA[<%= content%>]]></Content>
<% } else if(msgType === 'image') { %>
<Image>
<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
</Image>
<% } else if(msgType === 'video') { %>
<Video>
<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
<Title><![CDATA[<%= content.title %>]]></Title>
<Description><![CDATA[<%= content.description %>]]></Description>
</Video>
<% } else if(msgType === 'voice') { %>
<Voice>
<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
</Voice>
<% } else if(msgType === 'music') { %>
<Music>
<Title><![CDATA[<%= content.title %>]]></Title>
<Description><![CDATA[<%= content.description %>]]></Description>
<MusicUrl><![CDATA[<%= content.musicUrl %>]]></MusicUrl>
<HQMusicUrl><![CDATA[<%= content.hqMusicUrl%>]]></HQMusicUrl>
<ThumbMediaId><![CDATA[<%= content.thumbMediaId %>]]></ThumbMediaId>
</Music>
<% } else if(msgType === 'news') { %>
<ArticleCount><%= content.length %></ArticleCount>
<Articles>
<% content.forEach(function(item){ %>
<item>
<Title><![CDATA[<%= item.title %>]]></Title>
<Description><![CDATA[<%= item.description %>]]></Description>
<PicUrl><![CDATA[<%= item.picUrl %>]]></PicUrl>
<Url><![CDATA[<%= item.url %>]]></Url>
</item>
<% }) %>
</Articles>
<% } %>
</xml>

*/})

var compiled = ejs.compile(tpl)

exports = module.exports = {
compiled : compiled
}

以上暴露了compiled方法,但只是做好了封装模板而已,还缺少json格式数据
结合json数据

1
2
3
4
5
6
7
8
var tpl = require('以上文件路径')

var data = {
msgType : 'text',
content : 'hello world'
}

var xml = tpl.compiled(data)

或者可以使用render方法将模板和数据一并结合
1
var xml = ejs.render(tpl, data)


这篇文档算不上很好的教程,只是将开发过程的关键代码展示了出来,还有介绍了,heredoc封装xml模板,理解了用法。

其实做好的教程是,渐进式的从头到尾开发微信公众号,使流程变得清晰杳然,能学到更多。但是鉴于个人微信公众号无法认证,缺失了很有接口权限,申请的测试公众号配置时常出问题,开发困难,时间成本开销很大。所以只展示了关键代码。

思考了一下,项目的关键点可以写个渐进式的教程,展示开发的优化过程,让自己更深入理解知识点。

这篇笔记就写到这吧,全部代码放在github上。

前言

花了差不多一周的时间,用html5的新标签audio制作了一个音乐播放器,感觉最多坑的地方在于前期的布局,逻辑代码的规划也很重要。

在布局上填了很多坑,比如资源税浮动父元素没了高度,用clear也解决不了,不得不利用js设置父的高度等之类的,发现布局也有大学问,这一点要注重。

第二点就是代码规划,因为刚学了前端js的MVC框架(将控制逻辑,模型,视图的js划分开),所以想尝试,在项目里我的mvc框架为:

  • controller/appController.js 控制器总开关,程序的入 口,将controllers连接起来
  • controller/playerController.js 播放器的控制器
  • view/pageStyle.js 页面样式的改变逻辑
  • view/scale.js 进度条对象
  • songs.js 全局的songs模型

结合面向对象的方法,我在点击播放器按钮的时候,进度条,图片旋转和audio同时开始工作,所以把他们捆绑起来会比较好。

下面就这个项目里一些零散的知识点做些记录,以便一下使用。

圣杯布局

圣杯布局是三栏布局的经典布局方式,两侧固定宽度中间自适应。

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
<div class="both">
<div class="middle">中间</div> //优先加载
<div class="left">左边</div>
<div class="right">右边</div>
</div>

<style>
.box{
padding-left: 250px; //关键
padding-right: 250px; //关键
line-height: 200px;
text-align: center;
color: #fff;
}
.box:before,.box:after{ //伪类清除浮动,父元素有高度
content: '.';
display: block;
clear: both;
height: 0
visibility: hidden; //元素不可见,但占据空间
}
.middle,.left,.right{
float: left;
height: 200px;
}
.middle{
width: 100%;
background-color: red;
}
.left{
width: 250px;
background-color: blue;
margin-left: -250px; //关键
}
.right{
width: 250px;
background-color: yellow;
margin-right: -250px; //关键
}
</style>

三栏布局的另一经典是双飞翼布局,原理是middlediv下内嵌类为inner的div,利用inner的margin-left和margin-right。左右侧栏div分别float左右。
另一种方法是利用定位:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  <style>
body{margin:0; padding:0;}
#left{float:left;width:150px;background:red;}
#right{float:right;width:200px;background:green;}
#middle{
position:absolute; //关键
left:150px;
right:200px;
word-wrap:break-word; //让字体打断,不会超出div
background:blue;
}
</style>

<div id="middle">
middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;
middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;middle;
</div>
<div id="left">left</div>
<div id="right">right</div>

关于布局,还有很多种,请参考:
http://blog.csdn.net/andiqu/article/details/50045609
关注弹性布局(flex),和rem

animition的播放和暂停

1
-webkit-animation-play-state: running | paused
1
2
3
animation-fill-mode: backwards | forwards | both; //播放前显示动画第一帧,播放完显示动画的最后一帧,向前和向后模式都被应用
animation-direction: reverse | alternate; //播放顺序,resverse反向
animation-iteration-count: num | infinite // 2 | 循环

进度条的制作

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
<ul id="lanren">
<li class="curr">00:00</li>
<li class="progress">
<div class="scale" id="bar">
<div></div>
<span id="btn"></span>
</div>
</li>
<li class="total">00:10</li>
</ul>

<style>
body{margin:0;padding:0;font-size:12px;}
ul#lanren{ margin:50px auto; overflow: hidden; padding: 0 50px 0 50px;}
#lanren li{font-size:12px;line-height:24px; height:24px;list-style:none; position: relative; float: left;}
li.progress{
width: 100%;
}
li.curr{
width: 50px;
margin-right: -50px;
left: -50px;
text-align: center;
}
li.total{
width: 50px;
margin-left: -50px;
right: -50px;
text-align: center;
}
.scale{ background-color: #E4E4E4; border-left: 1px #83BBD9 solid; width: 100%; height: 3px; position: relative; font-size: 0px; border-radius: 3px; top:11px;}

.scale span{width:8px;height:8px;position:absolute;left:-2px;top:-2.5px;cursor:pointer; background-color: #000; display: inline-block; -webkit-border-radius: 50%;}

.scale div{ background-color: #3BE3FF; width: 0px; position: absolute; height: 3px; width: 0; left: 0; bottom: 0; }
</style>

播放按钮的制作和发光动画

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<div class="playContainer">
<li class="rewindBtn">
<a href="javascript:;" title="rewind">Rewind</a>
<a href="javascript:;" title="rewind">Rewind</a>
</li>
<li class="playBtn BtnBig">
<a href="javascript:;" title="start">Start</a>
</li>
<!--
<li class="pauseBtn">
<a href="#" title="pause">Pause</a>
</li>
-->

<li class="forwardBtn playBtn">
<a href="javascript:;" title="forward">Forward</a>
<a href="javascript:;" title="forward">Forward</a>
</li>
</div>

<style>
.playContainer li {
position: relative;
float: left;
border: 50px solid #404040;
border-color: rgba(119, 119, 119, 0.3);
color: transparent;
height: 0;
width: 0;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
-o-border-radius: 100%;
border-radius: 100%;
margin: 0 50px;
}
.playContainer a {
border-style: solid;
text-indent: -9999px;
position: absolute;
top: -16px;
left: -6px;
}
li.BtnBig{
border-width: 70px;
margin-top: -15px;
}
.playBtn a {
border-color: transparent transparent transparent #fff;
width: 0;
height: 0;
border-width: 24px 0 24px 36px;
left: -10px;
top: -22px;
}
.pauseBtn a {
border-color: transparent white;
border-width: 0 14px;
height: 36px;
width: 12px;
left: -20px;
}
.forwardBtn a {
border-left-width: 16px;
left: 2px;
border-width: 16px 0 16px 16px;
top: -15px;
}
.forwardBtn a:first-child {
margin-left: -14px;
}
.rewindBtn a {
border-width: 16px 16px 16px 0;
border-color: transparent #fff transparent transparent;
width: 0;
height: 0;
}
.rewindBtn a:first-child {
margin-left: -14px;
}

//发光动画
@-webkit-keyframes bs {
0% {
box-shadow: inset -1px 1px 3px 2px #444444, inset 1px -1px 3px 2px #222222, 0 0 0px 0 #787776;
}

50% {
box-shadow: inset -1px 1px 3px 2px #444444, inset 1px -1px 3px 2px #222222, 0 0 40px 0 #ffffff;
}

100% {
box-shadow: inset -1px 1px 3px 2px #444444, inset 1px -1px 3px 2px #222222, 0 0 0px 0 #b2ff1a;
}
}
</style>


URI编码

url里的中文服务器是识别不了的,要经过URI编码成Unicode编码,统一资源标识符,浏览器才能准确的找到资源。

1
2
3
4
5
encodeURI("春节") //%DD%DD%DD
decodeURI("%DD%DD%DD") //解码:春节
相同:
escape()
unescape()

ajax跨域

不涉及后台的跨域,直接用ajax发http请求:
https://bird.ioliu.cn/#interface
其他的跨域都要设计到后台
与jsonp有关

QQ音乐的API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
songsAPI = http://s.music.qq.com/fcgi-bin/music_search_new_platform?t=0&n=10&aggr=1&cr=1&loginUin=0&format=json&inCharset=GB2312&outCharset=utf-8&notice=0&platform=jqminiframe.json&needNewCode=0&p=1&catZhida=0&remoteplace=sizer.newclient.next_song&w={0}

n= 10 ,搜索的数据条目
w= content ,搜索内容
返回的数据中有个f属性,
DATA.data.song.list[i].f: xxx|xxx|xxx.....
其中第一个是songID,第五个是imgID


imgAPI = http://imgcache.qq.com/music/photo/album_500/imgID后面两个数/500_albumpic_imgID_0.jpg

500是图片的大小,支持300500



srcAPI = http://210.38.1.134:9999/ws.stream.qqmusic.qq.com/songID.m4a?fromtag=46

计时器

当在页面要多次用到定时器时,可以考虑把它挂载到全局。
当用到多个计时器是可以把它放在一个数组里,方便管理。

百度到的资源

专门说进度条的网站:https://usablica.github.io/progress.js/
js,jq获取div高度:http://www.cnblogs.com/xiaopin/archive/2012/03/26/2418152.html
获取div的margin,border,padding,content的宽高
js控制audio标签:http://blog.csdn.net/u014520745/article/details/52412427