.NET6使用微信小程序授权登录,获取手机号

1.在appsettings配置你的小程序配置信息

csharp 复制代码
  //微信小程序信息配置
  "WechatConfig": {
    "appid": "", //小程序ID
    "secret": "" //小程序秘钥
  },

2.请求接口时先获取Access_token

csharp 复制代码
        #region 获取小程序的Access_token
        public object GetAccess_token(string appid, string secret)
        {
            string strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl);
            req.Method = "GET";
            req.ContentType = "textml;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string jsonData = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            string jsonSr = jsonData;
            JObject jsons = JObject.Parse(jsonSr);
            string accesstoken = jsons["access_token"].ToString();
            return accesstoken;
        }
        #endregion

3.授权时获取手机号

csharp 复制代码
        #region 获取微信绑定手机号
        public  object GetPhoneNumber(string code, string appid, string secret)
        {
            string errCode = "";
            try
            {
                var accesstoken = GetAccess_token(appid, secret);
                string serviceAddress = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accesstoken;

                JObject codes = new JObject();
                codes["code"] = code;
                string sendData = JsonConvert.SerializeObject(codes);
                //换成Post请求方式
                string jsonString = UrlPost(sendData, serviceAddress);
                dynamic model = JToken.Parse(jsonString) as dynamic;
                JObject json = JObject.Parse(jsonString);
                errCode = json["errcode"].ToString();
                string purePhoneNumber = json["phone_info"]["phoneNumber"].ToString();
                //签发token
                //string token;
                //_authenservice.IsAuthenticated(code, out token);
                return new { Code = 200, Msg = "获取成功", Tel = purePhoneNumber, Token = token };
            }
            catch (Exception e)
            {
                return new { Code = 0, Msg = "获取失败" + e.Message };
            }
        }
        #endregion

4.微信接口要求必须使用Post请求方法

csharp 复制代码
 #region 提交Post请求
        /// <summary>
        /// 提交Post请求
        /// </summary>
        /// <param name="parameterData">参数集合</param>
        /// <param name="serviceUrl">URL</param>
        /// <param name="ContentType"></param>
        /// <param name="Accept"></param>
        /// <returns></returns>
        public static string UrlPost(string parameterData, string serviceUrl, string ContentType = "application/json", string Accept = "application/json")
        {
            //先根据用户请求的uri构造请求地址
            //string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);

            //创建Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //把用户传过来的数据转成"UTF-8"的字节流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(parameterData);

            myRequest.Method = "POST";
            //myRequest.Accept = "application/json";
            //myRequest.ContentType = "application/json";  // //Content-Type: application/x-www-form-urlencoded 
            myRequest.AutomaticDecompression = DecompressionMethods.GZip;
            myRequest.Accept = Accept;
            //myRequest.ContentType = ContentType;
            myRequest.ContentType = "application/json; charset=UTF-8";
            myRequest.ContentLength = buf.Length;
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;

            //myRequest.Headers.Add("content-type", "application/json");
            //myRequest.Headers.Add("accept-encoding", "gzip");
            //myRequest.Headers.Add("accept-charset", "utf-8");

            //发送请求
            Stream stream = myRequest.GetRequestStream();
            stream.Write(buf, 0, buf.Length);
            stream.Close();

            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
            string returnData = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            reader.Close();
            myResponse.Close();
            return returnData;
        }
        #endregion

//小程序官方文档

https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html

相关推荐
Cincoze-Johnny1 小时前
Windows系统-应用问题全面剖析Ⅴ:德承工控机DA-1000在Windows操作系统下[安装.NET Framework]教程
.net
沉默-_-2 小时前
微信小程序网络请求 wx.request 详解
网络·学习·微信小程序·小程序
2501_915909063 小时前
设置了 SSL Pinning 与双向 TLS 验证要怎么抓包
网络·网络协议·ios·小程序·uni-app·iphone·ssl
沉默-_-4 小时前
微信小程序页面配置详解
学习·微信小程序·apache·微信开发者工具
黑夜中的潜行者6 小时前
构建高性能 WPF 大图浏览器:TiledViewer 技术解密
性能优化·c#·.net·wpf·图形渲染
龙兵科技小付说7 小时前
不同价格的上门做饭小程序APP都有什么功能?
小程序·软件开发·上门做饭
初九之潜龙勿用9 小时前
C#实现导出Word图表通用方法之散点图
开发语言·c#·word·.net·office·图表
2501_916007479 小时前
如何查看 iOS 设备系统与硬件信息,iOS系统信息显示工具
android·ios·小程序·https·uni-app·iphone·webview
逆龙泰氽10 小时前
微信小程序开发04-1(小程序API)
微信小程序·小程序
说私域10 小时前
AI智能名片S2B2C商城小程序在微商中的应用与影响
大数据·人工智能·小程序·流量运营