微信小程序云端增强 SDK接入

移动开发
XpmJS可以链接任何云端资源,为小程序、移动应用提供云资源通道和后端能力。降低开发门槛,提升小程序的开发效率。无需编写后端代码,即可实现用户登录、WebSocket 通信、微信支付、云端数据表格、文件存储等功能。虽然 PHP 是最好的编程语言, 但是使用 XpmJS 后, 无需学习包括 PHP 在内的任何后端语言,用 Javascript 即可搞定一切,NodeJS 也不用!

【引自第九程序的博客】一、XpmJS 是啥

XpmJS可以链接任何云端资源,为小程序、移动应用提供云资源通道和后端能力。降低开发门槛,提升小程序的开发效率。无需编写后端代码,即可实现用户登录、WebSocket 通信、微信支付、云端数据表格、文件存储等功能。虽然 PHP 是最好的编程语言, 但是使用 XpmJS 后, 无需学习包括 PHP 在内的任何后端语言,用 Javascript 即可搞定一切,NodeJS 也不用!

二、为啥 XpmJS

从代码结构上看 XpmJS 更优雅!因为使用了 Promise!

 

XpmJS 封装了常用后端操作,还提供一个管理后台,微信支付只要一行代码就可以实现!

 

后端部署在你的云主机上!你可以完全掌控数据。

方法1: 一键安装

推荐使用腾讯云一键安装链接 ( 访问微信接口快, 可以免费申请 Https 证书 )

方法2: 安装脚本

安装前,先提前申请 Docker Hub 镜像 申请地址 https://www.daocloud.io/mirror

  1. # 请采用 Ubuntu 14.04 64位 LTS 
  2.  
  3. curl -sSL http://tuanduimao.com/xpmjs-server.sh | sh -s yourdomain.com http://<your id>.m.daocloud.io  

方法3: 使用 Docker 安装

  1. # 安装 Docker  
  2. curl -sSL https://get.daocloud.io/docker | sh 
  3.  
  4. # 启动容器 
  5. docker run -d --name=xpmjs-server  \ 
  6.     -e "HOST=yourdomain.com" \ 
  7.     -v /host/data:/data  \ 
  8.     -v /host/apps:/apps  \ 
  9.     -v /host/config:/config  \ 
  10.     -p 80:80 -p 443:443  \ 
  11.     tuanduimao/xpmjs-server:1.0  

XpmJS Server 升级

第一步: 下载代码:

  1. curl http://xpmjs-1252011659.costj.myqcloud.com/xpmjs-server-1.0.tar.gz 

第二步: 解压并更新:

  1. tar xvfz xpmjs-server-1.0.tar.gz 
  2.  
  3. cd 1.0 && docker cp . xpmjs-server:/code  

三、XpmJS 咋用

1. 用户 ( User )

用户登录 login()

  1. var user = app.xpm.require('User'); 
  2.  
  3. user.login().thenfunction( userInfo ) {  
  4.  
  5.     console.log( '用户登录成功', userInfo ); 
  6.     app.session.set('loginUser', userInfo ); 
  7. }) 
  8.  
  9. .catch( function( excp ) {  
  10.     console.log('用户登录失败', excp ); 
  11. }); 

用户退出 logout()

  1. var user = app.xpm.require('User'); 
  2.  
  3. user.logout().thenfunction( userInfo ) {  
  4.     console.log( '用户注销成功', userInfo ); 
  5. }) 
  6.  
  7. .catch( function( excp ) {  
  8.     console.log('用户注销失败', excp ); 
  9. });  

读取资料 get()

来自微信客户端的用户信息 ( 非云端数据 )

  1. var user = app.xpm.require('User'); 
  2.  
  3. user.get().thenfunction( userInfo ) {  
  4.     console.log( '读取成功', userInfo ); 
  5. }) 
  6.  
  7. .catch( function( excp ) {  
  8.     console.log('读取失败', excp ); 
  9. });  

2. 信道( Wss )

使用 Websocket 信道,可以实现双向实时通信。

