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

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

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

2.请求接口时先获取Access_token

        #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.授权时获取手机号

        #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请求方法

 #region 提交Post请求
        /// 
        /// 提交Post请求
        /// 
        /// 参数集合
        /// URL
        /// 
        /// 
        /// 
        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

你可能感兴趣的:(.NETCORE,.net,微信小程序,小程序)