Those who have done, know and understand wechat mini program know that if your small program application needs to obtain wechat user information data needs to be agreed by the user, that is, the user is authorized, if the user is not authorized, then you can not get the user’s information. Many of us also know that nowadays we don’t need to carry anything, but we are not allowed to carry mobile phones, because mobile phones are all we have, whether it is wallet, id, etc. So security and privacy is a touchy subject.

Small program to do so is to protect the privacy of the user data, early development of small programs are known, small program authorization in the middle of the interface was changed, when a lot of people ridicule, anyway change and did not change are the same, do anything will be ridiculed.

In my opinion, the practice of small program is quite good, after all, the user’s privacy or users themselves to make decisions, especially the recent headlines and Tencent development data between the avatar and other information events, this is more needed.

Today we will look at how to do a small program authorization package, encapsulation here is mainly for small program applications must be wechat user data, so it is not authorized to use.

Structure of the building

First we need to add an authorized component in the applets component directory, the basic structure is as follows:

Then create a new page for testing the component as follows:

The above code json and WXML file is not shown in detail, you should remember to introduce components and add components in WXML tags, if not very clear you can see the use of wechat applet components.

The basic structure of a component

The interface of the component is mainly to imitate the style of the authorization popup of wechat mini program, so I will make one according to this style, as follows:

<view class='box' catchtouchmove='true'> <view class='pop'> <view class='top'> <view class='txt'></view> <view </view> <view class='center'> <view Class ='explain'><text> Tujia to obtain the following permissions: </text></view> <view class='tip'> <view class='dian'></view> <text> Allow this application to access your camera function </text></view> </view> <button </button> </view> </view>Copy the code

Have a place to pay attention to the code above is to allow the button, because WeChat small program interface later adjustment must be authorized to use the button to open the Settings interface, and small program authorization API only the user authorization for the first time will pop-up asking, if once refused to authorize, then later you can’t get up authorization plays the window interface, so a problem here, Obviously the official has a good popover can be used, is not to use, must write a. I couldn’t use their stuff, I had to follow their rules, so I had to write my own.

Component styles
.box{ width: 100vw; height: 100vh; position: fixed; top: 0; left: 0; z-index: 999; display: flex; align-items: center; justify-content: center; font-family: 'PingFang SC'; background-color: rgba(0, 0, 0, .4); } .box .pop{ width: 621rpx; height: 522rpx; border-radius: 10rpx; Background - color: RGB (248247249); display: flex; flex-direction: column; justify-content: space-between; } .box .pop .top{ width: 100%; height: 94rpx; display: flex; align-items: center; justify-content: space-between; Border - bottom: 1 the RPX solid RGB (233237245); } .box .pop .top .txt{ font-size: 28rpx; Color: RGB (136136136); width: 128rpx; height: 93rpx; line-height: 93rpx; text-align: center; } .box .pop .top .title{ font-size: 36rpx; font-weight: bold; } .box .pop .center{ width: 100%; flex-grow: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; } .box .pop .center .duoduo{ width: 71rpx; height: 71rpx; border-radius: 50%; margin-bottom: 32rpx; } .box .pop .center .duoduo image{ width: 100%; height: 100%; border-radius: 50%; } .box .pop .center .explain{ font-size: 32rpx; width: 520rpx; text-align: center; Border - bottom: 1 the RPX solid RGB (233237245); padding-bottom: 32rpx; } .box .pop .center .tip{ width: 520rpx; font-size: 28rpx; Color: RGB (136136136); display: flex; align-items: center; margin-top: 32rpx; } .box .pop .center .tip .dian{ width: 9rpx; height: 9rpx; Background - color: RGB (136136136); border-radius: 50%; margin-left: 10rpx; margin-right: 22rpx; } .box .pop .bottom { width: 100%; height: 89rpx; line-height: 89rpx; text-align: center; Border - top: 1 the RPX solid RGB (233237245); font-size: 32rpx; Color: RGB (66169, 31); }Copy the code

Once you have the style, you can see what it looks like.

Popup window is written, the logic of how we write, according to the above mentioned rules you need to first WeChat small program used to own authorization apis to allow the user to select, if the user refuses to write yourself with a popup window to prompt the user authorization, in fact, there will be a problem is when users click on after refusing to play window prompts the user authorization, this is the reason why WeChat why such change, Always give the user pop-up window, so I suggest you do a small program when the design of a tourist state wechat most advocate.

The component logic

First, use the API of wechat applet itself to obtain whether the user has been authorized. The code is as follows:

