微信小程序----手机号授权操作
实现功能:通过点击授权按钮手机号会自动加载到对应的文本框中
下面以预约记录的模块来展示:
后端代码
手机号授权的操作步骤都是一样的可以直接复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public string GetPhone( string code, string encryptedData, string iv, int userid) { try { ConfigInfo info = ConfigInfo.GetConfig(); string url = string .Format($ "https://api.weixin.qq.com/sns/jscode2session?appid={info.AppID}&secret={info.AppSecret}&js_code={code}&grant_type=authorization_code" ); string str = NetHelper.Get(url); if (str.Contains( "invalid code" )) throw new Exception( "code失效" ); JObject jobj = JObject.Parse(str); string sessionKey = jobj.SelectToken( "session_key" ).ToString(); if ( string .IsNullOrEmpty(sessionKey)) throw new Exception( "获取session_key失败" ); AESHelper.AesIV = iv; AESHelper.AesKey = sessionKey; string result = AESHelper.AESDecrypt(encryptedData); //解析修改会员的手机号 JObject json = JObject.Parse(result); //string pureNumber = json.SelectToken("purePhoneNumber").ToString(); return result; } catch (Exception ex) { return "授权失败:" + ex.Message; } } |
html
在button按钮中加入ope-type
1 | <button style= "width:50px;" open-type= "getPhoneNumber" bindgetphonenumber= "getNumberClick" >授权</button> |
js
在data中设置数据
调用button定义的按钮设置手机号操作,线条中的内容是为为例把数值提交到表单写的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //获取手机号 getNumberClick(e) { var _this = this ; var userInfo = _this.data.info; e.detail.code = _this.data.mcode; account.getPhone(e, res => { // 存储手机号 var uform = {} if (res.indexOf( '授权失败' ) != -1 || res == null ) { wx.showToast({ title: '授权失败' , }) } else { res = JSON.parse(res); uform.mobile = res.phoneNumber; // console.info(uform.mobile) _this.setData({ 'form.mobile' :uform.mobile }) } wx.setStorageSync( 'phone' , res.phoneNumber); }) }, |
在onshow里面设置数据
在utils中设置获取后端接口的操作
可以去微信开发者工具参考
https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
分类:
项目开发 / 后台开发
, 项目开发 / 微信小程序开发
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话