uni-app关于微信小程序授权手机号

797 阅读1分钟

注:本文参考:www.jb51.net/article/179…

image.png

一、在pages.json上注册路由把地址给后端

image.png

二、由于需要按钮事件才能触发手机号授权弹窗,所以做一个mask询问是否愿意授权

image.png image.png

三、onload里获取扫码值

image.png

onLoad(option) {
			let that = this;
			uni.login({
			  provider: 'weixin',
			  success: function (res) {
				that.code = res.code;
			  }
			});
			if(util.getStorageSync("saleInviteTel")!=""){
				this.mask = false;
			}
			const scene = decodeURIComponent(option.scene);//id=34755&type=1
			let obj = {};
			scene.split("&").forEach(item => {
				let field = item.split("=")[0];
				let value = item.split("=")[1];
				obj[field] = value;
			})
			// let url, params;
			if (obj.type === "1") { //经纪人
				this.url = `contractSale/getScanContractSale/${obj.id}`;
				// if(util.getStorageSync("saleInviteTel")!=""){
					this.mask = false;
					this.getData(this.url);
				// }
			} else if (obj.type === "2") { //客户
				this.url = "noAuth/getCustomersContractSale";
				this.params.id = obj.id;
				if(util.getStorageSync("saleInviteTel")!=""){
					this.mask = false;
					this.params.tel = util.getStorageSync("saleInviteTel");
					this.getData(this.url,this.params);
				}
					// tel: util.getStorageSync("customersTel")
				// this.getData(url, params);
			}

		},

四、点击同意后弹出

image.png 五、点击允许

image.png

getPhoneNumber (e) {
				this.mask = false;
			  let that = this;
			  if (e.detail.errMsg !== "getPhoneNumber:ok") {
			    return;
			  }
			  
			  if (util.getStorageSync("saleInviteTel") != "") {
				  this.mask = false
				  this.getData(this.url,this.params)
			    return;
			  }
			  uni.checkSession({
			    success (res) {
			      // session_key 未过期,并且在本生命周期一直有效
			      that.DecryptData(e);
			    },
			    fail (err) {
			      // session_key 已经失效,需要重新执行登录流程
			      uni.login({
			        provider: 'weixin',
			        success: function (res) {
			          that.code = res.code;
			        }
			      });
			    }
			  })
			},

六、解密

image.png

async DecryptData (e) {
			  let that = this;
			  await api.commonAjax({
			    AjaxUrl: 'noAuth/decryptData',
			    method: 'GET',
				contentType:"application/json",
			    query: {
			      encryptedData: e.detail.encryptedData,
			      iv: e.detail.iv,
			      code: that.code
			    }
			  },
			    function (json) {
			      if (json.code == 200) {
			        util.setStorageSync("saleInviteTel", json.data);
					that.params.tel=json.data;
					that.getData(that.url, that.params);			        
			      } else {
			        setTimeout(() => {
			          uni.showToast({
			            title: json.message,
			            duration: 2000,
			            icon: "none"
			          });
			
			        })
			
			      }
			    }
			  );
			},