微信小程式開發總結

qq_42574821發表於2020-12-10

記錄下小程式開發過程中遇到的一些問題以及解決方案

原文連結

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 版本要求比較簡單。 從開發到上線一共用了兩天時間,小程式的稽核也是出奇的快。下午提交不到兩小時就稽核通過了。嚴重懷疑他們沒測?。

相關文章