打开信道 open()

  1. var wss = app.xpm.require('Wss'); 
  2. wss.open('/wxapp').then(function( res ) { 
  3.     console.log( '信道连接成功', res ); 
  4. }) 
  5. .catch( function( excp ) {  
  6.     console.log('信道连接失败', excp ); 
  7. });  

在线用户 liveUsers ()

  1. var wss = app.xpm.require('Wss'); 
  2. wss.liveUsers().then(function( users ) { 
  3.     console.log( '读取在线用户成功', users ); 
  4. }) 
  5. .catch( function( excp ) {  
  6.     console.log('读取在线用户失败', excp ); 
  7. });  

用户信息数据结构

字段 中文 说明
id 客户端ID  
_id 用户ID  
nickName 微信昵称  
gender 性别  
avatarUrl 头像  
language 语言  
group 用户组  
isadmin 是否是管理员 0 非管理员 1 管理员

检查用户是否在线 isOnline ( xpmjs-server 1.0rc4+ )

  1. var user = app.xpm.require('User'); 
  2. var wss = app.xpm.require('Wss'); 
  3.  
  4. user.login().thenfunction( userInfo ) {  
  5.     return wss.isOnline( userInfo['_id'] ) 
  6.  
  7. }).then function( isOnline ) { 
  8.     if ( isOnline ) { 
  9.         console.log( '用户在线'); 
  10.     } else { 
  11.         console.log( '用户离线'); 
  12.     } 
  13. }) 
  14. .catch( function( excp ) {  
  15.     console.log('出错啦', excp ); 
  16. });  

监听指令 listen()

小程序仅提供 WebSocket 客户端 API,所以小程序本身无法实现 WebSocket服务器。 wss.listen() 方法并非启动 WebSocket Server, 而是用来接收云端信道转发的指令。

  1. var wss = app.xpm.require('Wss'); 
  2. wss.listen('payment'function( res, status ){ 
  3.     // 当接收到 payment 指令后运行  
  4.     if ( status != 'success'return ; 
  5.     console.log( res, status ); 
  6. });  

发送指令 send()

  1. var wss = app.xpm.require('Wss'); 
  2. wss.liveUsers().then(function( users ) { 
  3.     console.log( '读取在线用户成功', users ); 
  4.     // 向第一个用户发送 payment 指令 
  5.     if ( users.length > 0 )  { 
  6.         return wss.send('payment', users[0], users[0]['id'] ) 
  7.     } else { 
  8.         return {code:404, message:'no live user'}; 
  9.     } 
  10.  
  11. }).thenfunction( res ){ 
  12.     console.log('发送完毕', res); 
  13. }); 
  14. .catch( function( excp ) {  
  15.     console.log('出错了', excp ); 
  16. });  

绑定事件 bind()

接收并处理 websocket 服务器事件,有效值 ( open/close/message/error )

  1. var wss = app.xpm.require('Wss'); 
  2. wss.bind('open'function(event) { 
  3.     console.log('信道服务器开启', event ); 
  4. }); 
  5.  
  6. wss.bind('close'function(event) { 
  7.     console.log('信道服务器关闭', event ); 
  8. });  

3. 会话 ( Session )

Session 会话分为客户端和服务端两部分,客户端与服务端会话ID相同,客户端保存用户信息资料,服务端保存用户 openid 等敏感信息。与服务端通信,使用Sesssion ID 鉴权,通过服务器端验证后,请勿将 Session ID 发送给第三方。

启用会话 start()

启用会话后,会自动创建一个会话ID

  1. var session = app.xpm.require('session'); 
  2.     session.start();  

会话 ID id()

  1. var session = app.xpm.require('session'); 
  2. var sid = app.id(); 
  3. console.log( sid );  

客户端会话数据管理 set() & get()

  1. var session = app.xpm.require('session'); 
  2.  
  3. session.set('hello''world'); 
  4.  
  5. console.log( session.get('hello') );  

4. 云端表格 ( Table )

可以使用云端表格接口,将数据保存在 MySQL 中,可以通过 SQL 查询数据。

创建数据表 _schema()

