一.微信小程序一些接口的使用

1. app.js的onLaunch方法執行,在執行第一個頁面的onLoad方法
2.頁面onLoad方法,頁面只加載一次。
3.onShow方法每次頁面顯示都會執行。
4.獲取權限的方法寫在 app.js 中進行獲取。用戶信息一般在app.js中進行獲取。如果用戶拒絕獲取用戶頭像信息,則可以在第一個界面的onShow()方法中(或在需要使用用戶信息的頁面中),進行重新引導用戶獲取權限,進而獲取用戶信息並將用戶信息進行存取.  獲取用戶信息代碼如下:
getUserInfo: function(cb){
    var that = this
    if (that.globalData.userInfo){
      typeof cb == "function" && cb(that.globalData.userInfo)
    }else{
      wx.getUserInfo({
        success: function (res) {
          that.globalData.userInfo = res.userInfo
          console.log(that.globalData.userInfo)
        },
        error: function (res) {
          console.log("error");
        },
        fail: function (res) {
          wx.showModal({
            title: '警告通知',
            content: '您拒絕授權,將無法正常顯示個人信息,點擊確定重新獲取授權。',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    if (res.authSetting["scope.userInfo"]) {//如果用戶重新同意了授權登錄
                      wx.getUserInfo({
                        success: function (res) {
                          that.globalData.userInfo = res.userInfo
                          console.log(that.globalData.userInfo)
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })
    }
  }
5.小程序獲取地理位置信息,使用騰訊地圖獲取具體的地址信息。
    (1)在騰訊地圖開放平臺,註冊程序使用的開發祕鑰。
    (2)下載所需要的js:qqmap-wx-jssdk.min.js
    (3) 使用wx.getLocation獲取經緯度。
    具體代碼使用如下:

//引入需要的js    
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
// 實例化騰訊地圖API核心類
qqmapsdk = new QQMapWX({
    key: 'EBNBZ-R4GKU-TDSVF-B2ISR-LF4WS-NWBL5' // 必填開發密鑰(key)
})

//獲取用戶地理位置信息
  getUserLocation: function(){
    var that = this
    //1、獲取當前位置座標
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        //2、根據座標獲取當前位置名稱,顯示在頂部:騰訊地圖逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            that.setData({
              location: addressRes.result.address_component.city
            })
          }
        })
      },
      fail: function (res) {
        wx.showModal({
          title: '警告通知',
          content: '您拒絕地理位置授權,將無法正常獲取地理位置信息,點擊確定重新獲取授權。',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting["scope.userLocation"]) {//如果用戶重新同意了授權登錄
                    wx.getLocation({
                      type: 'wgs84',
                      success: function (res) {
                        qqmapsdk.reverseGeocoder({
                          location: {
                            latitude: res.latitude,
                            longitude: res.longitude
                          },
                          success: function (addressRes) {
                            that.setData({
                              location: addressRes.result.address_component.city
                            })
                          }
                        })
                      }
                    })
                  }
                }
              })
            }
          }
        })
      }
    })
  },
6.在小程序的第一個界面進行權限的判斷或在需要使用的權限信息的地方進行判斷。
(1)獲取APP對象
var app = getApp()
(2)在onShow方法中進行權限的重新獲取。可以通過app.xxx方法獲取在app.js中進行授權的方法。

7.下拉刷新
(1)在所需要進行下拉刷新的頁面,用一下代碼進行包裹。
<scroll-view scroll-y="true" height="100%">
</scroll-view>
(2)在js中添加方法:
onPullDownRefresh: function () {
    console.log("下拉刷新")
    wx.showNavigationBarLoading() //在標題欄中顯示加載
    //進行數據請求
    //TODO    

    wx.hideNavigationBarLoading() //完成停止加載
    wx.stopPullDownRefresh() //停止下拉刷新
},

8.輪播圖片展示
( 1)在所需要的進行輪播展示圖片的頁面,增加代碼:
<swiper indicator-dots="{{indicatorDots}}" catchtap="onItemClick" class="swiper"
    autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" circular="{{circular}}">
    <block wx:for="{{imgUrls}}" wx:key="id">
        <swiper-item>
            <image src="{{item.img}}" class="slide-image" data-postId="{{item.id}}" />
        </swiper-item>
    </block>
</swiper>
(2)在js中進行數據的的設置,並設置輪播圖片的點擊事件。
Page({
    data: {
        imgUrls: [
        ],
        indicatorDots: true, //是否顯示畫板指示點
        autoplay: true, //是否自動切換
        circular: false, //是否採用銜接滑動
        interval: 5000,
        duration: 1000
    },   
        onItemClick: function (event) {
                console.log("點擊了")
                //您所需要進行的邏輯處理
                wx.showToast({
                        title: event.target.dataset.postid + "",
                })
        },

})

9.微信小程序獲取openID
(1)使用wx.login方法獲取code
wx.login({
    success: function (res) {
        if (res.code) {
            // console.log(res)
            // console.log(res.code)
            code = res.code
            //發起網絡請求獲取session_key和openid(請求後臺服務)
            // wx.request({
                // url: '',
                // data:{},
                // success: function (data){

                // }
            // })
        } else {
            console.log('獲取用戶登錄態失敗!' + res.errMsg)
        }
    }
})
(2)通過code在我們後臺程序進行獲取session_key和openid等信息
/**
      * 通過微信小程序登錄code獲取用戶的openId和session_key信息
      * @param code
      * @return
      */
     public static String getWxProgramSessionKey(String  code){
          logger.info("######getWxProgramSessionKey  start######");
          JSONObject jo = null;
          try {
              PropertiesUtil pu = new PropertiesUtil();
              //請求地址 https://api.weixin.qq.com/sns/jscode2session
              String url =  pu.readValue("wxRootHttpsUrl")+ThirdTemplateConstants.WX_GET_SESSIONKEY_OPENID;
              //請求參數 
              String params =  "appid="+pu.readValue("wxProgram")+"&secret="+pu.readValue("wxProgramSecret")
                        +"&js_code="+code+"&grant_type=authorization_code";
              String result = HttpUtil.sendGet(url,  params);
              jo = JSONObject.parseObject(result);
          } catch (Exception e) {
              logger.info("######getWxProgramSessionKey  error######");
              e.printStackTrace();
          }
          
          logger.info("######getWxProgramSessionKey  end######");
          return jo.toJSONString();
     }
返回結果:{"openid":"oh3gY48jSwO9oyBmU8g7TML4vxuE","session_key":"/oGyuh+h1l2wIi29UxuPEA=="}
(3)session_key可以用來進行前面獲取用戶信息的加密信息校驗,具體請參考官方文檔:https://developers.weixin.qq.com/miniprogram/dev/api/open.html#wxgetuserinfoobject





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章