小程序-demo:小程序示例

久未见 提交于 2019-12-23 05:08:05
ylbtech-小程序-demo:小程序示例

 

 
 

 

1.返回顶部
0、
1、app.js
const openIdUrl = require('./config').openIdUrl

App({
  onLaunch: function () {
    console.log('App Launch')
  },
  onShow: function () {
    console.log('App Show')
  },
  onHide: function () {
    console.log('App Hide')
  },
  globalData: {
    hasLogin: false,
    openid: null
  },
  // lazy loading openid
  getUserOpenId: function(callback) {
    var self = this

    if (self.globalData.openid) {
      callback(null, self.globalData.openid)
    } else {
      wx.login({
        success: function(data) {
          wx.request({
            url: openIdUrl,
            data: {
              code: data.code
            },
            success: function(res) {
              console.log('拉取openid成功', res)
              self.globalData.openid = res.data.openid
              callback(null, self.globalData.openid)
            },
            fail: function(res) {
              console.log('拉取用户openid失败,将无法正常使用开放接口等服务', res)
              callback(res)
            }
          })
        },
        fail: function(err) {
          console.log('wx.login 接口调用失败,将无法正常使用开放接口等服务', err)
          callback(err)
        }
      })
    }
  }
})
2、app.json
{
  "pages": [
    "page/component/index",

    "page/component/pages/view/view",
    "page/component/pages/scroll-view/scroll-view",
    "page/component/pages/swiper/swiper",

    "page/component/pages/text/text",
    "page/component/pages/icon/icon",
    "page/component/pages/progress/progress",

    "page/component/pages/button/button",
    "page/component/pages/checkbox/checkbox",
    "page/component/pages/form/form",
    "page/component/pages/input/input",
    "page/component/pages/label/label",
    "page/component/pages/picker/picker",
    "page/component/pages/radio/radio",
    "page/component/pages/slider/slider",
    "page/component/pages/switch/switch",
    "page/component/pages/textarea/textarea",

    "page/component/pages/navigator/navigator",
    "page/component/pages/navigator/navigate",
    "page/component/pages/navigator/redirect",

    "page/component/pages/image/image",
    "page/component/pages/audio/audio",
    "page/component/pages/video/video",

    "page/component/pages/map/map",

    "page/component/pages/canvas/canvas",



    "page/API/index",

    "page/API/pages/login/login",
    "page/API/pages/get-user-info/get-user-info",
    "page/API/pages/request-payment/request-payment",
    "page/API/pages/share/share",
    "page/API/pages/custom-message/custom-message",
    "page/API/pages/template-message/template-message",

    "page/API/pages/set-navigation-bar-title/set-navigation-bar-title",
    "page/API/pages/navigation-bar-loading/navigation-bar-loading",
    "page/API/pages/navigator/navigator",
    "page/API/pages/pull-down-refresh/pull-down-refresh",
    "page/API/pages/animation/animation",

    "page/API/pages/action-sheet/action-sheet",
    "page/API/pages/modal/modal",
    "page/API/pages/toast/toast",

    "page/API/pages/get-network-type/get-network-type",
    "page/API/pages/get-system-info/get-system-info",
    "page/API/pages/on-compass-change/on-compass-change",
    "page/API/pages/make-phone-call/make-phone-call",
    "page/API/pages/scan-code/scan-code",


    "page/API/pages/request/request",
    "page/API/pages/web-socket/web-socket",
    "page/API/pages/upload-file/upload-file",
    "page/API/pages/download-file/download-file",


    "page/API/pages/image/image",
    "page/API/pages/voice/voice",
    "page/API/pages/file/file",
    "page/API/pages/on-accelerometer-change/on-accelerometer-change",
    "page/API/pages/canvas/canvas",
    "page/API/pages/background-audio/background-audio",
    "page/API/pages/video/video",

    "page/API/pages/get-location/get-location",
    "page/API/pages/open-location/open-location",
    "page/API/pages/choose-location/choose-location",

    "page/API/pages/storage/storage"
  ],
  "window": {
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "演示",
    "navigationBarBackgroundColor": "#F8F8F8",
    "backgroundColor": "#F8F8F8"
  },
  "tabBar": {
    "color": "#7A7E83",
    "selectedColor": "#3cc51f",
    "borderStyle": "black",
    "backgroundColor": "#ffffff",
    "list": [{
      "pagePath": "page/component/index",
      "iconPath": "image/icon_component.png",
      "selectedIconPath": "image/icon_component_HL.png",
      "text": "组件"
    }, {
      "pagePath": "page/API/index",
      "iconPath": "image/icon_API.png",
      "selectedIconPath": "image/icon_API_HL.png",
      "text": "接口"
    }]
  },
  "networkTimeout": {
    "request": 10000,
    "connectSocket": 10000,
    "uploadFile": 10000,
    "downloadFile": 10000
  },
  "debug": false
}
3、app.wxss
/* reset */
page {
  background-color: #F8F8F8;
  height: 100%;
  font-size: 32rpx;
  line-height: 1.6;
}
checkbox, radio{
  margin-right: 10rpx;
}
button{
  margin-top: 20rpx;
  margin-bottom: 20rpx;
}
form{
  width: 100%;
}

