第一步:获取微信登录中的code

onLoad() {
			const self = this
			uni.login({
				provider: 'weixin',
				success: loginRes => {
					console.log(loginRes.code,111);
					self.getOAuth2UserInfo(loginRes.code) ;
				}
			});
		},

注:在onload 中 执行获取code

第二部:通过后台写的接口获取sessionKey


			getOAuth2UserInfo(code) {
				let self = this;
				self.$common.ajax({
					url: '/wx/miniapp/getOAuth2UserInfo',
					type: 'get',
					data: {code},
					isToken:true,
					success(data) {
						console.log(data,'获取sessionKey');
						self.decodePhoneParams.sessionKey = data.data.sessionKey;
					}
				})
			},

注:通过第一步拿到的code,执行函数获得sessionKey;

第三部:通过拿到的sessionKey,点击按钮获取encryptedData和iv; 通过这三个参数执行后台给的接口直接获取到手机号:

html中点击按钮

<button class="phoneSQ" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号授权</button>

			// 获取手机号
			getPhoneNumber(e) {
				let self = this;
				self.decodePhoneParams.encryptedData = e.detail.encryptedData;
				self.decodePhoneParams.ivStr = e.detail.iv;
				console.log(self.decodePhoneParams,222);
				self.$common.ajax({
					url: '/wx/miniapp/getEncrypted2PhoneNum',
					type: 'post',
					isForm:true,
					data: self.decodePhoneParams,
					success(data) {
						if(data.code == 200){
							self.mobile = data.data;
						}
						console.log(data,'获取手机号');
					}
				})
			},

注意:一定按照执行步骤,因为有可能获取到的code过期。所以通过第一步拿到code以后就直接执行函数拿到sessionKey(因为这个不会过期!);

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