/** * Check whether the user has authorized a certain permission, if not authorized to call the applets authorization, */ isAuthorize(scope, cb) {let self = this; wx.getSetting({ success(res) { if (! res.authSetting['scope.' + scope]) { wx.authorize({ scope: 'scope.' + scope, success() { return typeof cb == "function" && cb(); }, fail() { self.setAuthTxt(scope); self.callBack = cb; self.setData({ popShow: true }) } }) } else { return typeof cb == "function" && cb(); }}})}Copy the code

Add the above method to the component’s methods, where the callback function is used to handle the logic that needs to be executed for authorization success. The above code we can also see if the authorization failure will call setAuthTxt this function, here the main function is to set up some popover prompt information, set up after the callback save, finally show popover grant. Setting the page prompt message is very simple to set the value of data, as follows:

setAuthTxt(authType) { var authTxt = ''; Switch (authType) {case 'userInfo': authTxt = 'userInfo'; break; Case 'userLocation': authTxt = 'location '; break; Case 'record': authTxt = 'record function '; break; Case 'writePhotosAlbum': authTxt = 'Save to album '; break; Case 'camera': authTxt = 'camera'; break; } this.setData({ authType: authType, authTxt: authTxt }) }Copy the code

If the above content does not correspond to the permission you need to request, please add the format yourself.

Here, we need to modify the structure of the page to add some events to handle authorization operations, as follows:

+ <view class='box' catchtouchmove='true' wx:if='{{popShow}}'> <view class='pop'> <view class='top'> <view </view> <view class='title'> </view> + <view class=' TXT 'bindtap='popClose'> close </view> </view> <view Class ='center'> <view class='explain'><text> < / text > < view > < the view class = 'tip' > < the view class = 'dian "> < / view > + < text > agree this application access to your {{authTxt}} function < / text > < view > < / view > + <button class='bottom' open-type="openSetting" bindOpensetting ="getAuthorizeTool" </button> </view> </view>Copy the code

Then there is the logic for the user to click on permission, as follows:

getAuthorizeTool: function(res) { var scope = 'scope.' + this.data.authType; if (res.detail.authSetting[scope]) { this.setData({ popShow: false }) return typeof this.callBack == "function" && this.callBack(); }}Copy the code

The event handler that closes the popover is added as follows:

popClose() {
      this.setData({
        popShow: false
      })
    }
Copy the code

Now that this component is wrapped, let’s look at how to use it.

Authorize the use of components

The use of components is not described here, you can take a look at the official documentation, mainly introduces several cases of encapsulated components. First, we need to import the component in json file. Then we need to add the component tag in WXML. Here we need to add an ID to the tag so that we can call the event later.

<! --pages/auth/auth.wxml--> <text>pages/auth/auth.wxml</text> <auth id='authorization'></auth>Copy the code

Get the component instance in the call’s either Ready lifecycle as follows:

/** * onReady: function () {this.authorize = this.selectComponent("#authorization"); },Copy the code

Finally, there are calls, which are called in several cases.

Page level call

If a page requires certain permissions, of course, this component is only a simple function at the moment, so in this case even if the user does not authorize the page is already loaded, so it is suitable for use with visitor status. If the user does not have visitor status, either add a page or improve it yourself. The call method is as follows:

  onReady: function () {
    this.authorize = this.selectComponent("#authorization");
    this.authorize.isAuthorize('record', () => {
      console.log('fffffffff')
    })
  },
Copy the code

In fact, it is called after obtaining the component instance

Button level call

The operation of clicking a button can only be performed by obtaining certain permissions, such as clicking a button to record voice. The method is the same as above, but the specific function is called in different places, as follows:

onReady: function () { this.authorize = this.selectComponent("#authorization"); }, / * * * of dealing with the record button click event * / handleRecordButton () {this. The authorize. IsAuthorize (' record ', () => { console.log('fffffffff') }) },Copy the code

These are the two main calls.

Call the effect

There are three cases of effect wind after invoking a component.

Only the built-in authorization of the applet is triggered

In this case, the user invokes the authorization popup of the wechat applet for the first time, and the user is authorized immediately. The effect of this case is as follows:

In the GIF above you can see that the debugger will print out after the authorization, indicating that the authorization was successful.

Deny authorization to trigger custom pop-ups

When the user refuses authorization, it can pop up our custom popup window. In the custom popup window, you can choose to allow or not process. This is mainly what is allowed after a custom popover. The effect is as follows:

The user refused to customize authorization

If the above asynchronous user chooses to close, then the callback will not be executed, just as at the page level mentioned above, with the following effect:

To this authorization component has been packaged to check, if there is any error or insufficient hope we put forward, common learning, communication! You can also add my Vx :w_loading, thank you!