/* lib */
.strong{
  font-weight: bold;
}
.tc{
  text-align: center;
}

/* page */
.container {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  justify-content: space-between;
  font-size: 32rpx;
  font-family: -apple-system-font,Helvetica Neue,Helvetica,sans-serif;
}
.page-head{
  padding: 60rpx 50rpx 80rpx;
  text-align: center;
}
.page-head-title{
  display: inline-block;
  padding: 0 40rpx 20rpx 40rpx;
  font-size: 32rpx;
  color: #BEBEBE;
}
.page-head-line{
  margin: 0 auto;
  width: 150rpx;
  height: 2rpx;
  background-color: #D8D8D8;
}
.page-head-desc{
  padding-top: 20rpx;
  color: #9B9B9B;
  font-size: 32rpx;
}

.page-body {
  width: 100%;
  flex-grow: 1;
  overflow-x: hidden;
}
.page-body-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.page-body-wording {
  text-align: center;
  padding: 200rpx 100rpx;
}
.page-body-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  width: 100%;
  padding: 50rpx 0 150rpx 0;
}
.page-body-title {
  margin-bottom: 100rpx;
  font-size: 32rpx;
}
.page-body-text {
  font-size: 30rpx;
  line-height: 26px;
  color: #ccc;
}
.page-body-text-small {
  font-size: 24rpx;
  color: #000;
  margin-bottom: 100rpx;
}

.page-foot{
  margin: 100rpx 0 30rpx 0;
  text-align: center;
  color: #1aad19;
  font-size: 0;
}
.icon-foot{
  width: 152rpx;
  height: 23rpx;
}

