• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

微信小程序获取UnionId等相关信息

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 public class WxHelper
    {
        //微信小程序
        private static string _appid = ConfigurationManager.AppSettings["wxAPPID"];
        private static string _appSecret = ConfigurationManager.AppSettings["wxAppSecret"];

        //APP微信ID
        private static string id = ConfigurationManager.AppSettings["appWxAPPID"];
        // APP 微信
        private static string secret = ConfigurationManager.AppSettings["appWxAppSecret"];
         
        //微信公众号
        private static string _gzhappid = ConfigurationManager.AppSettings["wxgzhAPPID"];
        private static string _gzhappSecret = ConfigurationManager.AppSettings["wxgzhAppSecret"];

        public static WxSession Code2Session(string code)
        {
            var url =
                $"https://api.weixin.qq.com/sns/jscode2session?appid={_appid}&secret={_appSecret}&js_code={code}&grant_type=authorization_code";
            try
            {
                var request = WebRequest.Create(url);
                using (var response = request.GetResponse())
                {
                    using (var rs = response.GetResponseStream())
                    {
                        using (var s = new System.IO.StreamReader(rs))
                        {
                            return s.ReadToEnd().JsonTo<WxSession>();
                        }
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
          
        #region 获取微信手机号
        /// <summary>
        /// 获取微信手机号
        /// </summary>
        /// <param name="aesIv">向量</param>
        /// <param name="encryptedData">encryptedData</param>
        /// <param name="code">加密数据</param>
        /// <returns></returns>
        ///框架引用,用于返回Json串
        public static string GetPhoneNumber(string aesIv, string encryptedData, string code)
        {
            try
            {
                #region 获取Session_Key

                var AppId = _appid; //微信小程序AppID
                var Secret = _appSecret;  //微信小程序Secret
                string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId + "&secret=" + Secret + "&js_code=" + code + "&grant_type=authorization_code";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";
                request.ContentType = "text/html;charset=utf-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                var obj = new
                {
                    data = retString,
                    Success = true
                };
                Formatting microsoftDataFormatSettings = default(Formatting);
                string result = JsonConvert.SerializeObject(obj, microsoftDataFormatSettings);
                //序列化获取session_key
                v_petminiuserdetails item = JsonConvert.DeserializeObject<v_petminiuserdetails>(retString);

                #endregion

                #region 获取微信绑定手机号

                //判断是否是16位 如果不够补0
                //text = tests(text);
                //16进制数据转换成byte
                byte[] encryptedDatas = Convert.FromBase64String(encryptedData); // strToToHexByte(text);
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(item.session_key); // Encoding.UTF8.GetBytes(AesKey);
                rijndaelCipher.IV = Convert.FromBase64String(aesIv);// Encoding.UTF8.GetBytes(AesIV);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryptedDatas, 0, encryptedDatas.Length);
                string results = Encoding.Default.GetString(plainText);

                //序列化获取手机号码
                wechardetails<watermark> getPhone = JsonConvert.DeserializeObject<wechardetails<watermark>>(results);
                //getPhone.watermark.openid = item.openid; //获取用户OpenID
                return getPhone.phoneNumber;

                #endregion

            }
            catch (Exception ex)
            {
                return null;

            }
        }
        #endregion


        private static string DecodeData(string sessionKey, string iv, string encryptedData)
        {
            var dataBuffer = Convert.FromBase64String(encryptedData);
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Key = Convert.FromBase64String(sessionKey);
            rijndaelCipher.IV = Convert.FromBase64String(iv);
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;

            ICryptoTransform transform = rijndaelCipher.CreateDecryptor(rijndaelCipher.Key, rijndaelCipher.IV);
            byte[] plainText = transform.TransformFinalBlock(dataBuffer, 0, dataBuffer.Length);
            string result = Encoding.UTF8.GetString(plainText);
            return result;
        }

        /// <summary>
        ///  获取微信手机号
        /// </summary>
        /// <param name="sessionKey"></param>
        /// <param name="iv"></param>
        /// <param name="encryptedData"></param>
        /// <returns></returns>
        public static string GetUnionId(string sessionKey, string iv, string encryptedData)
        {
            string result = DecodeData(sessionKey, iv, encryptedData);
            Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            var wxUnion = Convert.ToString(jobject["phoneNumber"]);
            return wxUnion;
        }

        /// <summary>
        ///  获取微信UnionId
        /// </summary>
        /// <param name="sessionKey"></param>
        /// <param name="iv"></param>
        /// <param name="encryptedData"></param>
        /// <returns></returns>
        public static string GetUnionIdYjsq(string sessionKey, string iv, string encryptedData)
        {
            string result = DecodeData(sessionKey, iv, encryptedData);
            Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            var wxUnion = Convert.ToString(jobject["unionId"]);
            return wxUnion;
        }

        /// <summary>
        /// 获取微信信息
        /// </summary>
        /// <param name="sessionKey"></param>
        /// <param name="iv"></param>
        /// <param name="encryptedData"></param>
        /// <returns></returns>
        public static Newtonsoft.Json.Linq.JObject wxUserInfo(string sessionKey, string iv, string encryptedData)
        {
            string result = DecodeData(sessionKey, iv, encryptedData);
            Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            return jobject;
        }


        /// <summary>
        /// 获取微信access_token
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static WxTokenSession GetAccessToken(string code)
        {

            var url =
                $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={_appid}&secret={_appSecret}&code={code}&grant_type=authorization_code";
            try
            {
                var request = WebRequest.Create(url);
                using (var response = request.GetResponse())
                {
                    using (var rs = response.GetResponseStream())
                    {
                        using (var s = new System.IO.StreamReader(rs))
                        {
                            return s.ReadToEnd().JsonTo<WxTokenSession>();
                        }
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        public class WxSession
        {
            public string openid { get; set; }
            public string session_key { get; set; }
            public string errcode { get; set; }
            public string errMsg { get; set; }
            public string unionid { get; set; }
        }

        public class WxTokenSession
        {
            public string access_token { get; set; }
            public string expires_in { get; set; }
            public string refresh_token { get; set; }
            public string openid { get; set; }
            public string scope { get; set; }
            public string unionid { get; set; }
            public string errcode { get; set; }
            public string errMsg { get; set; }
        }

        //实体Model

        //获取用户openid、session_key
        public class v_petminiuserdetails
        {
            /// <summary>
            /// 微信用户openId
            /// </summary>
            public string openid { get; set; }
            /// <summary>
            /// session_key
            /// </summary>
            public string session_key { get; set; }
        }
        //获取用户手机号
        public class wechardetails<T>
        {
            /// <summary>
            /// 手机号
            /// </summary>
            public string phoneNumber { get; set; }
            /// <summary>
            /// 区域手机号
            /// </summary>
            public string purePhoneNumber { get; set; }
            /// <summary>
            /// 区码
            /// </summary>
            public string countryCode { get; set; }

            public T watermark { get; set; }
        }

        public class watermark
        {
            /// <summary>
            /// 时间戳
            /// </summary>
            public string timestamp { get; set; }
            /// <summary>
            /// 用户appid
            /// </summary>
            public string appid { get; set; }
            /// <summary>
            /// 用户openid
            /// </summary>
            public string openid { get; set; }
        }
    }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
关于微信小程序扫普通链接二维码打开小程序的本机Debug发布时间:2022-07-18
下一篇:
基于微信小程序的点餐系统发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap