.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

相关推荐
小泽呀x2 小时前
微信小程序中使用离线版阿里云矢量图标
微信小程序·小程序
fakaifa2 小时前
CRMEB Pro版v3.1源码全开源+PC端+Uniapp前端+搭建教程
前端·小程序·uni-app·php·源码下载
托马斯-酷涛3 小时前
小程序源码-模版 100多套小程序(附源码)
小程序
小蒜学长5 小时前
springboot基于SpringBoot的企业客户管理系统的设计与实现
java·spring boot·后端·spring·小程序·旅游
工业互联网专业5 小时前
Python毕业设计选题:基于Django+uniapp的公司订餐系统小程序
vue.js·python·小程序·django·uni-app·源码·课程设计
多客软件佳佳7 小时前
校园交友系统的设计与实现(开源版+三端交付+搭建+售后)
小程序·前端框架·uni-app·开源·php·交友
zhouang7703778 小时前
uniapp+vue2 设置全局变量和全局方法 (兼容h5/微信小程序)
微信小程序·小程序·uni-app
Crazy Struggle10 小时前
.NET 8 强大功能 IHostedService 与 BackgroundService 实战
c#·.net·.net core
说私域11 小时前
基于社交关系的电商平台发展与创新:以微店买家版为例兼论开源 AI 智能名片 2 + 1 链动模式 S2B2C 商城小程序
人工智能·小程序
番茄Salad11 小时前
使用Java绘制图片边框,解决微信小程序map组件中marker与label层级关系问题,label增加外边框后显示不能置与marker上面
微信小程序·小程序