.page-section{
  width: 100%;
  margin-bottom: 60rpx;
}
.page-section_center{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.page-section:last-child{
  margin-bottom: 0;
}
.page-section-gap{
  box-sizing: border-box;
  padding: 0 30rpx;
}
.page-section-spacing{
  box-sizing: border-box;
  padding: 0 80rpx;
}
.page-section-title{
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 10rpx;
  padding-left: 30rpx;
  padding-right: 30rpx;
}
.page-section-gap .page-section-title{
  padding-left: 0;
  padding-right: 0;
}
.page-section-ctn{

}

/* widget */
.btn-area{
  margin-top: 60rpx;
  box-sizing: border-box;
  width: 100%;
  padding: 0 30rpx;
}

.image-plus {
  width: 150rpx;
  height: 150rpx;
  border: 2rpx solid #D9D9D9;
  position: relative;
}
.image-plus-nb{
  border: 0;
}
.image-plus-text{
  color: #888888;
  font-size: 28rpx;
}
.image-plus-horizontal {
  position: absolute;
  top: 50%;
  left: 50%;
  background-color: #d9d9d9;
  width: 4rpx;
  height: 80rpx;
  transform: translate(-50%, -50%);
}
.image-plus-vertical {
  position: absolute;
  top: 50%;
  left: 50%;
  background-color: #d9d9d9;
  width: 80rpx;
  height: 4rpx;
  transform: translate(-50%, -50%);
}

.demo-text-1{
  position: relative;
  align-items: center;
  justify-content: center;
  background-color: #1AAD19;
  color: #FFFFFF;
  font-size: 36rpx;
}
.demo-text-1:before{
  content: 'A';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.demo-text-2{
  position: relative;
  align-items: center;
  justify-content: center;
  background-color: #2782D7;
  color: #FFFFFF;
  font-size: 36rpx;
}
.demo-text-2:before{
  content: 'B';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.demo-text-3{
  position: relative;
  align-items: center;
  justify-content: center;
  background-color: #F1F1F1;
  color: #353535;
  font-size: 36rpx;
}
.demo-text-3:before{
  content: 'C';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
4、config.js
/**
 * 小程序配置文件
 */

// 此处主机域名是腾讯云解决方案分配的域名
// 小程序后台服务解决方案:https://www.qcloud.com/solution/la

var host = "14592619.qcloud.la"

var config = {

    // 下面的地址配合云端 Server 工作
    host,

    // 登录地址,用于建立会话
    loginUrl: `https://${host}/login`,

    // 测试的请求地址,用于测试会话
    requestUrl: `https://${host}/testRequest`,

    // 用code换取openId
    openIdUrl: `https://${host}/openid`,

    // 测试的信道服务接口
    tunnelUrl: `https://${host}/tunnel`,

    // 生成支付订单的接口
    paymentUrl: `https://${host}/payment`,

    // 发送模板消息接口
    templateMessageUrl: `https://${host}/templateMessage`,

    // 上传文件接口
    uploadFileUrl: `https://${host}/upload`,

    // 下载示例图片接口
    downloadExampleUrl: `https://${host}/static/weapp.jpg`
};

module.exports = config
4、project.config.json
{
    "description": "项目配置文件。",
    "setting": {
        "urlCheck": true,
        "es6": true,
        "postcss": true,
        "minified": true,
        "newFeature": true
    },
    "compileType": "miniprogram",
    "libVersion": "1.6.4",
    "appid": "wx7d22ab7088f2db6a",
    "projectname": "wechatApp",
    "condition": {
        "search": {
            "current": -1,
            "list": []
        },
        "conversation": {
            "current": -1,
            "list": []
        },
        "miniprogram": {
            "current": -1,
            "list": []
        }
    }
}
5、image
6、page
7、utll
-util.js
function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  var hour = parseInt(time / 3600)
  time = time % 3600
  var minute = parseInt(time / 60)
  time = time % 60
  var second = time

  return ([hour, minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}

function formatLocation(longitude, latitude) {
  if (typeof longitude === 'string' && typeof latitude === 'string') {
    longitude = parseFloat(longitude)
    latitude = parseFloat(latitude)
  }

  longitude = longitude.toFixed(2)
  latitude = latitude.toFixed(2)

  return {
    longitude: longitude.toString().split('.'),
    latitude: latitude.toString().split('.')
  }
}

module.exports = {
  formatTime: formatTime,
  formatLocation: formatLocation
}
8、vendor
9、
2. vendor返回顶部
1、qcloud-weapp-client-sdk
1.1、lib
-constants.js
module.exports = {
    WX_HEADER_CODE: 'X-WX-Code',
    WX_HEADER_ENCRYPTED_DATA: 'X-WX-Encrypted-Data',
    WX_HEADER_IV: 'X-WX-IV',
    WX_HEADER_ID: 'X-WX-Id',
    WX_HEADER_SKEY: 'X-WX-Skey',

    WX_SESSION_MAGIC_ID: 'F2C224D4-2BCE-4C64-AF9F-A6D872000D1A',

    ERR_INVALID_PARAMS: 'ERR_INVALID_PARAMS',

    ERR_WX_LOGIN_FAILED: 'ERR_WX_LOGIN_FAILED',
    ERR_WX_GET_USER_INFO: 'ERR_WX_GET_USER_INFO',
    ERR_LOGIN_TIMEOUT: 'ERR_LOGIN_TIMEOUT',
    ERR_LOGIN_FAILED: 'ERR_LOGIN_FAILED',
    ERR_LOGIN_SESSION_NOT_RECEIVED: 'ERR_LOGIN_MISSING_SESSION',

    ERR_INVALID_SESSION: 'ERR_INVALID_SESSION',
    ERR_CHECK_LOGIN_FAILED: 'ERR_CHECK_LOGIN_FAILED',
};
-login.js
-request.js
var constants = require('./constants');
var utils = require('./utils');
var Session = require('./session');
var loginLib = require('./login');

var noop = function noop() {};

var buildAuthHeader = function buildAuthHeader(session) {
    var header = {};

    if (session && session.id && session.skey) {
        header[constants.WX_HEADER_ID] = session.id;
        header[constants.WX_HEADER_SKEY] = session.skey;
    }

    return header;
};

/***
 * @class
 * 表示请求过程中发生的异常
 */
var RequestError = (function () {
    function RequestError(type, message) {
        Error.call(this, message);
        this.type = type;
        this.message = message;
    }

    RequestError.prototype = new Error();
    RequestError.prototype.constructor = RequestError;

    return RequestError;
})();

function request(options) {
    if (typeof options !== 'object') {
        var message = '请求传参应为 object 类型,但实际传了 ' + (typeof options) + ' 类型';
        throw new RequestError(constants.ERR_INVALID_PARAMS, message);
    }

    var requireLogin = options.login;
    var success = options.success || noop;
    var fail = options.fail || noop;
    var complete = options.complete || noop;
    var originHeader = options.header || {};

    // 成功回调
    var callSuccess = function () {
        success.apply(null, arguments);
        complete.apply(null, arguments);
    };

    // 失败回调
    var callFail = function (error) {
        fail.call(null, error);
        complete.call(null, error);
    };

    // 是否已经进行过重试
    var hasRetried = false;

    if (requireLogin) {
        doRequestWithLogin();
    } else {
        doRequest();
    }

    // 登录后再请求
    function doRequestWithLogin() {
        loginLib.login({ success: doRequest, fail: callFail });
    }

    // 实际进行请求的方法
    function doRequest() {
        var authHeader = buildAuthHeader(Session.get());

        wx.request(utils.extend({}, options, {
            header: utils.extend({}, originHeader, authHeader),

            success: function (response) {
                var data = response.data;

                // 如果响应的数据里面包含 SDK Magic ID,表示被服务端 SDK 处理过,此时一定包含登录态失败的信息
                if (data && data[constants.WX_SESSION_MAGIC_ID]) {
                    // 清除登录态
                    Session.clear();

                    var error, message;
                    if (data.error === constants.ERR_INVALID_SESSION) {
                        // 如果是登录态无效,并且还没重试过,会尝试登录后刷新凭据重新请求
                        if (!hasRetried) {
                            hasRetried = true;
                            doRequestWithLogin();
                            return;
                        }

                        message = '登录态已过期';
                        error = new RequestError(data.error, message);

                    } else {
                        message = '鉴权服务器检查登录态发生错误(' + (data.error || 'OTHER') + '):' + (data.message || '未知错误');
                        error = new RequestError(constants.ERR_CHECK_LOGIN_FAILED, message);
                    }

                    callFail(error);
                    return;
                }

                callSuccess.apply(null, arguments);
            },

            fail: callFail,
            complete: noop,
        }));
    };

};

module.exports = {
    RequestError: RequestError,
    request: request,
};
-session.js
var constants = require('./constants');
var SESSION_KEY = 'weapp_session_' + constants.WX_SESSION_MAGIC_ID;

var Session = {
    get: function () {
        return wx.getStorageSync(SESSION_KEY) || null;
    },

    set: function (session) {
        wx.setStorageSync(SESSION_KEY, session);
    },

    clear: function () {
        wx.removeStorageSync(SESSION_KEY);
    },
};

module.exports = Session;
-utils.js
/**
 * 拓展对象
 */
exports.extend = function extend(target) {
    var sources = Array.prototype.slice.call(arguments, 1);

    for (var i = 0; i < sources.length; i += 1) {
        var source = sources[i];
        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key];
            }
        }
    }

    return target;
};
-wxTunnel.js
/* istanbul ignore next */
const noop = () => void(0);

let onOpen, onClose, onMessage, onError;

/* istanbul ignore next */
function listen(listener) {
    if (listener) {
        onOpen = listener.onOpen;
        onClose = listener.onClose;
        onMessage = listener.onMessage;
        onError = listener.onError;
    } else {
        onOpen = noop;
        onClose = noop;
        onMessage = noop;
        onError = noop;
    }
}

/* istanbul ignore next */
function bind() {
    wx.onSocketOpen(result => onOpen(result));
    wx.onSocketClose(result => onClose(result));
    wx.onSocketMessage(result => onMessage(result));
    wx.onSocketError(error => onError(error));
}

listen(null);
bind();

module.exports = { listen };
1.2、.bower.json
{
  "name": "qcloud-weapp-client-sdk",
  "description": "QCloud 微信小程序客户端 SDK",
  "main": "index.js",
  "authors": [
    "Tencent Cloud"
  ],
  "license": "MIT",
  "keywords": [
    "qcloud",
    "weapp",
    "wechat",
    "sdk",
    "client",
    "auth",
    "websocket"
  ],
  "homepage": "https://github.com/tencentyun/weapp-client-sdk",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests",
    "typings.json",
    "jsconfig.json",
    "package.json",
    ".npmignore",
    ".travis.yml",
    ".gitignore"
  ],
  "version": "0.8.2",
  "_release": "0.8.2",
  "_resolution": {
    "type": "version",
    "tag": "v0.8.2",
    "commit": "0944545afe0b6bc4aec8c39e8437dbe95a07a8d9"
  },
  "_source": "https://github.com/tencentyun/weapp-client-sdk.git",
  "_target": "*",
  "_originalSource": "qcloud-weapp-client-sdk"
}
1.3、LICENSE
1.4、README.md
# 微信小程序客户端腾讯云增强 SDK

[![Build Status](https://travis-ci.org/tencentyun/wafer-client-sdk.svg?branch=master)](https://travis-ci.org/tencentyun/wafer-client-sdk)
[![Coverage Status](https://coveralls.io/repos/github/tencentyun/wafer-client-sdk/badge.svg?branch=master)](https://coveralls.io/github/tencentyun/wafer-client-sdk?branch=master)
[![License](https://img.shields.io/github/license/tencentyun/wafer-client-sdk.svg)](LICENSE)

本 项目是 [Wafer](https://github.com/tencentyun/wafer-solution) 的组成部分,为小程序客户端开发提供 SDK 支持会话服务和信道服务。

## SDK 获取与安装

解决方案[客户端 Demo](https://github.com/tencentyun/wafer-client-demo) 已经集成并使用最新版的 SDK,需要快速了解的可以从 Demo 开始。

如果需要单独开始,本 SDK 已经发布为 bower 模块,可以直接安装到小程序目录中。

```sh
npm install -g bower
bower install qcloud-weapp-client-sdk
```

安装之后,就可以使用 `require` 引用 SDK 模块:

```js
var qcloud = require('./bower_components/qcloud-weapp-client-sdk/index.js');
```

## 会话服务

[会话服务](https://github.com/tencentyun/wafer-solution/wiki/%E4%BC%9A%E8%AF%9D%E6%9C%8D%E5%8A%A1)让小程序拥有会话管理能力。

### 登录

登录可以在小程序和服务器之间建立会话,服务器由此可以获取到用户的标识和信息。

```js
var qcloud = require('./bower_components/qcloud-weapp-client-sdk/index.js');

// 设置登录地址
qcloud.setLoginUrl('https://199447.qcloud.la/login');
qcloud.login({
    success: function (userInfo) {
        console.log('登录成功', userInfo);
    },
    fail: function (err) {
        console.log('登录失败', err);
    }
});
```
本 SDK 需要配合云端 SDK 才能提供完整会话服务。通过 [setLoginUrl](#setLoginUrl) 设置登录地址,云服务器在该地址上使用云端 SDK 处理登录请求。

> `setLoginUrl` 方法设置登录地址之后会一直有效,因此你可以在微信小程序启动时设置。

登录成功后,可以获取到当前微信用户的基本信息。

### 请求

如果希望小程序的网络请求包含会话,登录之后使用 [request](#request) 方法进行网络请求即可。

```js
qcloud.request({
    url: 'http://199447.qcloud.la/user',
    success: function (response) {
        console.log(response);
    },
    fail: function (err) {
        console.log(err);
    }
});
```

如果调用 `request` 之前还没有登录,则请求不会带有会话。`request` 方法也支持 `login` 参数支持在请求之前自动登录。

```js
// 使用 login 参数之前,需要设置登录地址
qcloud.setLoginUrl('https://199447.qcloud.la/login');
qcloud.request({
    login: true,
    url: 'http://199447.qcloud.la/user',
    success: function (response) {
        console.log(response);
    },
    fail: function (err) {
        console.log(err);
    }
});
```

关于会话服务详细技术说明,请参考 [Wiki](https://github.com/tencentyun/wafer-solution/wiki/%E4%BC%9A%E8%AF%9D%E6%9C%8D%E5%8A%A1)。

## 信道服务

[信道服务](https://github.com/tencentyun/wafer-solution/wiki/%E4%BF%A1%E9%81%93%E6%9C%8D%E5%8A%A1)小程序支持利用腾讯云的信道资源使用 WebSocket 服务。

```js
// 创建信道,需要给定后台服务地址
var tunnel = this.tunnel = new qcloud.Tunnel('https://199447.qcloud.la/tunnel');

// 监听信道内置消息,包括 connect/close/reconnecting/reconnect/error
tunnel.on('connect', () => console.log('WebSocket 信道已连接'));
tunnel.on('close', () => console.log('WebSocket 信道已断开'));
tunnel.on('reconnecting', () => console.log('WebSocket 信道正在重连...'));
tunnel.on('reconnect', () => console.log('WebSocket 信道重连成功'));
tunnel.on('error', error => console.error('信道发生错误:', error));

// 监听自定义消息(服务器进行推送)
tunnel.on('speak', speak => console.log('收到 speak 消息:', speak));

// 打开信道
tunnel.open();
// 发送消息
tunnel.emit('speak', { word: "hello", who: { nickName: "techird" }});
// 关闭信道
tunnel.close();
```

信道服务同样需要业务服务器配合云端 SDK 支持,构造信道实例的时候需要提供业务服务器提供的信道服务地址。通过监听信道消息以及自定义消息来通过信道实现业务。

关于信道使用的更完整实例,建议参考客户端 Demo 中的[三木聊天室应用源码](https://github.com/tencentyun/wafer-client-demo/blob/master/pages/chat/chat.js)。

关于信道服务详细技术说明,请参考 [Wiki](https://github.com/tencentyun/wafer-solution/wiki/%E4%BF%A1%E9%81%93%E6%9C%8D%E5%8A%A1)。

## API


### setLoginUrl
设置会话服务登录地址。

#### 语法
```js
qcloud.setLoginUrl(loginUrl);
```

#### 参数
|参数         |类型           |说明
|-------------|---------------|--------------
|loginUrl     |string         |会话服务登录地址

### login
登录,建立微信小程序会话。

#### 语法
```js
qcloud.login(options);
```

#### 参数
|参数         |类型           |说明
|-------------|---------------|--------------
|options      |PlainObject    |会话服务登录地址
|options.success | () => void | 登录成功的回调
|options.error | (error) => void | 登录失败的回调


### request
进行带会话的请求。

#### 语法
```js
qcloud.request(options);
```

#### 参数
|参数         |类型           |说明
|-------------|---------------|--------------
|options      |PlainObject    | 会话服务登录地址
|options.login | bool         | 是否自动登录以获取会话,默认为 false
|options.url   | string       | 必填,要请求的地址
|options.header | PlainObject | 请求头设置,不允许设置 Referer
|options.method | string      | 请求的方法,默认为 GET
|options.success | (response) => void | 登录成功的回调。<ul><li>`response.statusCode`:请求返回的状态码</li><li>`response.data`:请求返回的数据</li></ul>
|options.error | (error) => void | 登录失败的回调
|options.complete | () => void | 登录完成后回调,无论成功还是失败

### Tunnel

表示一个信道。由于小程序的限制,同一时间只能有一个打开的信道。

#### constructor

##### 语法
```js
var tunnel = new Tunnel(tunnelUrl);
```

#### 参数
|参数         |类型           |说明
|-------------|---------------|--------------
|tunnelUrl    |String         | 会话服务登录地址


#### on
监听信道上的事件。信道上事件包括系统事件和服务器推送消息。

##### 语法
```js
tunnel.on(type, listener);
```

##### 参数
|参数         |类型           |说明
|-------------|---------------|--------------
|type         |string         | 监听的事件类型
|listener     |(message?: any) => void | 监听器,具体类型的事件发生时调用监听器。如果是消息,则会有消息内容。

##### 事件
|事件         |说明
|-------------|-------------------------------
|connect      |信道连接成功后回调
|close        |信道关闭后回调
|reconnecting |信道发生重连时回调
|reconnected  |信道重连成功后回调
|error        |信道发生错误后回调
|[message]    |信道服务器推送过来的消息类型,如果消息类型和上面内置的时间类型冲突,需要在监听的时候在消息类型前加 `@`
|\*           |监听所有事件和消息,监听器第一个参数接收到时间或消息类型 

#### open
打开信道,建立连接。由于小程序的限制,同一时间只能有一个打开的信道。

##### 语法
```js
tunnel.open();
```

#### emit
向信道推送消息。

##### 语法
```js
tunnel.emit(type, content);
```

##### 参数
|参数         |类型           |说明
|-------------|---------------|--------------
|type         |string         | 要推送的消息的类型
|content      |any            | 要推送的消息的内容

#### close
关闭信道

##### 语法
```js
tunnel.close();
```

## LICENSE

[MIT](LICENSE)
1.5、bower.json
{
  "name": "qcloud-weapp-client-sdk",
  "description": "QCloud 微信小程序客户端 SDK",
  "main": "index.js",
  "authors": [
    "Tencent Cloud"
  ],
  "license": "MIT",
  "keywords": [
    "qcloud",
    "weapp",
    "wechat",
    "sdk",
    "client",
    "auth",
    "websocket"
  ],
  "homepage": "",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests",
    "typings.json",
    "jsconfig.json",
    "package.json",
    ".npmignore",
    ".travis.yml",
    ".gitignore"
  ]
}
1.6、index.js
var constants = require('./lib/constants');
var login = require('./lib/login');
var Session = require('./lib/session');
var request = require('./lib/request');
var Tunnel = require('./lib/tunnel');

var exports = module.exports = {
    login: login.login,
    setLoginUrl: login.setLoginUrl,
    LoginError: login.LoginError,

    clearSession: Session.clear,

    request: request.request,
    RequestError: request.RequestError,

    Tunnel: Tunnel,
};

// 导出错误类型码
Object.keys(constants).forEach(function (key) {
    if (key.indexOf('ERR_') === 0) {
        exports[key] = constants[key];
    }
});
2、
3. page返回顶部
 
4.返回顶部
 
5.返回顶部
1、
2、
 
6.返回顶部
 
warn 作者:ylbtech
出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!