uniapp+.net core 小程序获取手机号
获取手机号
从基础库 2.21.2 开始,对获取手机号的接口进行了安全升级,以下是新版本接口使用指南。(旧版本接口目前可以继续使用,但建议开发者使用新版本接口,以增强小程序安全性)
因为需要用户主动触发才能发起获取手机号接口,所以该功能不由 API 来调用,需用 button 组件的点击来触发。另外,新版本接口不再需要提前调用wx.login
进行登录。
注意:
- 目前该接口针对非个人开发者,且完成了认证的小程序开放(不包含海外主体)。需谨慎使用,若用户举报较多或被发现在不必要场景下使用,微信有权永久回收该小程序的该接口权限;
- 在使用该接口时,用户可使用微信绑定手机号进行授权,也添加非微信绑定手机号进行授权。若开发者仅通过手机号作为业务关联凭证,在重点场景可适当增加短信验证逻辑。
使用方法
需要将 button 组件 open-type
的值设置为 getPhoneNumber
,当用户点击并同意之后,可以通过 bindgetphonenumber
事件回调获取到动态令牌code
,然后把code
传到开发者后台,并在开发者后台调用微信后台提供的 phonenumber.getPhoneNumber 接口,消费code
来换取用户手机号。每个code
有效期为5分钟,且只能消费一次。
注:getPhoneNumber
返回的 code
与 wx.login
返回的 code
作用是不一样的,不能混用。
前端
template
使用getphonenumber获取回调code
//小程序写法 <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button> //uni-app写法 <button class="wx-login" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取手机号</button>
js
调用服务器的url,消费code
来换取用户手机号
methods: { getPhoneNumber: function(e) { var that = this; var userPhone = uni.getStorageSync('userPhone'); if(userPhone != '') { getApp().globalData.userPhone = userPhone; uni.navigateTo({ url: 'personal' }); return; } if (e.detail.errMsg == "getPhoneNumber:ok") { //端口号是由后端服务器生成 wx.request({ url: '后端服务URL', data: { code: e.detail.code }, method: "get", success: function(res) { uni.setStorageSync('userPhone', res.data); getApp().globalData.userPhone = res.data; uni.navigateTo({ url: 'personal' }); }, fail: function(res) { console.log(res.errMsg) } }) } } }
后端
后端使用.net core配置api
appsetting配置
"Wx": { "appid": "", "secret": "", "baseurl": "https://api.weixin.qq.com/", "getToken": "cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", "getuserphonenumber": "wxa/business/getuserphonenumber?access_token={0}" }
Startup.cs
注册HttpClient调用微信API
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("WxClient", config => { config.BaseAddress = new Uri(Configuration["Wx:baseurl"]); config.DefaultRequestHeaders.Add("Accept", "application/json"); }); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { GlobalContext.HttpClientFactory = app.ApplicationServices.GetService<IHttpClientFactory>(); }
GlobalContext.cs
获取token方法与获取手机号方法,通过HTTPClient调用获取Token方法,用Token和Code调用getuserphonenumber获取用户手机号
using System; using System.Reflection; using System.Text; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.Hosting;using Microsoft.AspNetCore.Http; using System.Net.Http; using Newtonsoft.Json; namespace YiSha.Util { public class GlobalContext {public static IHttpClientFactory HttpClientFactory { get; set; } public static IConfiguration Configuration { get; set; }public static string Token { get; set; } public static DateTime TimeOutDate { get; set; } /// <summary> /// 获取Token /// </summary> /// <returns>Item1 Token;Item2 是否成功</returns> public static Result GetToken() { //判断Token是否存在 以及Token是否在有效期内 if (string.IsNullOrEmpty(Token) || TimeOutDate > DateTime.Now) { //构造请求链接 var requestBuild = Configuration["Wx:getToken"]; requestBuild = string.Format(requestBuild, Configuration["Wx:appid"], Configuration["Wx:secret"] ); using (var wxClient = HttpClientFactory.CreateClient("WxClient")) { var httpResponse = wxClient.GetAsync(requestBuild).Result; var dynamic = JsonConvert.DeserializeObject<dynamic>( httpResponse.Content.ReadAsStringAsync().Result ); if (dynamic.errmsg == null)//刷新Token { Token = dynamic.access_token; var expires_in = Convert.ToDouble(dynamic.expires_in); TimeOutDate = DateTime.Now.AddSeconds(expires_in); return new Result(Token); } else { return new Result(errMsg:dynamic.errmsg); } } } else { return new Result(Token); } } public static Result GetUserPhoneNumber(string code) { var token = GetToken(); if(!token.isSuccess) { return token; } //构造请求链接 var requestBuild = Configuration["Wx:getuserphonenumber"]; requestBuild = string.Format(requestBuild, token.data); //建立HttpClient using (var wxClient = HttpClientFactory.CreateClient("WxClient")) { string content = $"{{\"code\":\"{code}\"}}"; byte[] data = Encoding.UTF8.GetBytes(content); var bytearray = new ByteArrayContent(data); var httpResponse = wxClient.PostAsync(requestBuild, bytearray).Result; var dynamic = JsonConvert.DeserializeObject<dynamic>( httpResponse.Content.ReadAsStringAsync().Result ); if (dynamic.errmsg == "ok") return new Result(dynamic.phone_info.phoneNumber.ToString()); else return new Result(errMsg: dynamic.errmsg.ToString()); } } /// <summary> /// 返回消息 /// </summary> public class Result { public Result() { } /// <summary> /// 正确 /// </summary> /// <param name="data"></param> public Result(string data) { this.data = data; this.isSuccess = true; } /// <summary> /// 错误 /// </summary> /// <param name="errMsg"></param> /// <param name="isSuccess"></param> public Result(string errMsg,bool isSuccess = false) { this.errMsg = errMsg; this.isSuccess = isSuccess; } public string data { get; set; } public string errMsg { get; set; } public bool isSuccess { get; set; } } } }
调用
[HttpGet] public string GetPhone(string code) { var phone = GlobalContext.GetUserPhoneNumber(code); if(!phone.isSuccess) { //错误处理 } return phone.data; }
获取截图
文档传送门:
获取手机号:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html