仅管理员帐号拥有创建数据表权限 ( 登录管理后台,打开用户表,将开发者对应帐号记录的 isadmin 字段数值设置为 1 )

 

  1. var table = app.xpm.require('Table''hello'); 
  2. table._schema( 
  3.     [   
  4.       {name:"name", type:'string'option:{length:80, require:true }, acl:"rwd:r:-" }, 
  5.       {name:"company", type:'string'option:{length:100}, acl:"w:-:-" } 
  6.     ],  
  7.     { record:"rwd:rw:-"table:"rwd:-:-", field:'rwd:r:-',  user:'admin'group:'member' } 
  8. true ).thenfunction( data ) { 
  9.     console.log('数据表创建成功', data ); 
  10. }) 
  11. .catch( function( excp ) {  
  12.     console.log('数据表创建失败', excp ); 
  13. });  

字段配置参数

参数 中文 说明
name 字段名称  
type 字段类型 string/integer/text/boolean 等
option 字段参数 index:true 索引 unique:true 唯一索引 length:80 字段长度
acl 字段鉴权 rw:rw:rw r: 读取 w: 写入 -:无 user:group:other

数据增删改查 get() create() update() remove()

  1. var table = app.xpm.require('Table''hello'); 
  2.  
  3. // 创建 
  4. table.create(  
  5.     {name:'张艺谋', company:'中国电影制片厂'
  6. ).then(function(data) { // 更新 
  7.     return table.update(data['_id'], {name:'冯小刚'}); 
  8.  
  9. }).then(function(data) { // 读取 
  10.     return table.get(data['_id']); 
  11.  
  12. }).then(function(data) { // 删除 
  13.     return table.remove(data['name'], 'name' ); 
  14.  
  15. }).then(function(resp) { 
  16.     console.log( 'remove success', resp ); 
  17.  
  18. }).catch( function( excp ) {  
  19.     console.log('出错了', excp ); 
  20. });  

数据查询 query()

  1. var table = app.xpm.require('Table''hello'); 
  2. table.query() 
  3.     .where('name''=''冯小刚'
  4.     .orderby('name''asc'
  5.     .limit(2)  // 仅查询 2条  
  6.  
  7. .fetch('name','company').then(function(data) {   
  8.     console.log( '查询结果', data );  
  9. }) 
  10.  
  11.  
  12. table.query() 
  13.     .where('name''=''冯小刚'
  14.     .orderby('name''asc'
  15.     .paginate(3, 2)  // 分3页,当前显示第 2页  
  16.  
  17. .fetch('name','company').then(function(data) {   
  18.     console.log( '查询结果', data );  
  19. });  

联合查询 join(), leftjoin(), rightjoin() (xpmjs-server 1.0rc4+)

Table 1: User

id name title
1 张三 产品经理
2 李四 工程师
3 王五 运维工程师

Table 2: Project

id name uid
1 小程序开发组 1
2 网页开发组 3

   

  1. var table = app.xpm.require('Table''Project'); 
  2. table.query() 
  3.     .join('User''User.id''=''Project.uid' )  // leftjoin / rightjoin 
  4.     .limit(1)   
  5. .fetch('User.id as userid''User.name as username''Project.*').then(function(data) {   
  6.     console.log( '查询结果', data );  
  7. })  

返回值

  1.     { 
  2.         "id":1, 
  3.         "name":"小程序开发组" 
  4.         "userid":1, 
  5.         "username":"产品经理" 
  6.  
  7.     } 
  8.  

inWhere 查询 inWhere()

Table 1: User

id name title
1 张三 产品经理
2 李四 工程师
3 王五 运维工程师

Table 2: Project

id name users
1 小程序开发组 ["1","2","3"]
2 网页开发组 ["1", "3"]

   

  1. var table = app.xpm.require('Table''Project'); 
  2. table.query() 
  3.     .inWhere('users''User''id''*' ) 
  4.     .limit(1)   
  5. .fetch('User.id as userid''User.name as username''Project.*').then(function(data) {   
  6.     console.log( '查询结果', data );  
  7. })  

返回值

  1.     { 
  2.         "id":1, 
  3.         "name":"小程序开发组" 
  4.         "users":[ 
  5.             { 
  6.                 "id":1, 
  7.                 "name":"张三"
  8.                 "title":"产品经理" 
  9.             } 
  10.             ... 
  11.         ] 
  12.  
  13.     } 
  14.  

5. 微信支付 ( Pay )

发起支付 request();

  1. var pay = app.xpm.require('Pay'); 
  2. pay.request({ 
  3.     total_fee:500,  // 单位分 
  4.     body:'算命、服务器开光'
  5.     attach:'HELLO XpmJS.com',  
  6.     detail:'{id:888,desp:"算命,抽SSR,赠送服务器开光"}' 
  7. }).then(function( data ){ 
  8.     console.log('Request Pay Success', data ); 
  9. }).catch( function( excp){ 
  10.     console.log('Request Pay Failure', excp ); 
  11. });  

云端事件 before(), success(), fail(), complete() (xpmjs-server 1.0rc4+)

  1. pay.before('create', {  // 创建充值记录 (统一下单成功后, 发起支付前, 在云端运行 ) 
  2.     'table':'income'
  3.     'data': { 
  4.         sn:'{{sn}}'
  5.         order_sn: data.order.sn, 
  6.         uid:data.order.uid, 
  7.         amount:data.order.sale_price, 
  8.         amount_free:0, 
  9.         status:'PENDING'
  10.         status_tips:"F请求付款" 
  11.     } 
  12. }) 
  13.  
  14. .order({   // 生成订单  ( 统一下单接口, 仅设定并不发送请求 ) 
  15.     total_fee:data.order.sale_price,  // 单位分 
  16.     body:data.order.show_name, 
  17.     attach:'attach user is ' + mid,  // 应该是当前登录用户的 ID  
  18.     detail:data 
  19. }) 
  20.  
  21. .success('update', { // 更新充值记录 ( 支付成功后回调,在云端运行 ) 
  22.     'table':'income'
  23.     'data': { 
  24.         sn:'{{sn}}'
  25.         status:'DONE'
  26.         status_tips:"income status_tips field" 
  27.     }, 
  28.     'unique':'sn' 
  29. }) 
  30.  
  31. .success('app', {   // 调用APP 示例 ( 支付成功后回调,在云端运行 ) 
  32.     'name':'xapp'
  33.     'api':['ticket','index',{sn:'{{sn}}','status_tips':"{{0.status_tips}}"}], 
  34.     'data': { 
  35.         sn:'{{sn}}'
  36.         status:'DONE' 
  37.     } 
  38. }) 
  39.  
  40. .success('update', {  // 更新订单状态 ( 支付成功后回调,在云端运行 ) 
  41.     'table':'order'
  42.     'data': { 
  43.         _id:oid, 
  44.         status:'PENDING' 
  45.     } 
  46. }) 
  47.  
  48. .success('create', {   // 创建消费记录 ( 支付成功后回调,在云端运行 ) 
  49.     'table':'payout'
  50.     'data': { 
  51.         sn:'{{sn}}'
  52.         order_sn: data.order.sn, 
  53.         uid:data.order.uid, 
  54.         amount:data.order.sale_price, 
  55.         amount_free:0, 
  56.         status:'DONE'
  57.         status_tips:"F请求付款" 
  58.     } 
  59. }) 
  60.  
  61. .request().then(function( payResp  ) {  // 发起请求 
  62.     console.log( payResp ); 
  63. })  

6. 本地存储 ( Stor )

  1. var stor = app.xpm.require('Stor'); 
  2.  
  3. stor.setSync('key','value'); 
  4.  
  5. console.log(stor.getSync('key')); 
  6.  
  7. stor.setMapSync('map_name''key''value'); 
  8.  
  9. console.log(stor.getMapSync('map_name','key'));  

7. 云端应用 ( App ) (xpmjs-server 1.0rc3+)

调用示例

  1. var xapp = app.xpm.require('App''xapp' );  // xapp 应用名称 
  2.  
  3. xapp.api( 'ticket''available' )  // ticket 控制器  available 方法名 
  4.  
  5. .post({ 
  6.     'train_date':'2017-01-26'
  7.     'from_station':'BJP'
  8.     'to_station':'SHH' 
  9. }) 
  10.  
  11. .thenfunction( resp ) { 
  12.   console.log('POST RESP:', resp ); 
  13. }) 
  14.  
  15. .catch( function( excp ) { 
  16.   console.log('POST EXCP:', excp ); 
  17. });  

XpmJS 云端应用开发

参考云端应用 Demo <火车票余票查询接口实现>

https://git.oschina.net/xpmjs/xapp

 

8. 云端队列 ( Que.js ) (xpmjs-server 1.0rc4+)

  1. var que = app.xpm.require('Que''hello'); 
  2. que.select('world').push('create', {  // 增加数据 
  3.     table:'payout'
  4.     data: { 
  5.         sn:'200193'
  6.         order_sn:'test29993'
  7.         amount:100, 
  8.         status:'DONE' 
  9.     } 
  10. }).push('update', { // 更新数据 
  11.     table:'order'
  12.     data: { 
  13.         sn:'148457330261256'
  14.         status_tips:'{{0.sn}} {{0.status}}' 
  15.     }, 
  16.     unique:'sn' 
  17. }).push('app', {   // 调用APP 示例 
  18.     'name':'xapp'
  19.     'api':['ticket','index',{sn:'{{0.sn}}'}], 
  20.     'data': { 
  21.         sn:'{{0.sn}} {{1.sn}}'
  22.         status:'DONE' 
  23.     } 
  24. }).run().then(function(resp){ 
  25.     console.log( 'Response', resp ); 
  26. }) 
  27. .catch(function(excp){ 
  28.     console.log( 'Error', excp ); 
  29. })  

9. 文件上传 Utils.upload & App.upload (xpmjs-server 1.0+)

上传文件到腾讯云对象存储

  1. var qcloud = app.xpm.require('app''xqcloud'); 
  2. qcloud.api("cos",'upload'
  3.  
  4. .upload( tempFilePaths[0] ) 
  5. .then(function(data){ 
  6.     that.setData({ 
  7.         'rs.corver':data.access_url, 
  8.         'rs.images':[data.access_url] 
  9.     }); 
  10. }) 
  11. .catch( function(excp){ 
  12.     console.log('Upload Fail', excp ); 
  13. });  

10. 常用方法 ( Utils )

请求网址 ( Utils.fetch ) (xpmjs-server 1.0rc3+)

  1. var utils = app.xpm.require('Utils' );   
  2.  
  3. utils.fetch'http://qcloud.com' ).thenfunction( resp ) {     
  4.     console.log('FETCH RESP:', resp ); 
  5. }) 
  6.  
  7. .catch( function( excp ) { 
  8.   console.log('FETCH EXCP:', excp ); 
  9. });  

生成二维码图片 ( Utils.qrImageUrl ) (xpmjs-server 1.0+)

返回二维码图片地址

  1. var utils = app.xpm.require('Utils' );  
  2. var url = utils.qrImageUrl('hello world', {size:200}); 
  3. console.log( url );  

生成小程序页面二维码 ( Utils.qrcode ) ( xpmjs-server 1.0 )

  1. var utils = app.xpm.require('Utils' ); 
  2.  
  3. var url = utils.qrcode('/page/detail?id=1'); 
  4.  
  5. console.log( url );  

三、微信小程序 Demo 

 

小程序 Demo 源码

四、安装配置

1. 云端配置

【安装后端程序】

推荐使用腾讯云( 访问微信接口快, 可以免费申请 Https 证书 )

方法1: 使用脚本安装 ( 目前仅支持 Ubuntu 14.04 64 LTS 操作系统 )

创建一台云服务器,选择 Ubuntu 14.04 64 LTS 操作系统。 登录服务器运行以下脚本。

安装前,先提前申请 Docker Hub 镜像 申请地址 https://www.daocloud.io/mirror

  1. curl -sSL http://tuanduimao.com/xpmjs-server.sh | sh -s yourdomain.com http://<your id>.m.daocloud.io 

方法2: 使用 Docker 安装

  1. docker run -d --name=xpmjs-server  \ 
  2.     -e "HOST=yourdomain.com" \ 
  3.     -v /host/data:/data  \ 
  4.     -v /host/apps:/apps  \ 
  5.     -v /host/config:/config  \ 
  6.     -p 80:80 -p 443:443  \ 
  7.     tuanduimao/xpmjs-server:1.0  

【设置管理员名称和密码】

访问: http://yourdomian.com/setup.php

1、填写后台信息

 

2、填写管理员信息

 

【上传 HTTPS 证书 & 微信支付证书】

访问:http://yourdomian.com/baas-admin/cert/index 上传 HTTPS 证书和证书密钥; 如已申请微信支付,建议尽量上传支付证书,用于双向验证证书和密钥,确保支付安全。

 

上传好证书后,登录服务器,重启容器。

  1. docker restart xpmjs-server 

访问: https://yourdomian.com ( 有 "S", 检查证书是否生效 )

【设置小程序配置信息】

访问: https://yourdomian.com/baas-admin/conf/index ( 有 "S", 填写小程序和微信支付的信息 )

 

2. 使用 XpmJS

【下载代码】

使用 Git Bash , 进入小程序项目目录, 运行 git clone 拉去代码。(也可以 使用 Git 等客户端 Clone 代码 )

  1. git clone https://git.oschina.net/xpmjs/xpmjs.git xpmjs 

克隆成功后的目录结构为:

 

 

【编写配置信息】

编辑 app.js 将域名更换为你的域名。( 必须配置好 Https 证书 )

  1. App({ 
  2.  
  3.   onLaunch: function () { 
  4.  
  5.     var that = this; 
  6.  
  7.     // 创建 xpm 对象 
  8.     this.xpm = require('xpmjs/xpm.js').option({ 
  9.         'app':1,  // 对应后台 APP 配置,支持5个 
  10.         'host':'yourdomian.com'
  11.         'https':'yourdomian.com'
  12.         'wss''yourdomian.com/ws-server'
  13.         'table.prefix''demo'
  14.         'user.table':'user' 
  15.     }); 
  16.  
  17.     // 创建全局对象 
  18.     this.wss = this.xpm.require('wss');  // 信道 
  19.     this.session = this.xpm.require('session');  // 会话 
  20.     this.stor = this.xpm.require('stor'); // 存储 
  21.  
  22.   }, 
  23.  
  24.   xpm:null
  25.   session:null
  26.   stor:null
  27.   wss:null 
  28. })  

建议将 xpm、wss、session、stor 设定为全局变量。 

责任编辑:庞桂玉 来源: 第九程序的博客
相关推荐

2016-11-04 10:31:49

微信程序指南

2017-05-08 15:03:07

微信小程序开发实战

2016-11-22 11:23:52

微信小程序腾讯微信

2016-09-27 15:40:58

微信程序前端

2016-09-27 16:38:24

JavaScript微信Web

2016-11-04 10:49:48

微信小程序

2021-06-10 10:51:27

程序基础架构

2017-06-09 10:06:54

微信小程序架构分析

2017-06-09 10:40:00

微信小程序架构分析

2017-01-09 10:01:49

微信小程序

2017-06-09 12:58:20

微信小程序架构分析

2016-10-20 21:02:12

微信小程序javascript

2016-09-28 18:10:59

微信程序MINA

2016-11-19 18:06:44

微信小程序张小龙

2015-02-11 14:45:16

微信SDK

2017-02-06 13:32:12

微信小程序思想

2018-07-26 15:16:50

小程序iPhone X甜酸

2016-09-27 20:36:23

微信HttpWeb

2020-04-13 15:45:11

小程序微信互联网法院

2018-03-30 15:46:17

直播微信小程序
点赞
收藏

51CTO技术栈公众号