


A brief discussion on how to authorize login to the mini program and obtain information and mobile phone number
Jul 23, 2021 am 10:53 AMThis article will share with you how to implement authorized login in WeChat applet and obtain user information and mobile phone number.
Relevant learning recommendations: Mini Program Development Tutorial
Summary, the new function of obtaining the user’s mobile phone number is used, which uses the information about obtaining For the functions of user information and user mobile phone number, when I first wrote it, I found that I wrote two buttons on a login page. The logic of obtaining the mobile phone number is to jump to the homepage when the user clicks authorize, and when the user clicks to reject the pop-up prompt, finally I found that it may be a limitation on WeChat. There is a prompt when debugging on the simulator. If you click on the reject button on a real machine, it will still work. I couldn’t help but write another set about judging the authorization of mobile phone numbers when users enter a certain details page. I will record it here. I hope it can be solved. Help friends in need and see the effect first! ! !
1. Global judgment
App({ onLaunch: function () { //調(diào)用API從本地緩存中獲取數(shù)據(jù) // 展示本地存儲(chǔ)能力 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) var that = this; //獲取用戶本地是否是第一次進(jìn)入新版本 var versions = wx.getStorageSync('versions'); console.log('versions:' + versions); //判斷是不是需要授權(quán) if (versions == '1'){ // 已經(jīng)授權(quán),可以直接調(diào)用 getUserInfo 獲取頭像昵稱,不會(huì)彈框 wx.getUserInfo({ success: function (res) { that.globalData.userInfo = res.userInfo console.log(that.globalData.userInfo) }, fail: function () { wx.redirectTo({ url: '../wurui_house/pages/login/index', }) } }) }else{ //未授權(quán), 跳轉(zhuǎn)登錄頁面 wx.redirectTo({ url: '../wurui_house/pages/login/index', }) } }, onShow: function () { // console.log(getCurrentPages()) }, onHide: function () { // console.log(getCurrentPages()) }, onError: function (msg) { //console.log(msg) }, util: require('we7/resource/js/util.js'), tabBar: { "color": "#123", "selectedColor": "#1ba9ba", "borderStyle": "#1ba9ba", "backgroundColor": "#fff", "list": [ ] }, getLocationInfo: function (cb) { var that = this; if (this.globalData.locationInfo) { cb(this.globalData.locationInfo) } else { wx.getLocation({ type: 'gcj02', // 默認(rèn)為 wgs84 返回 gps 坐標(biāo),gcj02 返回可用于 wx.openLocation 的坐標(biāo) success: function (res) { that.globalData.locationInfo = res; cb(that.globalData.locationInfo) }, fail: function () { // fail }, complete: function () { // complete } }) } }, globalData: { userInfo: null, appid: "", appsecret: "", }, siteInfo: require('siteinfo.js') });
2.Login login page judgment
(1) index.wxml
<view wx:if="{{isHide}}"> <view wx:if="{{canIUse}}"> <view> <image src='../../../we7/resource/images/login.png'></image> </view> <view> <text>請(qǐng)依次允許獲得你的公開信息及手機(jī)號(hào)碼</text> </view> <view class="" > <button class="{{flag?'show':'hide'}}" type="primary" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">{{AuthorizedLogin}}</button> <button class="{{flag?'hide':'show'}}" type="primary" open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">{{UserPhone}}</button> </view> </view> <view wx:else>請(qǐng)升級(jí)微信版本</view> </view>
(4) index.wxss
.header { margin: 90rpx 0 90rpx 50rpx; border-bottom: 1px solid #ccc; text-align: center; width: 650rpx; height: 300rpx; line-height: 450rpx; } .header image { width: 200rpx; height: 200rpx; } .content { margin-left: 50rpx; margin-bottom: 90rpx; } .content text { display: block; color: #9d9d9d; margin-top: 40rpx; } /* .operBtn{ border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx; } .operBtns{ background: #eef0ed !important; border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx; color: #000300 !important; } */ .hide{ border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx; display: none; } .show{ display: block; /* background: #eef0ed !important; */ border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx; /* color: #000300 !important; */ }
(3) index.js
const app = getApp(); Page({ data: { //判斷小程序的API,回調(diào),參數(shù),組件等是否在當(dāng)前版本可用。 canIUse: wx.canIUse('button.open-type.getUserInfo'), isHide: false, AuthorizedLogin: '授權(quán)登錄', UserPhone: '手機(jī)號(hào)授權(quán)', lee: "", flag: true }, onLoad: function() { var that = this; // 查看是否授權(quán) //獲取用戶本地是否是第一次進(jìn)入新版本 var versions = wx.getStorageSync('versions'); if (versions == '1') { wx.getSetting({ success: function(res) { if (res.authSetting['scope.userInfo']) { //調(diào)用共通的登錄方法 app.util.getUserInfo( function(userinfo) { that.setData({ userinfo: userinfo }) }); } else { // 用戶沒有授權(quán) // 改變 isHide 的值,顯示授權(quán)頁面 that.setData({ isHide: true }); } } }); } else { // 用戶沒有授權(quán) // 改變 isHide 的值,顯示授權(quán)頁面 that.setData({ isHide: true }); } }, bindGetUserInfo: function(e) { if (e.detail.userInfo) { //用戶按了允許授權(quán)按鈕 var that = this; let user = e.detail.userInfo; // 獲取到用戶的信息了,打印到控制臺(tái)上看下 console.log("用戶的信息如下:"); console.log(user); //授權(quán)成功后,通過改變 isHide 的值,讓實(shí)現(xiàn)頁面顯示出來,把授權(quán)頁面隱藏起來 that.data.lee if (that.data.lee == '') { wx.showToast({ icon: "none", title: '請(qǐng)繼續(xù)點(diǎn)擊獲取手機(jī)號(hào)', }), that.setData({ isHide: true, flag: (!that.data.flag), lee: true }) that.wxlogin(); } else if (!that.data.lee) { wx.switchTab({ url: "/wurui_house/pages/index/index" }) } } else { //用戶按了拒絕按鈕 wx.showModal({ title: '警告', content: '您點(diǎn)擊了拒絕授權(quán),將無法進(jìn)入小程序,請(qǐng)授權(quán)之后再進(jìn)入!!!', showCancel: false, confirmText: '返回授權(quán)', success: function(res) { // 用戶沒有授權(quán)成功,不需要改變 isHide 的值 if (res.confirm) { console.log('用戶點(diǎn)擊了“返回授權(quán)”'); } } }); } }, wxlogin: function() { //獲取用戶的openID var that = this; //調(diào)用共通的登錄方法 app.util.getUserInfo( function(userinfo) { that.setData({ userinfo: userinfo }) }); }, getPhoneNumber: function(e) { //點(diǎn)擊獲取手機(jī)號(hào)碼按鈕 var that = this; that.data.lee if (that.data.lee == '') { wx.showToast({ icon: "none", title: '請(qǐng)先點(diǎn)擊獲取用戶信息', }) return } else { wx.checkSession({ success: function(res) { console.log(e.detail.errMsg) console.log(e.detail.iv) console.log(e.detail.encryptedData) var ency = e.detail.encryptedData; var iv = e.detail.iv; var sessionk = that.data.sessionKey; if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { wx.showModal({ title: '警告', content: '您點(diǎn)擊了拒絕授權(quán),部分功能無法使用!!!', showCancel: false, confirmText: '返回授權(quán)', success: function(res) { // 用戶沒有授權(quán)成功,不需要改變 isHide 的值 if (res.confirm) { wx.setStorageSync('enws', '1'); wx.switchTab({ url: "/wurui_house/pages/index/index" }) console.log('用戶點(diǎn)擊了“返回授權(quán)”'); }; } }), that.setData({ modalstatus: true, }); } else { that.setData({ lee: false, }); wx.switchTab({ url: "/wurui_house/pages/index/index" }) //同意授權(quán) var userinfo = wx.getStorageSync('userInfo'); app.util.request({ 'url': 'entry/wxapp/saveusermobile', data: { sessionid: userinfo.sessionid, uid: userinfo.memberInfo.uid, iv: iv, encryptedData: ency }, success: function(res) { if (res.data.data.error == 0) { console.log('success' + res.data.data); //用戶已經(jīng)進(jìn)入新的版本,可以更新本地?cái)?shù)據(jù) wx.setStorageSync('versions', '1'); wx.setStorageSync('enws', '2'); } else { //用戶保存手機(jī)號(hào)失敗,下次進(jìn)入繼續(xù)授權(quán)手機(jī)號(hào) wx.setStorageSync('enws', '1'); console.log('fail' + res.data.data); } }, fail: function(res) { console.log('fail' + res); } }); } }, fail: function() { console.log("session_key 已經(jīng)失效,需要重新執(zhí)行登錄流程"); that.wxlogin(); //重新登錄 } }); } } })
2. The mask layer writing method used to determine the mobile phone number authorization of a certain details page
(1) index.html
<code> <!-- 受權(quán)彈框提醒 --> <view class="container"> <view class="float" hidden='{{viewShowed}}'> <view class='floatContent'> <text>允許授權(quán)獲取手機(jī)號(hào)</text> <view class='floatText'> <button bindtap='cancle' class='btn-cancle'>取消</button> <button class='btn-cancle' open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">確認(rèn)</button> </view> </view> </view> </view> </code>
(2) index. wxss
/* 手機(jī)號(hào)授權(quán) */ .float { height: 100%; width: 100%; position: fixed; background-color: rgba(0, 0, 0, 0.5); z-index: 2; top: 0; left: 0; } .floatContent { /* padding: 20rpx 0; */ width: 80%; background: #fff; margin: 40% auto; border-radius: 20rpx; display: flex; flex-direction: column; justify-content: space-around; align-items: center; position: relative; height: 255rpx; } .floatContent text { color: #000; font-size: 40rpx; display: block; margin: 0 auto; position: absolute; top: 50rpx; /* text-align: center; */ /* line-height: 60rpx; */ border-radius: 30rpx; } .floatText{ width: 100%; height: 100rpx; display: flex; justify-content: flex-start; position: absolute; bottom: 0; } .btn-cancle{ line-height: 100rpx; flex: 1; margin: 0; padding: 0; border-radius: none; }
(3) index.js
data: { viewShowed: true, //控制授權(quán)能否顯示 }, cancle: function () { wx.setStorageSync('enws', '2'); this.setData({ viewShowed: true }) }, /** * 生命周期函數(shù)--監(jiān)聽頁面顯示 */ onShow: function () { var enws = wx.getStorageSync('enws'); console.log("enws:", +enws); var that = this; if (enws != '2') { //判斷能否授權(quán) that.setData({ viewShowed: false, }) console.log('判斷能否授權(quán)'); } else { } }, getPhoneNumber: function (e) { //點(diǎn)擊獲取手機(jī)號(hào)碼按鈕 var that = this; wx.checkSession({ success: function (res) { console.log(e.detail.errMsg) console.log(e.detail.iv) console.log(e.detail.encryptedData) var ency = e.detail.encryptedData; var iv = e.detail.iv; var sessionk = that.data.sessionKey; that.setData({ viewShowed: true, }) wx.setStorageSync('enws', '2'); if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { } else { //同意授權(quán) var userinfo = wx.getStorageSync('userInfo'); app.util.request({ 'url': 'entry/wxapp/saveusermobile', data: { sessionid: userinfo.sessionid, uid: userinfo.memberInfo.uid, iv: iv, encryptedData: ency }, success: function (res) { console.log('success' + res); if (res.data.data.error == 0) { console.log('success' + res.data.data); //用戶已經(jīng)進(jìn)入新的版本,可以更新本地?cái)?shù)據(jù) wx.setStorageSync('versions', '1'); } else { //用戶保存手機(jī)號(hào)失敗,下次進(jìn)入繼續(xù)授權(quán)手機(jī)號(hào) } }, fail: function (res) { console.log('fail' + res); } }); } } }); },
Link: https://pan.baidu.com/s/1E7d33scSpk1tiq_Ndium2g
Extraction code: ll9i
After copying this content, open Baidu network disk and download util.js
For more programming-related knowledge, please visit: Programming getting Started! !
The above is the detailed content of A brief discussion on how to authorize login to the mini program and obtain information and mobile phone number. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

With the rapid development of social media, Xiaohongshu has become one of the most popular social platforms. Users can create a Xiaohongshu account to show their personal identity and communicate and interact with other users. If you need to find a user’s Xiaohongshu number, you can follow these simple steps. 1. How to use Xiaohongshu account to find users? 1. Open the Xiaohongshu APP, click the "Discover" button in the lower right corner, and then select the "Notes" option. 2. In the note list, find the note posted by the user you want to find. Click to enter the note details page. 3. On the note details page, click the "Follow" button below the user's avatar to enter the user's personal homepage. 4. In the upper right corner of the user's personal homepage, click the three-dot button and select "Personal Information"

How to set up WeChat to disallow adding via mobile phone number? In WeChat APP, you can disallow adding WeChat via mobile phone number, but most users don’t know how to set it up to not allow WeChat to be added via mobile phone number. Next is WeChat brought by the editor to users It is not allowed to add setting method tutorials through mobile phone numbers. Interested users can come and take a look! Tutorial on how to use WeChat. How to set up WeChat when adding a mobile phone number is not allowed. 1. First open the WeChat APP, enter the main page, click [Me] in the lower right corner to enter, and select the [Settings] function; 2. Then enter the setting function page and find [Friend Permissions] ] Service function; 3. Then on the friend permissions interface, slide the button behind [Verification is required when adding me as a friend]; 4. Finally, on the page shown below, slide [Mobile Phone Number]

The +86 in front of the mobile phone number refers to China's international dialing code. When dialing a domestic mobile phone in China, adding "+86" is the same as not adding it; and the international telephone area code is assigned by the International Telecommunications Union according to the "E.164" standard. Country codes; all numbers are prefix numbers, which means these numbers are used to "dial" the destination country.

In the digital age, Xiaohongshu has become a platform for many people to share their lives and discover good things. Over time, we may need to change the mobile phone number on the account. So, how to change Xiaohongshu’s mobile phone number? 1. How to change the mobile phone number of Xiaohongshu account? 1. Log in to your Xiaohongshu account and enter the “My” page. 2. Click "..." in the upper right corner and select "Settings". 3. On the settings page, find the "Account and Security" option and click to enter. 4. On the Account and Security page, find the "Mobile Phone Number" option and click to enter. 5. At this time, the page will display the current mobile phone number, click "Change Mobile Number". 6. Enter the new mobile phone number, receive the verification code, and fill it out. 7. Set a new password to ensure account security. 8. After completing the above steps,

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

Meituan APP is a super reliable food delivery service software. It has rich and diverse functions. Everyone can operate it for free and complete various tasks. You can all live a better life and save a lot. Some unnecessary troubles, there are a lot of merchants here for everyone to choose from, and some merchants here provide you with some group buying services. If you do group buying, they can help you save more. The money is super value for money. Of course, when you use this platform, you may need to bind some of your own information, especially your phone number. If your phone number is changed, , you must change the binding in time. The specific operation method is as follows, very

Douyin is a popular short video platform, and many people may already have their own Douyin account. However, sometimes we may need to apply for a new Douyin account, but for users who already have a Douyin account, it may not be clear how to proceed. So, how do users who already have a Douyin account apply for a new one? 1. How to apply for a new account if I already have a Douyin account? If you already have a Douyin account, if you want to apply for a new Douyin account, you can try the following methods: In order to register a new Douyin account, you can consider using a different mobile phone number. Douyin stipulates that each mobile phone number can only register one account, so you can use the mobile phone numbers of family members and friends, or if you have multiple mobile phone numbers, directly use another mobile phone number to register. This will prevent your account from being blocked
