1. Wechat authorized avatar nickname, etc

The new version getUserProfile:

<button wx:if="{{canIUseGetUserProfile}}" class="authBtn" bindTap ="getUserProfile"> {userInfo: {}, hasUserInfo: false, canIUseGetUserProfile: false,}, onLoad() {// To determine whether the old and new versions are compatible let that = this; if (app.globalData.userInfo) { this.setData({ userInfo: app.globalData.userInfo, hasUserInfo: true }) }else if (wx.getUserProfile) { this.setData({ canIUseGetUserProfile: } else {// in no open-type=getUserInfo version compatible processing wx.getUserInfo({success: res => { app.globalData.userInfo = res.userInfo; this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } }) } }, getUserProfile(e) { let code = ""; let that = this; SetTimeout wx.login({success(res) {code = res.code; }}); SetTimeout (() => {wx.getUserProfile({desc: 'to improve member profile ', // declare the purpose of obtaining user's personal information, please fill in success carefully: SetData ({userInfo: res1.userinfo, hasUserInfo: res1.userInfo, hasUserInfo: True,}) / / callback interface to the database, and the pop-up for mobile number bounced wx. Request ({url: 'https:njlingshi.com/api/weChatAuth?code=' + code, method: "POST", success(res2) {that.setdata ({showPhoneModal: true,// show the popup codeKey to get the phone number: Res2. Data. The data codeKey, / / store the encryption key and user information behind use userInfoEncrypt: {" encryptedData ": res1 encryptedData," iv ": res1.iv } }) } }) } }) }) },Copy the code

The old version getUserInfo:

<button wx:else class="authBtn" opentype ="getUserInfo" bindGetUserInfo ="getUserInfo"> </button> js: // getUserInfo(e) {// getUserInfo(e) {// getUserInfo(e) {// getUserInfo(e) {// getUserInfo(e) {// getUserInfo(e) { This.setdata ({userInfo: e.dietail.userinfo, hasUserInfo: true }) wx.login({ success(res) { if (res.code) { wx.request({ url: 'https:njlingshi.com/api/weChatAuth?code='+code, method: "POST", success(res) { that.setData({ showPhoneModal: CodeKey: res.data.data.codeKey, "userInfoEncrypt": {// Use "encryptedData" after storing the key and user encryption information: e.detail.encryptedData, "iv": e.detail.iv } }) } }) } } }); },Copy the code

The difference between:

1, getUserProfile page can be invoked after the click event, each request will pop up the authorization window, need to get user information after wx.getUserProfile({}) method execution

GetUserInfo allows you to get the information when the button is clicked and is not recommended at this time.

2, remember this time if the interface prompt decryption failure, wechat decryption check failure is the back end of the pot do not back, hard point!

3, Tips: small program in the final audit online when the card login, if you enter the page must be authorized to log in to the line may not pass, this must be communicated well, the home page and other interfaces do not need token can also access.

2. Authorize the mobile phone number

wxml: <button class="authBtn" open-type="getPhoneNumber" bindgetPhonenumber ="getPhoneNumber"> </button> js:getPhoneNumber(e) { let that = this; if (! E.dyail.iv) {this.setdata ({showPhoneModal: false}) return; } wx. Request ({url: 'https:njlingshi.com/api/miniProgramLogin, method: "POST", data: {/ / need to use the various parameters of the incoming interface "codeKey" : that.data.codeKey, "userInfoEncrypt": that.data.userInfoEncrypt, "userPhoneEncrypt": { encryptedData: e.detail.encryptedData, iv: e.detail.iv } }, success(res) { if(res.statusCode == 200) { app.globalData.token = res.data.data.token; // Store token and user information in global variable app.globalData.userInfo = res.data.data; // Store token and user information in global variable app.globalData.userInfo = res.data.data; that.setData({showPhoneModal: false}) wx.setStorage({ key: "token", data: res.data.data.token }) wx.setStorage({ key: "Userinfo ", data: res.data.data}) wx.showloading ({title: 'loading '}); setTimeout(()=>{wx.hideLoading(); Else {wx.showToast({icon:'error', title: res.data.message,})}})},Copy the code

3. Authorize the location of the address

"Permission ": {"scope. UserLocation ": {"desc": }}, app.js onShow() {// get the user's current location wx.getLocation({type: 'gcj02', success (res) {that. Globaldata.userlat = res.latitude; that.globalData.userLong = res.longitude; }})}, globalData: {userLat: ' ', / / users are longitude and latitude userLong: "',}Copy the code

Calculates the distance between the user’s current location and the destination location

Rad(d) {return d * math.pi / 180.0; }, getDistance(lat1, lng1, lat2, Var radLat1 = this.rad (lat1); var radLat1 = this.rad (lat1); var radLat2 = this.Rad(lat2); var a = radLat1 - radLat2; var b = this.Rad(lng1) - this.Rad(lng2); var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); S = s * 6378.137; s = Math.round(s * 10000) / 10000; S = s.tofixed (1) + 'km' // return s} App. GetDistance (app. GlobalData userLat, app. GlobalData. UserLong, "31.929074190568766", "118.8757504898559");Copy the code

4. Encapsulate the request interface

In my opinion, this operation achieves request interception to a certain extent, which is equivalent to the request interception of VUE’s Axios

app.js wxRequest(method, url, data, callback, errFun) { let baseUrl = 'https://njlingshi.com'; Wx. request({url: baseUrl+ URL, method: method, data: data, header: {'content-type': method == 'GET' || method == 'POST'? 'application/json':'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': this.globalData.token }, dataType: 'json', success: function (res) { if(res.statusCode == 200) { callback(res.data); }else if(res.statuscode == 401){wx.showToast({icon: "none", title: 'Please login! ', }) wx.removeStorageSync('token'); Wx. showToast({icon: "none", title: res.data.errmsg? res.data.errMsg : res.data.message, }) } }, fail: function (err) { console.log(err) errFun(err); }})}, let that = this; app.wxRequest('GET', '/api/getHotList',{}, (res) => { this.setData({ hotList: res.data && res.data.length > 0 ? res.data : [] }) }, (err) => { console.log(err) })Copy the code

5. Some simple pothole avoidance guidelines

  • 1, wx. ShowToast text display is not complete, remove the icon, you can display up to two lines of text, if still not enough, you can write a component to use

  • WXML needs to use indexOf for arrays

  • 1, define a common.wxs in utils

  •         function indexOf(arr, value) {    
           if (arr.indexOf(value) < 0) {        
                return false;    
           } else {        
                return true;    
           }
      }
      module.exports.indexOf = indexOf;
    Copy the code
  • wxml: 

    {{item}} {{item}} {{item}} {{item}} {{item}} {{item}} {{item}

  • Common styles can be written in app.wxss to reduce duplicate styles; Public JS can be placed in app.js

Write so much first, later update again, feel useful friend point like ah ~