微信小程序开发总结

2,689 阅读4分钟
原文链接: zhuanlan.zhihu.com

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

原文链接

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="{% raw %}{{titles}}{% endraw %}" 
  wx:key="{% raw %}{{item}}{% endraw %}" 
  class="home-title {% raw %}{{index == activeIndex ? 'active' : ''}}{% endraw %}" 
  bindtap='changeClassify'>
  {% raw %}{{item.name}}{% endraw %}
</text>

// index == activeIndex classw为 "home-title active" 否则为 "home-title "

4.循环嵌套

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

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

  <view class="classify-items">
    <view class="classify-item" wx:for=">{% raw %}{{item.data}}{% endraw %}"  wx:for-item="cell" wx:key="index">
      <view>
        <text class="classify-item_name">{% raw %}{{cell.name}}{% endraw %}</text>
      </view>
    </view>
  </view>
</view>

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

//wxml
<text wx:for="{% raw %}{{titles}}{% endraw %}" wx:key="{% raw %}{{index}}{% endraw %}" bindtap='changeClassify' data-id="{% raw %}{{index}}{% endraw %}">{% raw %}{{item.name}}{% endraw %}</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)
}
// index == activeIndex classw为 "home-title active" 否则为 "home-title "

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

  • 直接使用小城程序自带方法 onReachBottom 、 onPullDownRefresh
  • 如果使用 scroll-view 组件还可以监听 bindscrolltoupper 、 bindscrolltolower
// 上拉加载更多
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="{% raw %}{{!isloading}}{% endraw %}">
    <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="{% raw %}{{isloading}}{% endraw %}"></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 版本要求比较简单。 从开发到上线一共用了两天时间,小程序的审核也是出奇的快。下午提交不到两小时就审核通过了。严重怀疑他们没测:joy:。

原作者: Hiz Blog 来自: Hiz Blog

原文链接:微信小程序开发总结