实现微信小程序授权获取手机号登录(c#后端代码附上 少爷接收)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、不多说上代码(html)
  • 二、js
    • 2.用code拿到sessionkey和optionid的接口
    • 3、我们拿到sessionkey就要去解密手机号了
  • 总结


前言

先准备微信认证哦~
我们的步骤:
1、用户点击手机号触发wx.login去获取code
2、通过code去换取openid和sessionkey
3、通过sessionkey去解密用户手机号
注意:第一步骤也可用其他方法

一、不多说上代码(html)

 <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" bindtap="hideModal" bindtap="getUserProfile" >授权微信手机号button>

二、js

getPhoneNumber(e) {
    var that = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      wx.showLoading({ title: "登录中" })
      wx.login({  //请求得到code
        success:function(res){
          console.log("code====="+res.code)
          if(res.code){
            wx.request({
              url: 'xxxxxx',  //通过code获取到sessionkey	接口我会放到后面
              data:{
                code:res.code
              },
              success:function(res){
                console.log("sessionkey======="+res.data)
                var sess=res.data;  //拿到sessionkey
               wx.checkSession({
                 success: (res) => {
                  wx.request({
                    url: "https://www.meirilinggong.com/Wxdrop/getPhoneNumber", //通过iv data key拿到手机号并解密
                    data: {
                      aesIv: e.detail.iv,
                      encryptedData: e.detail.encryptedData,
                      session_key:sess,
                    },
                    method: "POST",
                    success: function(res) {
                      console.log(res.data)
                    }
                  });
                 },
                 fail:function(res){
                   console.log(res)
                 }
               })
              }
            })
            
          }else{
            console.log("用户登录状态失败")
          }
        }
      })
    }
  },

2.用code拿到sessionkey和optionid的接口

 /// 
        /// 获取OpenID、session_key
        /// 
        /// 
        /// 
        public string wxlogin(string code)
        {
            ActionJson<string> actionJson = new ActionJson<string>()
            {
                status = 200,
                message = ""
            };
            try
            {
                //获取AccessToken
                string AccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
                string AccessTokenResult = RequestUrl(string.Format(AccessTokenUrl, AppID, AppSecret, code), "GET");
                string AccessToken = GetJsonValue(AccessTokenResult, "access_token");
                string ExpiresIn = GetJsonValue(AccessTokenResult, "expires_in");
                string RefreshToken = GetJsonValue(AccessTokenResult, "refresh_token");
                string OpenID = GetJsonValue(AccessTokenResult, "openid");
                string session_key = GetJsonValue(AccessTokenResult, "session_key");
                string ErrCode = GetJsonValue(AccessTokenResult, "errcode");
                string ErrMsg = GetJsonValue(AccessTokenResult, "errmsg");


                return session_key;
            }
            catch (Exception ex)
            {
                actionJson.status = 400;
                actionJson.message = ex.Message;
            }
            return "";
        }
          private static string RequestUrl(string url, string method)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = method;
            request.ContentType = "text/html";
            request.Headers.Add("charset", "utf-8");

            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            return content;
        }


        private static string GetJsonValue(string jsonStr, string key)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim('"') + "\"";
                int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗号,若是最后一个,截“}”号,取最小值
                    int end = jsonStr.IndexOf(',', index);
                    if (end == -1)
                    {
                        end = jsonStr.IndexOf('}', index);
                    }

                    result = jsonStr.Substring(index, end - index);
                    result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
                }
            }
            return result;
        }

3、我们拿到sessionkey就要去解密手机号了

注意注意注意:session有时候可能会因为转义出现\(反斜杠)的符号,我们需要把他替换掉。否则拿到手机号失败的

 /// 
        /// 微信授权 解码获得用户手机号
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public string getPhoneNumber(string encryptedData, string aesIv, string session_key, string wechatId)
        {

            try
            {
                session_key = session_key.Replace("\\", "");
                byte[] encryData = Convert.FromBase64String(encryptedData);
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(session_key);
                rijndaelCipher.IV = Convert.FromBase64String(aesIv);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);

                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                string phoneNumber = model.phoneNumber;
                //return model.phoneNumber;
                if (string.IsNullOrEmpty(phoneNumber))
                {
                    return "";
                }
                return phoneNumber;
            }
            catch (Exception ex)
            {
            }
            return "";
        }

总结

1、在微信认证之后 我们可以直接wx.login拿到code
2、通过code我们可以拿到很多必要参数(参数最好后台获取、务必不要在前端直接拿)安全性第一
3、通过拿到的sessionkey去换取我们需要解码的手机号
4、解码成功之后就是对比数据库啦

个人见解 有问题勿喷~

你可能感兴趣的:(小程序,c#,小程序)