161

微信小程序开发总结

 6 years ago
source link: https://juejin.im/post/59c20199f265da0658151cfe
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2017年09月20日 阅读 6544

微信小程序开发总结

记录下小程序开发过程中遇到的一些问题以及解决方案

原文链接

1. 微信开发者 1.0.0 版本

GET 1351598279.appservice.open.weixin.qq.com/appservice net::ERR_NAME_NOT_RESOLVED

公司的网络是翻墙网络,微信应该是给禁掉了

设置-----> 代理设置 -----> 不适用任何代理,勾选直联网络

2. 对应的服务器证书无效。控制台输入 showRequestInfo() 可以获取更详细信息

小程序数据请求必须是https, 没配证书用于调试可以先在项目设置中选择不校验安全域名、TLS 版本以及 HTTPS 证书

3. 按条件设置class

<text wx:for="{{titles}}" 
  wx:key="{{item}}" 
  class="home-title {{index == activeIndex ? 'active' : ''}}" 
  bindtap='changeClassify'>
  {{item.name}}
</text>

// index == activeIndex classw为 "home-title active" 否则为 "home-title "复制代码

4.循环嵌套

// 普通的单次循环
<text wx:for="{{titles}}" wx:key="{{index}}">{{item.name}}</text>

//循环嵌套时使用 wx:for-item="XXX" 
<view wx:for="{{hotArr}}">
  <view class="classify-title" bindtap="goClassifyPage">
    <text>{{item.name}}</text>
  </view>

  <view class="classify-items">
    <view class="classify-item" wx:for="{{item.data}}"  wx:for-item="cell" wx:key="index">
      <view>
        <text class="classify-item_name">{{cell.name}}</text>
      </view>
    </view>
  </view>
</view>复制代码

5. router 跳转传参及参数获取

//wxml
<text wx:for="{{titles}}" wx:key="{{index}}" bindtap='changeClassify' data-id="{{index}}">{{item.name}}</text>

//js
function changeClassify(e) {
  //
  let id = e.currentTarget.dataset.id;

  //跳转到classify 页面
  wx.navigateTo({
    url: '../classify/classify?id=' + id
  })
}

//classify 页面 获取参数
onLoad: function (opts) {
  console.log(opts.id)
  console.log(this.options.id)
}复制代码

6. 上拉加载更多, 下拉刷新

  • 直接使用小城程序自带方法onReachBottomonPullDownRefresh
  • 如果使用scroll-view组件还可以监听 bindscrolltoupperbindscrolltolower

// 上拉加载更多
onReachBottom: function() {
  if (this.data.next != null) {
    this.setData({ isHideLoadMore: false })
    this.getNextPage()
  }
}

// 下拉刷新
onPullDownRefresh: function() {
  this.refreshData()
}复制代码

7. 组件化 template的使用

对于通用的组件可以抽出一个template

/**
* 1. 给template 设置name
* 2. 组件传过来的值可以直接使用  hidden="{{!isloading}}"
*/
<template name="loading">
  <view class="weui-loadmore" hidden="{{!isloading}}">
    <view class="weui-loading"></view>
    <view class="weui-loadmore__tips">正在加载</view>
  </view> 
</template>

// 
/** 
* 使用通用的template 
* 1. 按路径引入
* 2. 设置 is 等于 template的name data="{{isloading}}" 给template的数据
*/
<import src="../template/loading.wxml"/>

<template is="loading" data="{{isloading}}"></template>复制代码

8. 获取用户的UniqueID 以及 openid

UniqueID 以及 openid的获取涉及到用户的敏感信息,返回的数据encryptedData是加密后的数据要提取信息需要对数据进行解密

官网提供了解密的算法,将nodejs的版本拿过来稍作修改即可

  • 下载 cryptojs 放到项目的utils目录下
  • 在utils 目录下新建decode.js 写入以下内容
//utils/decode.js
var Crypto = require('./cryptojs/cryptojs.js').Crypto;

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode :使用 CryptoJS 中 Crypto.util.base64ToBytes()进行 base64解码
  var encryptedData = Crypto.util.base64ToBytes(encryptedData)
  var key = Crypto.util.base64ToBytes(this.sessionKey);
  var iv = Crypto.util.base64ToBytes(iv);

  // 对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充
  var mode = new Crypto.mode.CBC(Crypto.pad.pkcs7);

  try {
    // 解密
    var bytes = Crypto.AES.decrypt(encryptedData, key, {
      asBpytes: true,
      iv: iv,
      mode: mode
    });

    var decryptResult = JSON.parse(bytes);

  } catch (err) {
    console.log(err)
  }

  if (decryptResult.watermark.appid !== this.appId) {
    console.log(err)
  }

  return decryptResult
}

module.exports = WXBizDataCrypt复制代码
  • 在app.js 引入decode.js 对数据进行解密

var WXBizDataCrypt = require('utils/decode.js');

var AppId = 'XXXXXX'  
var AppSecret = 'XXXXXXXXX'

//app.js
App({
  onLaunch: function () {
    //调用登录接口
      wx.login({
        success: function (res) {
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session',
            data: {
              appid: AppId,
              secret: AppSecret,
              js_code: res.code,
              grant_type: 'authorization_code'
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'GET',
            success: function(res) {
              var pc = new WXBizDataCrypt(AppId, res.data.session_key)
              wx.getUserInfo({
                success: function (res) {
                  var data = pc.decryptData(res.encryptedData, res.iv)
                  console.log('解密后 data: ', data)
                }
              })
            },
            fail: function(res) {
            }
          })
        }
      })
  }
})复制代码

注意:UniqueID 的获取微信开放平台帐号必须已完成开发者资质认证,否则解密后的数据没有UniqueID字段

解密后数据

解密后数据解密后数据

由于公司1.0 版本要求比较简单。 从开发到上线一共用了两天时间,小程序的审核也是出奇的快。下午提交不到两小时就审核通过了。严重怀疑他们没测😂。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK